chuyue commited on
Commit
5c6a0e3
·
verified ·
1 Parent(s): 52d5a1d

Upload UltraX models, code and assets

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +5 -0
  2. LICENSE +201 -0
  3. README.md +133 -0
  4. README_ZH.md +128 -0
  5. assets/ultrax-logo.png +3 -0
  6. assets/ultrax_pipeline.png +3 -0
  7. code/requirements.txt +7 -0
  8. code/stage1_model_construction/e2e_refinement/refine_dataset.py +192 -0
  9. code/stage1_model_construction/function_construction/function_construction.py +948 -0
  10. code/stage1_model_construction/model_training/train.sh +40 -0
  11. code/stage1_model_construction/prompt_optimization/api_client.py +150 -0
  12. code/stage1_model_construction/prompt_optimization/config.py +45 -0
  13. code/stage1_model_construction/prompt_optimization/data_sampler.py +113 -0
  14. code/stage1_model_construction/prompt_optimization/evaluator.py +183 -0
  15. code/stage1_model_construction/prompt_optimization/main.py +242 -0
  16. code/stage1_model_construction/prompt_optimization/optimizer.py +672 -0
  17. code/stage1_model_construction/prompt_optimization/refinement_prompt_en.txt +147 -0
  18. code/stage1_model_construction/seed_preprocessing/sliding_window_splitter.py +256 -0
  19. code/stage1_model_construction/sft_data_building/sample_and_format.py +240 -0
  20. code/stage2_large_scale_execution/inference/inference.py +990 -0
  21. code/stage2_large_scale_execution/post_processing/post_process_and_execute.py +821 -0
  22. models/UltraX-No-Instruction/added_tokens.json +28 -0
  23. models/UltraX-No-Instruction/args.json +391 -0
  24. models/UltraX-No-Instruction/chat_template.jinja +89 -0
  25. models/UltraX-No-Instruction/config.json +60 -0
  26. models/UltraX-No-Instruction/generation_config.json +13 -0
  27. models/UltraX-No-Instruction/merges.txt +0 -0
  28. models/UltraX-No-Instruction/model.safetensors +3 -0
  29. models/UltraX-No-Instruction/special_tokens_map.json +31 -0
  30. models/UltraX-No-Instruction/tokenizer.json +3 -0
  31. models/UltraX-No-Instruction/tokenizer_config.json +239 -0
  32. models/UltraX-No-Instruction/trainer_state.json +0 -0
  33. models/UltraX-No-Instruction/training_args.bin +3 -0
  34. models/UltraX-No-Instruction/vocab.json +0 -0
  35. models/UltraX-Preservation-Weighted/added_tokens.json +28 -0
  36. models/UltraX-Preservation-Weighted/args.json +391 -0
  37. models/UltraX-Preservation-Weighted/chat_template.jinja +89 -0
  38. models/UltraX-Preservation-Weighted/config.json +60 -0
  39. models/UltraX-Preservation-Weighted/generation_config.json +13 -0
  40. models/UltraX-Preservation-Weighted/merges.txt +0 -0
  41. models/UltraX-Preservation-Weighted/model.safetensors +3 -0
  42. models/UltraX-Preservation-Weighted/special_tokens_map.json +31 -0
  43. models/UltraX-Preservation-Weighted/tokenizer.json +3 -0
  44. models/UltraX-Preservation-Weighted/tokenizer_config.json +239 -0
  45. models/UltraX-Preservation-Weighted/trainer_state.json +0 -0
  46. models/UltraX-Preservation-Weighted/training_args.bin +3 -0
  47. models/UltraX-Preservation-Weighted/vocab.json +0 -0
  48. models/UltraX/added_tokens.json +28 -0
  49. models/UltraX/args.json +391 -0
  50. models/UltraX/chat_template.jinja +89 -0
.gitattributes CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* 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
 
 
 
 
 
 
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
+ assets/ultrax-logo.png filter=lfs diff=lfs merge=lfs -text
37
+ assets/ultrax_pipeline.png filter=lfs diff=lfs merge=lfs -text
38
+ models/UltraX/tokenizer.json filter=lfs diff=lfs merge=lfs -text
39
+ models/UltraX-No-Instruction/tokenizer.json filter=lfs diff=lfs merge=lfs -text
40
+ models/UltraX-Preservation-Weighted/tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [OpenBMB]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ tags:
6
+ - data-refinement
7
+ - function-calling
8
+ - programmatic-editing
9
+ - pretraining
10
+ pipeline_tag: text-generation
11
+ ---
12
+
13
+ # UltraX
14
+
15
+ <div align="center">
16
+ <img src="assets/ultrax-logo.png" width="500"/>
17
+ </div>
18
+
19
+ <p align="center">
20
+ <b>Refining Pre-Training Data at Scale with Adaptive Programmatic Editing</b>
21
+ </p>
22
+
23
+ <p align="center">
24
+ <a href="">📜 Paper</a> |
25
+ <a href="">💻 Code</a> |
26
+ <a href="">🤗 Datasets</a> |
27
+ <a href="https://huggingface.co/collections/openbmb/ultradata">📦 UltraData Collection</a>
28
+ </p>
29
+
30
+ <p align="center">
31
+ English |
32
+ <a href="README_ZH.md">中文</a>
33
+ </p>
34
+
35
+ ## 📚 Introduction
36
+
37
+ **UltraX** is a function-calling refinement framework for large-scale pre-training data. Instead of end-to-end text rewriting, UltraX trains a lightweight refinement model to predict structured editing operations — including insertion, deletion, and modification — which are then deterministically executed on the original text.
38
+
39
+ This repository provides the **UltraX refinement models**, which are trained via full-parameter SFT to predict cleaning function calls for web-crawled text:
40
+
41
+ | Model | Description |
42
+ |-------|-------------|
43
+ | **UltraX** | Default model: instruction-guided with edit-weighted sampling (main experiment) |
44
+ | **UltraX-No-Instruction** | Ablation variant: trained without system instruction |
45
+ | **UltraX-Preservation-Weighted** | Ablation variant: trained with preservation-weighted sampling (60% keep_all) |
46
+
47
+ ## 🔬 Pipeline Overview
48
+
49
+ <div align="center">
50
+ <img src="assets/ultrax_pipeline.png" width="800"/>
51
+ </div>
52
+
53
+ ## 💡 Model Details
54
+
55
+ All models are trained with the following configuration:
56
+
57
+ | Setting | Value |
58
+ |---------|-------|
59
+ | Training Framework | ms-swift with DeepSpeed ZeRO3 |
60
+ | Training Type | Full-parameter SFT |
61
+ | Max Sequence Length | 20,480 tokens |
62
+ | Learning Rate | 3e-5 (cosine decay, min lr 3e-6) |
63
+ | Warmup Ratio | 0.03 |
64
+ | Precision | bfloat16 |
65
+ | Hardware | 8x GPU |
66
+
67
+ ### Model Variants
68
+
69
+ - **UltraX (Instruction-Guided, Edit-Weighted):** The default configuration. The model is trained with a system instruction that defines the editing operations and cleaning rules, using edit-weighted sampling.
70
+
71
+ - **UltraX-No-Instruction:** Trained without system instruction. Demonstrates that programmatic refinement brings clear gains even without explicit task protocol (Avg: 45.73 vs Raw 45.08), though instruction guidance further improves performance (Avg: 46.14).
72
+
73
+ - **UltraX-Preservation-Weighted:** Trained with preservation-weighted sampling where keep_all accounts for 60% of training data. Shows stronger performance on certain tasks (ARC-C, ARC-E, OBQA, SciQ), demonstrating the trade-off between editing aggressiveness and content preservation.
74
+
75
+ ## 🔧 Function Space
76
+
77
+ The model predicts operations from the following function space:
78
+
79
+ | Function | Description |
80
+ |----------|-------------|
81
+ | `keep_all()` | Document needs no modification |
82
+ | `remove_all()` | Entire document is valueless (e.g., error pages, login walls) |
83
+ | `remove_lines(start, end)` | Remove consecutive lines from start to end (inclusive) |
84
+ | `replace_str(line, old, new)` | Replace a substring within a specific line |
85
+ | `add_line(base, sub_idx, content)` | Insert a new line near the base position |
86
+
87
+ ### Input/Output Format
88
+
89
+ **Input:** Text with line number markers (`<lid:N>` prefix per line), preceded by a system instruction.
90
+
91
+ **Output:** A sequence of function calls, one per line. Example:
92
+ ```
93
+ remove_lines(1, 3)
94
+ replace_str(5, 'Click here to subscribe', '')
95
+ remove_lines(12, 15)
96
+ ```
97
+
98
+ ## 📈 Evaluation Results
99
+
100
+ Performance comparison on FineWeb (20B tokens, 1B MiniCPM, 10 benchmarks, zero-shot):
101
+
102
+ | Method | ARC-C | ARC-E | CSQA | HellaS | MMLU | OBQA | PIQA | SIQA | WinoG | SciQ | **Avg** | **#Win** |
103
+ |--------|-------|-------|------|--------|------|------|------|------|-------|------|---------|----------|
104
+ | Raw | 25.85 | 45.66 | 35.63 | 44.89 | 28.51 | 31.60 | 70.35 | 43.24 | 51.54 | 73.50 | 45.08 | 0/10 |
105
+ | UltraX-No-Instruction | 26.02 | **47.18** | 35.79 | **46.50** | 28.25 | 31.20 | 71.65 | 43.55 | 52.57 | 74.60 | 45.73 | 2/10 |
106
+ | UltraX-Preservation-Weighted | **26.79** | 47.14 | 36.12 | 46.30 | 28.54 | **33.80** | 70.67 | 42.78 | 51.62 | **76.10** | 45.99 | 3/10 |
107
+ | **UltraX** (default) | 26.62 | 45.96 | **37.43** | 46.29 | **28.90** | 31.80 | **71.98** | **43.71** | **52.72** | 76.00 | **46.14** | 5/10 |
108
+
109
+ ## ❤️ Acknowledgements
110
+
111
+ - The refinement model is trained using [ms-swift](https://github.com/modelscope/ms-swift).
112
+ - UltraX builds upon insights from [ProX](https://github.com/GAIR-NLP/ProX) and RefineX.
113
+
114
+ Thanks for their awesome work! Open-source contributions make UltraX possible! 🙌
115
+
116
+ ## 🌟 Citation
117
+
118
+ If you find our work useful, please consider citing:
119
+
120
+ ```bibtex
121
+ @misc{ultrax2026,
122
+ title={UltraX: Refining Pre-Training Data at Scale with Adaptive Programmatic Editing},
123
+ author={Xinlong Zhao and Dongsheng Liu and Hengyu Zhao and Zixuan Fu and Zheng Wang and Jie Cai and Jie Zhou and Qiang Ma and Xuanhe Zhou and Xu Han and Yudong Wang and Zhiyuan Liu},
124
+ year={2026},
125
+ eprint={},
126
+ archivePrefix={arXiv},
127
+ primaryClass={cs.CL},
128
+ }
129
+ ```
130
+
131
+ ## 💳 License
132
+
133
+ This project is released under the [Apache 2.0](./LICENSE).
README_ZH.md ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # UltraX
2
+
3
+ <div align="center">
4
+ <img src="assets/ultrax-logo.png" width="500"/>
5
+ </div>
6
+
7
+ <p align="center">
8
+ <b>基于自适应程序化编辑的大规模预训练数据精炼</b>
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="">📜 论文</a> |
13
+ <a href="">💻 代码</a> |
14
+ <a href="">🤗 数据集</a> |
15
+ <a href="https://huggingface.co/collections/openbmb/ultradata">📦 UltraData 合集</a>
16
+ </p>
17
+
18
+ <p align="center">
19
+ <a href="README.md">English</a> |
20
+ 中文
21
+ </p>
22
+
23
+ ## 📚 简介
24
+
25
+ **UltraX** 是一个面向大规模预训练数据的函数调用式精炼框架。与端到端文本改写不同,UltraX 训练一个轻量精炼模型来预测结构化编辑操作——包括插入、删除和修改——然后在原始文本上确定性执行。
26
+
27
+ 本仓库提供 **UltraX 精炼模型**,通过全参数 SFT 训练,可预测网页文本的清洗函数调用:
28
+
29
+
30
+ | 模型 | 说明 |
31
+ | -------------------------------- | ------------------------- |
32
+ | **UltraX** | 默认模型:指令引导 + 编辑偏置采样(主实验配置) |
33
+ | **UltraX-No-Instruction** | 消融变体:无系统指令训练 |
34
+ | **UltraX-Preservation-Weighted** | 消融变体:保留偏置采样(60% keep_all) |
35
+
36
+
37
+ ## 🔬 流程概览
38
+
39
+ <div align="center">
40
+ <img src="assets/ultrax_pipeline.png" width="800"/>
41
+ </div>
42
+
43
+ ## 💡 模型详情
44
+
45
+ 所有模型使用以下配置训练:
46
+
47
+
48
+ | 配置项 | 值 |
49
+ | ------ | -------------------------- |
50
+ | 训练框架 | ms-swift + DeepSpeed ZeRO3 |
51
+ | 训练类型 | 全参数 SFT |
52
+ | 最大序列长度 | 20,480 tokens |
53
+ | 学习率 | 3e-5(余弦衰减,最小 lr 3e-6) |
54
+ | 预热比例 | 0.03 |
55
+ | 精度 | bfloat16 |
56
+ | 硬件 | 8x GPU |
57
+
58
+
59
+ ### 模型变体
60
+
61
+ - **UltraX(指令引导,编辑偏置):** 默认配置。模型在系统指令下训练,定义了编辑操作和清洗规则,使用编辑偏置采样策略。
62
+ - **UltraX-No-Instruction:** 无系统指令训练。实验表明,即使没有显式任务协议,程序化精炼仍能带来明显提升(平均分:45.73 vs Raw 45.08),但指令引导可进一步提升性能(平均分:46.14)。
63
+ - **UltraX-Preservation-Weighted:** 使用保留偏置采样,keep_all 占训练数据的 60%。在部分任务上(ARC-C、ARC-E、OBQA、SciQ)表现更强,展示了编辑积极性与内容保留之间的平衡。
64
+
65
+ ## 🔧 函数空间
66
+
67
+ 模型预测以下函数空间中的操作:
68
+
69
+
70
+ | 函数 | 说明 |
71
+ | ---------------------------------- | ------------------------- |
72
+ | `keep_all()` | 文档无需修改 |
73
+ | `remove_all()` | 整篇文档无价值(如错误页面、登录墙) |
74
+ | `remove_lines(start, end)` | 删除从 start 到 end 的连续行(含首尾) |
75
+ | `replace_str(line, old, new)` | 在指定行内替换子字符串 |
76
+ | `add_line(base, sub_idx, content)` | 在指定位置附近插入新行 |
77
+
78
+
79
+ ### 输入/输出格式
80
+
81
+ **输入:** 带行号标记(`<lid:N>` 前缀)的文本,前置系统指令。
82
+
83
+ **输出:** 每行一个函数调用序列。示例:
84
+
85
+ ```
86
+ remove_lines(1, 3)
87
+ replace_str(5, 'Click here to subscribe', '')
88
+ remove_lines(12, 15)
89
+ ```
90
+
91
+ ## 📈 评估结果
92
+
93
+ 在 FineWeb 上的性能对比(20B tokens,1B MiniCPM,10 个基准,零样本):
94
+
95
+
96
+ | 方法 | ARC-C | ARC-E | CSQA | HellaS | MMLU | OBQA | PIQA | SIQA | WinoG | SciQ | **平均** | **#胜** |
97
+ | ---------------------------- | --------- | --------- | --------- | --------- | --------- | --------- | --------- | --------- | --------- | --------- | --------- | ------ |
98
+ | Raw | 25.85 | 45.66 | 35.63 | 44.89 | 28.51 | 31.60 | 70.35 | 43.24 | 51.54 | 73.50 | 45.08 | 0/10 |
99
+ | UltraX-No-Instruction | 26.02 | **47.18** | 35.79 | **46.50** | 28.25 | 31.20 | 71.65 | 43.55 | 52.57 | 74.60 | 45.73 | 2/10 |
100
+ | UltraX-Preservation-Weighted | **26.79** | 47.14 | 36.12 | 46.30 | 28.54 | **33.80** | 70.67 | 42.78 | 51.62 | **76.10** | 45.99 | 3/10 |
101
+ | **UltraX**(默认) | 26.62 | 45.96 | **37.43** | 46.29 | **28.90** | 31.80 | **71.98** | **43.71** | **52.72** | 76.00 | **46.14** | 5/10 |
102
+
103
+
104
+ ## ❤️ 致谢
105
+
106
+ - 精炼模型使用 [ms-swift](https://github.com/modelscope/ms-swift) 进行训练。
107
+ - UltraX 的设计借鉴了 [ProX](https://github.com/GAIR-NLP/ProX) 和 RefineX 的研究成果。
108
+
109
+ 感谢以上优秀的开源工作!🙌
110
+
111
+ ## 🌟 引用
112
+
113
+ 如果我们的工作对您有帮助,请考虑引��:
114
+
115
+ ```bibtex
116
+ @misc{ultrax2026,
117
+ title={UltraX: Refining Pre-Training Data at Scale with Adaptive Programmatic Editing},
118
+ author={Xinlong Zhao and Dongsheng Liu and Hengyu Zhao and Zixuan Fu and Zheng Wang and Jie Cai and Jie Zhou and Qiang Ma and Xuanhe Zhou and Xu Han and Yudong Wang and Zhiyuan Liu},
119
+ year={2026},
120
+ eprint={},
121
+ archivePrefix={arXiv},
122
+ primaryClass={cs.CL},
123
+ }
124
+ ```
125
+
126
+ ## 💳 许可证
127
+
128
+ 本项目基于 [Apache 2.0](./LICENSE) 协议发布。
assets/ultrax-logo.png ADDED

Git LFS Details

  • SHA256: 8b65442a2351dda9bbcd4b361e1a921c485cbe069dcaaec36b4b52921a0a527e
  • Pointer size: 131 Bytes
  • Size of remote file: 963 kB
assets/ultrax_pipeline.png ADDED

Git LFS Details

  • SHA256: 93d3d8dab4b0f467f2f8a88a9944e08a329eb972b179118da8f41e8f37df4a00
  • Pointer size: 132 Bytes
  • Size of remote file: 1.4 MB
code/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ pyarrow
2
+ pandas
3
+ transformers
4
+ requests
5
+ torch
6
+ vllm
7
+ ms-swift
code/stage1_model_construction/e2e_refinement/refine_dataset.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Batch data refinement using an optimized prompt.
4
+
5
+ Reads parquet files, refines each row's content via LLM API,
6
+ and writes results with matching filenames.
7
+
8
+ Supports:
9
+ - Configurable concurrent file workers
10
+ - Resume from breakpoint (skips already-completed output files)
11
+
12
+ Usage:
13
+ python refine_dataset.py --input_dir <dir> --output_dir <dir> --prompt_file <file> --api_key <key>
14
+ """
15
+
16
+ import os
17
+ import time
18
+ import logging
19
+ import argparse
20
+ import threading
21
+ import requests
22
+ import pyarrow as pa
23
+ import pyarrow.parquet as pq
24
+ from concurrent.futures import ThreadPoolExecutor, as_completed
25
+
26
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
27
+ logger = logging.getLogger(__name__)
28
+
29
+ _lock = threading.Lock()
30
+ _stats = {"calls": 0, "tokens": 0, "errors": 0}
31
+
32
+
33
+ def call_api(system_prompt, user_content, api_url, api_key, model,
34
+ temperature=0, max_tokens=24000, timeout=180, retry_times=3, retry_delay=2):
35
+ messages = [
36
+ {"role": "system", "content": system_prompt},
37
+ {"role": "user", "content": user_content},
38
+ ]
39
+ body = {
40
+ "model": model,
41
+ "messages": messages,
42
+ "temperature": temperature,
43
+ "max_tokens": max_tokens,
44
+ "enable_thinking": False,
45
+ }
46
+ headers = {
47
+ "Content-Type": "application/json",
48
+ "Authorization": f"Bearer {api_key}",
49
+ }
50
+
51
+ for attempt in range(retry_times):
52
+ try:
53
+ resp = requests.post(api_url, json=body, headers=headers, timeout=timeout)
54
+ resp.raise_for_status()
55
+ data = resp.json()
56
+ content = data["choices"][0]["message"]["content"]
57
+
58
+ with _lock:
59
+ _stats["calls"] += 1
60
+ usage = data.get("usage", {})
61
+ _stats["tokens"] += usage.get("total_tokens", 0)
62
+
63
+ return content
64
+ except Exception:
65
+ if attempt < retry_times - 1:
66
+ time.sleep(retry_delay * (attempt + 1))
67
+
68
+ with _lock:
69
+ _stats["errors"] += 1
70
+ return None
71
+
72
+
73
+ def process_file(input_path, output_path, prompt, api_url, api_key, model):
74
+ fname = os.path.basename(input_path)
75
+ table = pq.read_table(input_path, columns=["content"])
76
+ contents = table.column("content").to_pylist()
77
+
78
+ originals, refined, success_flags = [], [], []
79
+ for text in contents:
80
+ result = call_api(prompt, text, api_url, api_key, model)
81
+ originals.append(text)
82
+ if result is not None:
83
+ refined.append(result)
84
+ success_flags.append("yes")
85
+ else:
86
+ refined.append("")
87
+ success_flags.append("no")
88
+
89
+ out_table = pa.table({
90
+ "original_content": originals,
91
+ "refined_content": refined,
92
+ "refinement_success": success_flags,
93
+ })
94
+
95
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
96
+ tmp_path = output_path + ".tmp"
97
+ pq.write_table(out_table, tmp_path)
98
+ os.rename(tmp_path, output_path)
99
+
100
+ ok = sum(1 for f in success_flags if f == "yes")
101
+ return fname, len(contents), ok
102
+
103
+
104
+ def run_dataset(ds_name, input_dir, output_dir, prompt_file, api_url, api_key, model, concurrency):
105
+ ds_input = os.path.join(input_dir, ds_name)
106
+ ds_output = os.path.join(output_dir, ds_name)
107
+
108
+ with open(prompt_file, "r", encoding="utf-8") as f:
109
+ prompt = f.read()
110
+
111
+ all_files = sorted(f for f in os.listdir(ds_input) if f.endswith(".parquet"))
112
+ os.makedirs(ds_output, exist_ok=True)
113
+
114
+ todo, skipped = [], 0
115
+ for fname in all_files:
116
+ output_path = os.path.join(ds_output, fname)
117
+ if os.path.isfile(output_path):
118
+ skipped += 1
119
+ else:
120
+ todo.append(fname)
121
+
122
+ logger.info("[%s] Input: %s (%d files), To process: %d, Skipped: %d",
123
+ ds_name, ds_input, len(all_files), len(todo), skipped)
124
+
125
+ if not todo:
126
+ return
127
+
128
+ total_rows, total_ok, done = 0, 0, 0
129
+ t0 = time.time()
130
+
131
+ with ThreadPoolExecutor(max_workers=concurrency) as pool:
132
+ futures = {}
133
+ for fname in todo:
134
+ inp = os.path.join(ds_input, fname)
135
+ out = os.path.join(ds_output, fname)
136
+ futures[pool.submit(process_file, inp, out, prompt, api_url, api_key, model)] = fname
137
+
138
+ for future in as_completed(futures):
139
+ fname = futures[future]
140
+ try:
141
+ _, n, ok = future.result()
142
+ total_rows += n
143
+ total_ok += ok
144
+ done += 1
145
+ logger.info("[%s] [%d/%d] %s rows=%d ok=%d", ds_name, done, len(todo), fname, n, ok)
146
+ except Exception as exc:
147
+ done += 1
148
+ logger.error("[%s] [%d/%d] %s FAILED: %s", ds_name, done, len(todo), fname, exc)
149
+
150
+ logger.info("[%s] DONE files=%d rows=%d ok=%d elapsed=%.0fs",
151
+ ds_name, len(all_files), total_rows, total_ok, time.time() - t0)
152
+
153
+
154
+ def main():
155
+ parser = argparse.ArgumentParser(description="Batch LLM data refinement")
156
+ parser.add_argument("--input_dir", type=str, required=True,
157
+ help="Root input directory (contains dataset subdirectories with parquet files)")
158
+ parser.add_argument("--output_dir", type=str, required=True,
159
+ help="Root output directory")
160
+ parser.add_argument("--prompt_dir", type=str, required=True,
161
+ help="Directory containing per-dataset optimized_prompt.txt files")
162
+ parser.add_argument("--api_url", type=str, required=True,
163
+ help="LLM API endpoint URL")
164
+ parser.add_argument("--api_key", type=str, default=os.environ.get("API_KEY", ""),
165
+ help="API key (or set API_KEY env var)")
166
+ parser.add_argument("--model", type=str, default="deepseek-v3",
167
+ help="Model name for API calls")
168
+ parser.add_argument("--concurrency", type=int, default=64,
169
+ help="Number of concurrent file workers (default: 64)")
170
+ parser.add_argument("--datasets", nargs="*", default=None,
171
+ help="Specific dataset names (default: all subdirectories)")
172
+ args = parser.parse_args()
173
+
174
+ if args.datasets:
175
+ datasets = args.datasets
176
+ else:
177
+ datasets = sorted(d for d in os.listdir(args.input_dir)
178
+ if os.path.isdir(os.path.join(args.input_dir, d)))
179
+
180
+ logger.info("Datasets to process: %s", datasets)
181
+ for ds in datasets:
182
+ prompt_file = os.path.join(args.prompt_dir, ds, "optimized_prompt.txt")
183
+ if not os.path.isfile(prompt_file):
184
+ logger.warning("Prompt file not found for %s: %s, skipping", ds, prompt_file)
185
+ continue
186
+ run_dataset(ds, args.input_dir, args.output_dir, prompt_file,
187
+ args.api_url, args.api_key, args.model, args.concurrency)
188
+ logger.info("All datasets complete.")
189
+
190
+
191
+ if __name__ == "__main__":
192
+ main()
code/stage1_model_construction/function_construction/function_construction.py ADDED
@@ -0,0 +1,948 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ LAM + DCR Function Construction Algorithm
4
+ ==========================================
5
+
6
+ This module implements the core algorithm for Stage 1 of UltraX:
7
+ - **LAM (Line-Aware Matching):** Matches lines between original and refined text
8
+ using a global optimal matching strategy with content similarity, context
9
+ similarity, and positional factors.
10
+ - **DCR (Diff-based Cleaning Representation):** Converts text-level differences
11
+ into structured, fine-grained cleaning operations (replace_str, remove_lines,
12
+ add_line, remove_all, keep_all).
13
+
14
+ The pipeline processes parquet files containing (original_content, refined_content)
15
+ pairs and outputs JSONL training data where each example maps line-id-marked
16
+ original text to a sequence of cleaning function calls.
17
+ """
18
+
19
+ import argparse
20
+ import difflib
21
+ import json
22
+ import logging
23
+ import pyarrow.parquet as pq
24
+ from pathlib import Path
25
+ from typing import List, Dict, Tuple
26
+ from datetime import datetime
27
+ from collections import defaultdict
28
+ from multiprocessing import Pool
29
+ from functools import partial
30
+
31
+ logging.basicConfig(
32
+ level=logging.INFO,
33
+ format='%(asctime)s - %(levelname)s - %(message)s'
34
+ )
35
+ logger = logging.getLogger(__name__)
36
+
37
+
38
+ class BatchDataCleaner:
39
+
40
+ NON_MEANINGFUL_CHARS = set(
41
+ # Whitespace characters (including fullwidth space)
42
+ ' \u3000\u00a0\u2002\u2003\u2009'
43
+ # English punctuation
44
+ ',.;:!?\'\"'
45
+ # Chinese punctuation
46
+ ',。;:!?、''""'
47
+ # Fullwidth English punctuation
48
+ '.,;:!?'"'
49
+ # Small punctuation variants
50
+ '﹑﹐﹔﹕﹖﹗'
51
+ )
52
+
53
+ def __init__(self):
54
+ pass
55
+
56
+ def _strip_non_meaningful(self, s: str) -> str:
57
+ """Remove non-meaningful characters, preserving substantive text content."""
58
+ return ''.join(c for c in s if c not in self.NON_MEANINGFUL_CHARS)
59
+
60
+ def is_meaningful_replace_str(self, op: Dict) -> bool:
61
+ """Check whether a replace_str operation has substantive text changes.
62
+
63
+ Returns False if the change only involves punctuation/whitespace.
64
+ Returns True if there is a meaningful text content change.
65
+ """
66
+ if op['operation'] != 'replace_str':
67
+ return True
68
+
69
+ search = op['search_content']
70
+ replace = op['replace_content']
71
+
72
+ stripped_search = self._strip_non_meaningful(search)
73
+ stripped_replace = self._strip_non_meaningful(replace)
74
+
75
+ return stripped_search != stripped_replace
76
+
77
+ def filter_meaningful_operations(self, operations: List[Dict]) -> List[Dict]:
78
+ """Filter operation list, keeping only replace_str operations with substantive changes."""
79
+ filtered = []
80
+
81
+ for op in operations:
82
+ if op['operation'] == 'replace_str':
83
+ if self.is_meaningful_replace_str(op):
84
+ filtered.append(op)
85
+ else:
86
+ filtered.append(op)
87
+
88
+ return filtered
89
+
90
+ def make_context_unique_in_line(self, line: str, start: int, end: int) -> tuple:
91
+ """Dynamically adjust context within a line to ensure target string uniqueness."""
92
+ target = line[start:end]
93
+ max_possible_len = max(start, len(line) - end)
94
+
95
+ for context_len in range(0, max_possible_len + 1):
96
+ before = line[max(0, start - context_len):start]
97
+ after = line[end:min(len(line), end + context_len)]
98
+ context_pattern = before + target + after
99
+ if line.count(context_pattern) == 1:
100
+ return before, target, after, True
101
+
102
+ return line[0:start], target, line[end:], True
103
+
104
+ def _get_line_similarity(self, line1: str, line2: str) -> float:
105
+ """Compute similarity between two lines."""
106
+ s1, s2 = line1.strip(), line2.strip()
107
+ if s1 == s2:
108
+ return 1.0
109
+ matcher = difflib.SequenceMatcher(None, s1, s2)
110
+ return matcher.ratio()
111
+
112
+ def _get_context_similarity(self, orig_idx: int, ref_idx: int,
113
+ orig_lines: List[Tuple[int, str]],
114
+ ref_lines: List[Tuple[int, str]],
115
+ context_size: int = 3) -> float:
116
+ """Compute context similarity (context_size lines before and after)."""
117
+ context_scores = []
118
+
119
+ for i in range(1, context_size + 1):
120
+ orig_prev = orig_idx - i
121
+ ref_prev = ref_idx - i
122
+ if orig_prev >= 0 and ref_prev >= 0:
123
+ sim = self._get_line_similarity(
124
+ orig_lines[orig_prev][1],
125
+ ref_lines[ref_prev][1]
126
+ )
127
+ context_scores.append(sim)
128
+
129
+ for i in range(1, context_size + 1):
130
+ orig_next = orig_idx + i
131
+ ref_next = ref_idx + i
132
+ if orig_next < len(orig_lines) and ref_next < len(ref_lines):
133
+ sim = self._get_line_similarity(
134
+ orig_lines[orig_next][1],
135
+ ref_lines[ref_next][1]
136
+ )
137
+ context_scores.append(sim)
138
+
139
+ # Return neutral 0.5 when no context is available to avoid unfairly penalizing boundary lines
140
+ return sum(context_scores) / len(context_scores) if context_scores else 0.5
141
+
142
+ def match_lines(self, original_lines: List[str], refined_lines: List[str]) -> Tuple[List[Tuple[int, int]], List[int], List[int]]:
143
+ """Match original and refined lines using global optimal matching with context and position.
144
+
145
+ Strategy:
146
+ 1. Compute content similarity, context similarity, and position similarity for all line pairs
147
+ 2. Combined score = content * 0.6 + context * 0.2 + position * 0.2
148
+ 3. Greedily match by descending combined score while preventing crossings
149
+
150
+ Returns:
151
+ matched_pairs: [(original_line_num, refined_line_num), ...]
152
+ unmatched_original: [unmatched original line numbers, ...]
153
+ unmatched_refined: [unmatched refined line numbers, ...]
154
+ """
155
+ orig_non_empty = [(i + 1, line) for i, line in enumerate(original_lines) if line.strip()]
156
+ ref_non_empty = [(j + 1, line) for j, line in enumerate(refined_lines) if line.strip()]
157
+
158
+ max_lines = max(len(orig_non_empty), len(ref_non_empty), 1)
159
+
160
+ all_pairs = []
161
+ for orig_idx, (orig_line_num, orig_content) in enumerate(orig_non_empty):
162
+ for ref_idx, (ref_line_num, ref_content) in enumerate(ref_non_empty):
163
+ content_sim = self._get_line_similarity(orig_content, ref_content)
164
+ if content_sim >= 0.4:
165
+ context_sim = self._get_context_similarity(
166
+ orig_idx, ref_idx, orig_non_empty, ref_non_empty
167
+ )
168
+ position_diff = abs(orig_idx - ref_idx)
169
+ position_sim = 1.0 - (position_diff / max_lines)
170
+
171
+ total_score = content_sim * 0.6 + context_sim * 0.2 + position_sim * 0.2
172
+ all_pairs.append((orig_idx, ref_idx, orig_line_num, ref_line_num, total_score))
173
+
174
+ all_pairs.sort(key=lambda x: x[4], reverse=True)
175
+
176
+ matched_pairs = []
177
+ used_orig = set()
178
+ used_ref = set()
179
+
180
+ def would_cross(orig_num: int, ref_num: int) -> bool:
181
+ """Check if a new match would cross any existing match."""
182
+ for prev_orig, prev_ref in matched_pairs:
183
+ if (orig_num > prev_orig and ref_num < prev_ref) or \
184
+ (orig_num < prev_orig and ref_num > prev_ref):
185
+ return True
186
+ return False
187
+
188
+ for orig_idx, ref_idx, orig_line_num, ref_line_num, total_score in all_pairs:
189
+ if orig_idx in used_orig or ref_idx in used_ref:
190
+ continue
191
+
192
+ if would_cross(orig_line_num, ref_line_num):
193
+ continue
194
+
195
+ matched_pairs.append((orig_line_num, ref_line_num))
196
+ used_orig.add(orig_idx)
197
+ used_ref.add(ref_idx)
198
+
199
+ unmatched_original = [orig_non_empty[i][0] for i in range(len(orig_non_empty)) if i not in used_orig]
200
+ unmatched_refined = [ref_non_empty[j][0] for j in range(len(ref_non_empty)) if j not in used_ref]
201
+
202
+ matched_pairs.sort(key=lambda x: x[0])
203
+
204
+ return matched_pairs, unmatched_original, unmatched_refined
205
+
206
+ def merge_remove_lines_operations(self, operations: List[Dict]) -> List[Dict]:
207
+ """Merge remove operations: use remove_lines(start, end) uniformly (start==end for single lines)."""
208
+ remove_line_numbers = []
209
+ other_operations = []
210
+ removed_contents_dict = {}
211
+
212
+ for op in operations:
213
+ if op['operation'] == 'remove_lines':
214
+ remove_line_numbers.extend(op['line_numbers'])
215
+ for line_num, content in zip(op['line_numbers'], op.get('removed_content', [])):
216
+ removed_contents_dict[line_num] = content
217
+ else:
218
+ other_operations.append(op)
219
+
220
+ result_operations = []
221
+ if remove_line_numbers:
222
+ unique_line_numbers = sorted(set(remove_line_numbers))
223
+ i = 0
224
+ while i < len(unique_line_numbers):
225
+ start = end = unique_line_numbers[i]
226
+ while i + 1 < len(unique_line_numbers) and unique_line_numbers[i + 1] == unique_line_numbers[i] + 1:
227
+ i += 1
228
+ end = unique_line_numbers[i]
229
+
230
+ result_operations.append({
231
+ 'operation': 'remove_lines',
232
+ 'start_line': start,
233
+ 'end_line': end,
234
+ 'description': f"Remove line {start}{'-' + str(end) if end != start else ''}",
235
+ 'removed_content': [removed_contents_dict.get(n, '') for n in range(start, end + 1)]
236
+ })
237
+ i += 1
238
+
239
+ return result_operations + other_operations
240
+
241
+ def analyze_char_operations(self, orig_line: str, ref_line: str, line_num: int) -> List[Dict]:
242
+ """Analyze character-level changes within a line, producing replace_str operations."""
243
+ matcher = difflib.SequenceMatcher(None, orig_line, ref_line)
244
+ operations = []
245
+
246
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():
247
+ if tag == 'equal':
248
+ continue
249
+ elif tag == 'delete':
250
+ removed_str = orig_line[i1:i2]
251
+ context_before, target, context_after = self._make_context_unique_for_position(orig_line, i1, i2)
252
+ operations.append({
253
+ 'operation': 'replace_str',
254
+ 'line_number': line_num,
255
+ 'search_content': context_before + target + context_after,
256
+ 'replace_content': context_before + context_after,
257
+ 'description': f"Line {line_num}: delete string {repr(removed_str)}"
258
+ })
259
+ elif tag == 'insert':
260
+ inserted_str = ref_line[j1:j2]
261
+ context_before, context_after = self._make_insert_context_unique(orig_line, i1)
262
+
263
+ operations.append({
264
+ 'operation': 'replace_str',
265
+ 'line_number': line_num,
266
+ 'search_content': context_before + context_after,
267
+ 'replace_content': context_before + inserted_str + context_after,
268
+ 'description': f"Line {line_num}: insert string {repr(inserted_str)}"
269
+ })
270
+ elif tag == 'replace':
271
+ old_str, new_str = orig_line[i1:i2], ref_line[j1:j2]
272
+ context_before, target, context_after = self._make_context_unique_for_position(orig_line, i1, i2)
273
+ operations.append({
274
+ 'operation': 'replace_str',
275
+ 'line_number': line_num,
276
+ 'search_content': context_before + target + context_after,
277
+ 'replace_content': context_before + new_str + context_after,
278
+ 'description': f"Line {line_num}: replace {repr(old_str)} -> {repr(new_str)}"
279
+ })
280
+
281
+ return operations
282
+
283
+ def _make_context_unique_for_position(self, line: str, start: int, end: int) -> Tuple[str, str, str]:
284
+ """Generate context ensuring find() locates the correct position.
285
+
286
+ Not only requires search_content to be unique, but also verifies
287
+ that find() returns the correct position.
288
+ """
289
+ target = line[start:end]
290
+ max_possible_len = max(start, len(line) - end)
291
+
292
+ for context_len in range(0, max_possible_len + 1):
293
+ before = line[max(0, start - context_len):start]
294
+ after = line[end:min(len(line), end + context_len)]
295
+ search_content = before + target + after
296
+
297
+ found_pos = line.find(search_content)
298
+ expected_pos = start - len(before)
299
+
300
+ if found_pos == expected_pos:
301
+ return before, target, after
302
+
303
+ return line[0:start], target, line[end:]
304
+
305
+ def _make_insert_context_unique(self, line: str, insert_pos: int) -> Tuple[str, str]:
306
+ """Generate unique context for insertion, ensuring find() locates the correct insertion point."""
307
+ max_context = max(insert_pos, len(line) - insert_pos, 1)
308
+
309
+ for context_len in range(1, max_context + 1):
310
+ before = line[max(0, insert_pos - context_len):insert_pos]
311
+ after = line[insert_pos:min(len(line), insert_pos + context_len)]
312
+ search_content = before + after
313
+
314
+ found_pos = line.find(search_content)
315
+ expected_pos = insert_pos - len(before)
316
+
317
+ if found_pos == expected_pos:
318
+ return before, after
319
+
320
+ return line[:insert_pos], line[insert_pos:]
321
+
322
+ def reorder_operations_for_execution(self, operations: List[Dict]) -> List[Dict]:
323
+ """Reorder operations: sort by line number, within same line by search_content length (descending)."""
324
+ str_ops = [op for op in operations if op['operation'] == 'replace_str']
325
+ other_ops = [op for op in operations if op['operation'] != 'replace_str']
326
+ str_ops.sort(key=lambda op: (op['line_number'], -len(op['search_content'])))
327
+ return str_ops + other_ops
328
+
329
+ def extract_modifications(self, search: str, replace: str, pos_in_line: int) -> List[Tuple[int, int, str]]:
330
+ """Extract actual modifications from search_content and replace_content.
331
+
332
+ Args:
333
+ search: search_content
334
+ replace: replace_content
335
+ pos_in_line: starting position of search_content in the original line
336
+
337
+ Returns:
338
+ List of modifications: [(abs_start_in_line, abs_end_in_line, new_content), ...]
339
+ """
340
+ matcher = difflib.SequenceMatcher(None, search, replace)
341
+ modifications = []
342
+
343
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():
344
+ if tag == 'equal':
345
+ continue
346
+ abs_start = pos_in_line + i1
347
+ abs_end = pos_in_line + i2
348
+ new_content = replace[j1:j2]
349
+ modifications.append((abs_start, abs_end, new_content))
350
+
351
+ return modifications
352
+
353
+ def merge_overlapping_ops(self, ops: List[Dict], orig_line: str, line_num: int, max_merged_len: int = 30) -> List[Dict]:
354
+ """Merge multiple nearby operations into a single operation.
355
+
356
+ Uses minimum necessary range as search_content.
357
+ Does not merge if the resulting length exceeds max_merged_len.
358
+
359
+ Args:
360
+ ops: list of operations to merge
361
+ orig_line: original line content
362
+ line_num: line number
363
+ max_merged_len: max length of merged search_content
364
+
365
+ Returns:
366
+ Merged operation list (may be a single merged op or the original list)
367
+ """
368
+ all_modifications = []
369
+
370
+ for op in ops:
371
+ search = op['search_content']
372
+ replace = op['replace_content']
373
+
374
+ pos = orig_line.find(search)
375
+ if pos == -1:
376
+ continue
377
+
378
+ mods = self.extract_modifications(search, replace, pos)
379
+ all_modifications.extend(mods)
380
+
381
+ if not all_modifications:
382
+ return ops
383
+
384
+ all_modifications.sort(key=lambda x: x[0])
385
+
386
+ merged_modifications = []
387
+ for start, end, content in all_modifications:
388
+ if merged_modifications:
389
+ last_start, last_end, last_content = merged_modifications[-1]
390
+ if start < last_end:
391
+ new_start = last_start
392
+ new_end = max(last_end, end)
393
+ overlap_in_last = start - last_start
394
+ new_content = last_content[:overlap_in_last] + content
395
+ merged_modifications[-1] = (new_start, new_end, new_content)
396
+ continue
397
+ merged_modifications.append((start, end, content))
398
+
399
+ if not merged_modifications:
400
+ return ops
401
+
402
+ min_start = merged_modifications[0][0]
403
+ max_end = max(m[1] for m in merged_modifications)
404
+
405
+ merged_len = max_end - min_start
406
+ if merged_len > max_merged_len:
407
+ return ops
408
+
409
+ context_before, target, context_after, _ = self.make_context_unique_in_line(
410
+ orig_line, min_start, max_end
411
+ )
412
+ search_content = context_before + target + context_after
413
+
414
+ new_start = min_start - len(context_before)
415
+
416
+ replace_content = search_content
417
+ for start, end, new_content in reversed(merged_modifications):
418
+ rel_start = start - new_start
419
+ rel_end = end - new_start
420
+ replace_content = replace_content[:rel_start] + new_content + replace_content[rel_end:]
421
+
422
+ if replace_content == search_content:
423
+ return ops
424
+
425
+ return [{
426
+ 'operation': 'replace_str',
427
+ 'line_number': line_num,
428
+ 'search_content': search_content,
429
+ 'replace_content': replace_content,
430
+ 'description': f"Line {line_num}: merge {len(ops)} nearby replace operations"
431
+ }]
432
+
433
+ def get_ops_distance(self, op_a: Dict, op_b: Dict, orig_line: str) -> int:
434
+ """Compute distance between two operations (based on actual modification positions)."""
435
+ pos_a = orig_line.find(op_a['search_content'])
436
+ if pos_a == -1:
437
+ return float('inf')
438
+ mods_a = self.extract_modifications(op_a['search_content'], op_a['replace_content'], pos_a)
439
+
440
+ pos_b = orig_line.find(op_b['search_content'])
441
+ if pos_b == -1:
442
+ return float('inf')
443
+ mods_b = self.extract_modifications(op_b['search_content'], op_b['replace_content'], pos_b)
444
+
445
+ if not mods_a:
446
+ mods_a = [(pos_a, pos_a + len(op_a['search_content']), '')]
447
+ if not mods_b:
448
+ mods_b = [(pos_b, pos_b + len(op_b['search_content']), '')]
449
+
450
+ min_gap = float('inf')
451
+ for start_a, end_a, _ in mods_a:
452
+ for start_b, end_b, _ in mods_b:
453
+ if end_a <= start_b:
454
+ gap = start_b - end_a
455
+ elif end_b <= start_a:
456
+ gap = start_a - end_b
457
+ else:
458
+ gap = 0
459
+ min_gap = min(min_gap, gap)
460
+
461
+ return min_gap
462
+
463
+ def greedy_merge_ops(self, ops: List[Dict], orig_line: str, line_num: int,
464
+ max_gap: int = 30, max_merged_len: int = 20) -> List[Dict]:
465
+ """Greedy merge: merge operations by distance priority.
466
+
467
+ Args:
468
+ ops: operation list
469
+ orig_line: original line content
470
+ line_num: line number
471
+ max_gap: maximum allowed distance between operations
472
+ max_merged_len: maximum search_content length after merging
473
+
474
+ Returns:
475
+ Merged operation list
476
+ """
477
+ if len(ops) <= 1:
478
+ return ops
479
+
480
+ n = len(ops)
481
+ distances = []
482
+ for i in range(n):
483
+ for j in range(i + 1, n):
484
+ dist = self.get_ops_distance(ops[i], ops[j], orig_line)
485
+ if dist <= max_gap:
486
+ distances.append((dist, i, j))
487
+
488
+ distances.sort(key=lambda x: x[0])
489
+
490
+ # Union-Find for tracking merged operation groups
491
+ parent = list(range(n))
492
+
493
+ def find(x):
494
+ if parent[x] != x:
495
+ parent[x] = find(parent[x])
496
+ return parent[x]
497
+
498
+ def union(x, y):
499
+ px, py = find(x), find(y)
500
+ if px != py:
501
+ parent[px] = py
502
+
503
+ group_ranges = {}
504
+
505
+ for op_idx, op in enumerate(ops):
506
+ pos = orig_line.find(op['search_content'])
507
+ if pos != -1:
508
+ mods = self.extract_modifications(op['search_content'], op['replace_content'], pos)
509
+ if mods:
510
+ min_start = min(m[0] for m in mods)
511
+ max_end = max(m[1] for m in mods)
512
+ else:
513
+ min_start = pos
514
+ max_end = pos + len(op['search_content'])
515
+ group_ranges[op_idx] = (min_start, max_end)
516
+
517
+ for dist, i, j in distances:
518
+ root_i, root_j = find(i), find(j)
519
+ if root_i == root_j:
520
+ continue
521
+
522
+ if root_i not in group_ranges or root_j not in group_ranges:
523
+ continue
524
+
525
+ range_i = group_ranges[root_i]
526
+ range_j = group_ranges[root_j]
527
+ new_min = min(range_i[0], range_j[0])
528
+ new_max = max(range_i[1], range_j[1])
529
+ new_len = new_max - new_min
530
+
531
+ if new_len <= max_merged_len:
532
+ union(i, j)
533
+ new_root = find(i)
534
+ group_ranges[new_root] = (new_min, new_max)
535
+ if root_i != new_root and root_i in group_ranges:
536
+ del group_ranges[root_i]
537
+ if root_j != new_root and root_j in group_ranges:
538
+ del group_ranges[root_j]
539
+
540
+ groups = {}
541
+ for i in range(n):
542
+ root = find(i)
543
+ if root not in groups:
544
+ groups[root] = []
545
+ groups[root].append(ops[i])
546
+
547
+ result = []
548
+ for root, group_ops in groups.items():
549
+ if len(group_ops) == 1:
550
+ result.append(group_ops[0])
551
+ else:
552
+ merged = self.merge_overlapping_ops(group_ops, orig_line, line_num)
553
+ result.extend(merged)
554
+
555
+ return result
556
+
557
+ def merge_same_line_replace_operations(self, operations: List[Dict], original_lines: List[str]) -> List[Dict]:
558
+ """Merge replace_str operations on the same line.
559
+
560
+ Uses greedy distance-based merging to reduce operation count
561
+ while keeping each operation's content manageable.
562
+
563
+ Args:
564
+ operations: operation list
565
+ original_lines: original text split into lines (with newlines)
566
+
567
+ Returns:
568
+ Processed operation list
569
+ """
570
+ replace_ops = [op for op in operations if op['operation'] == 'replace_str']
571
+ other_ops = [op for op in operations if op['operation'] != 'replace_str']
572
+
573
+ if not replace_ops:
574
+ return operations
575
+
576
+ line_ops = defaultdict(list)
577
+ for op in replace_ops:
578
+ line_ops[op['line_number']].append(op)
579
+
580
+ merged_ops = []
581
+
582
+ for line_num in sorted(line_ops.keys()):
583
+ ops = line_ops[line_num]
584
+
585
+ if len(ops) == 1:
586
+ merged_ops.append(ops[0])
587
+ continue
588
+
589
+ if isinstance(line_num, int) and 1 <= line_num <= len(original_lines):
590
+ orig_line = original_lines[line_num - 1]
591
+ else:
592
+ merged_ops.extend(ops)
593
+ continue
594
+
595
+ merged_result = self.greedy_merge_ops(ops, orig_line, line_num)
596
+ merged_ops.extend(merged_result)
597
+
598
+ return merged_ops + other_ops
599
+
600
+ def analyze_line_operations(self, original: str, refined: str) -> List[Dict]:
601
+ """Analyze original and refined text, producing a list of line-based operations."""
602
+ if original == refined:
603
+ return []
604
+
605
+ if refined.strip() == '[Content valueless, deleted]':
606
+ return [{
607
+ 'operation': 'remove_all',
608
+ 'description': 'Content is valueless, remove entirely'
609
+ }]
610
+
611
+ original_lines = original.splitlines(keepends=True)
612
+ refined_lines = refined.splitlines(keepends=True)
613
+
614
+ matched_pairs, unmatched_original, unmatched_refined = self.match_lines(original_lines, refined_lines)
615
+
616
+ operations = []
617
+
618
+ # 1. Matched line pairs -> generate replace_str operations
619
+ for orig_line_num, ref_line_num in matched_pairs:
620
+ orig_line = original_lines[orig_line_num - 1]
621
+ ref_line = refined_lines[ref_line_num - 1]
622
+ if orig_line != ref_line:
623
+ char_ops = self.analyze_char_operations(orig_line, ref_line, orig_line_num)
624
+ operations.extend(char_ops)
625
+
626
+ # 2. Unmatched original lines -> generate remove_lines operations
627
+ if unmatched_original:
628
+ operations.append({
629
+ 'operation': 'remove_lines',
630
+ 'line_numbers': unmatched_original,
631
+ 'description': f"Remove line {', '.join(map(str, unmatched_original[:3]))}{'...' if len(unmatched_original) > 3 else ''}",
632
+ 'removed_content': [original_lines[i-1] for i in unmatched_original]
633
+ })
634
+
635
+ # 3. Unmatched refined lines -> generate add_line operations
636
+ if unmatched_refined:
637
+ refined_to_orig = {ref: orig for orig, ref in matched_pairs}
638
+
639
+ insert_after_counter = {}
640
+ insert_before_counter = {}
641
+
642
+ for ref_line_num in sorted(unmatched_refined):
643
+ content = refined_lines[ref_line_num - 1]
644
+
645
+ prev_orig = 0
646
+ for ref_num in range(ref_line_num - 1, 0, -1):
647
+ if ref_num in refined_to_orig:
648
+ prev_orig = refined_to_orig[ref_num]
649
+ break
650
+
651
+ next_orig = 0
652
+ for ref_num in range(ref_line_num + 1, len(refined_lines) + 1):
653
+ if ref_num in refined_to_orig:
654
+ next_orig = refined_to_orig[ref_num]
655
+ break
656
+
657
+ if prev_orig > 0:
658
+ base_position = prev_orig
659
+ sub_index = insert_after_counter.get(base_position, 0) + 1
660
+ insert_after_counter[base_position] = sub_index
661
+ desc = f"Insert new line #{sub_index} after line {base_position}"
662
+ elif next_orig > 0:
663
+ base_position = next_orig - 1
664
+ sub_index = insert_before_counter.get(next_orig, 0) + 1
665
+ insert_before_counter[next_orig] = sub_index
666
+ desc = f"Insert new line #{sub_index} before line {next_orig}"
667
+ else:
668
+ base_position = 0
669
+ sub_index = insert_before_counter.get(0, 0) + 1
670
+ insert_before_counter[0] = sub_index
671
+ desc = f"Insert new line #{sub_index} at beginning of file"
672
+
673
+ operations.append({
674
+ 'operation': 'add_line',
675
+ 'base_position': base_position,
676
+ 'sub_index': sub_index,
677
+ 'content': content,
678
+ 'description': desc
679
+ })
680
+
681
+ operations = self.merge_remove_lines_operations(operations)
682
+ operations = self.merge_same_line_replace_operations(operations, original_lines)
683
+ operations = self.filter_meaningful_operations(operations)
684
+ operations = self.reorder_operations_for_execution(operations)
685
+
686
+ return operations
687
+
688
+ def filter_data(self, operations: List[Dict]) -> bool:
689
+ """Check whether data meets filtering criteria.
690
+
691
+ Returns:
692
+ True: keep this data
693
+ False: filter out this data
694
+ """
695
+ if len(operations) >= 20:
696
+ return False
697
+
698
+ add_line_count = 0
699
+ for op in operations:
700
+ if op['operation'] == 'replace_str':
701
+ if len(op['search_content']) >= 150:
702
+ return False
703
+ if len(op['replace_content']) >= 150:
704
+ return False
705
+
706
+ if op['operation'] == 'add_line':
707
+ add_line_count += 1
708
+ if len(op['content']) >= 200:
709
+ return False
710
+
711
+ if add_line_count >= 10:
712
+ return False
713
+
714
+ return True
715
+
716
+ def add_line_id_markers(self, content: str) -> str:
717
+ """Add line number markers to each line of the original content."""
718
+ lines = content.splitlines()
719
+ marked_lines = []
720
+ for i, line in enumerate(lines, start=1):
721
+ marked_lines.append(f"<lid:{i}>{line}")
722
+ return '\n'.join(marked_lines)
723
+
724
+ def generate_simple_function(self, operations: List[Dict]) -> str:
725
+ """Generate simplified function code from operations."""
726
+ if not operations:
727
+ return "keep_all()"
728
+
729
+ if len(operations) == 1 and operations[0]['operation'] == 'remove_all':
730
+ return "remove_all()"
731
+
732
+ func_lines = []
733
+ for op in operations:
734
+ if op['operation'] == 'remove_lines':
735
+ func_lines.append(f"remove_lines({op['start_line']}, {op['end_line']})")
736
+ elif op['operation'] == 'add_line':
737
+ content = op['content'] if op['content'].endswith('\n') else op['content'] + '\n'
738
+ func_lines.append(f"add_line({op['base_position']}, {op['sub_index']}, {repr(content)})")
739
+ elif op['operation'] == 'replace_str':
740
+ func_lines.append(f"replace_str({op['line_number']}, {repr(op['search_content'])}, {repr(op['replace_content'])})")
741
+
742
+ return '\n'.join(func_lines)
743
+
744
+
745
+ def get_combo_name(operations: List[Dict]) -> str:
746
+ if not operations:
747
+ return "keep_all"
748
+ if len(operations) == 1 and operations[0]['operation'] == 'remove_all':
749
+ return "remove_all"
750
+ return '_'.join(sorted(set(op['operation'] for op in operations)))
751
+
752
+
753
+ def process_single_file(parquet_file: Path, input_dir: Path, output_dir: Path) -> Dict:
754
+ """Process a single parquet file (for multiprocessing)."""
755
+ stats = {"processed": 0, "filtered": 0, "skipped": 0, "failed": 0}
756
+ relative_path = parquet_file.relative_to(input_dir)
757
+ output_json = output_dir / relative_path.with_suffix('.jsonl')
758
+ output_json.parent.mkdir(parents=True, exist_ok=True)
759
+
760
+ if output_json.exists():
761
+ try:
762
+ with open(output_json, 'r', encoding='utf-8') as f:
763
+ stats["processed"] = sum(1 for _ in f)
764
+ except Exception:
765
+ pass
766
+ return stats
767
+
768
+ cleaner = BatchDataCleaner()
769
+ results = []
770
+
771
+ try:
772
+ pf = pq.ParquetFile(parquet_file)
773
+
774
+ for batch in pf.iter_batches(batch_size=50):
775
+ df = batch.to_pandas()
776
+ required = ['original_content', 'refined_content', 'refinement_success']
777
+ if any(col not in df.columns for col in required):
778
+ continue
779
+
780
+ for _, row in df.iterrows():
781
+ if str(row['refinement_success']).strip().lower() not in ('yes', 'true', '1'):
782
+ stats["skipped"] += 1
783
+ continue
784
+
785
+ raw_original = row['original_content']
786
+ raw_refined = row['refined_content']
787
+ if raw_original is None or raw_refined is None:
788
+ stats["skipped"] += 1
789
+ continue
790
+ original_content = str(raw_original)
791
+ refined_content = str(raw_refined)
792
+ if original_content in ('nan', 'None', '') or refined_content in ('nan', 'None', ''):
793
+ stats["skipped"] += 1
794
+ continue
795
+
796
+ try:
797
+ operations = cleaner.analyze_line_operations(original_content, refined_content)
798
+
799
+ if not cleaner.filter_data(operations):
800
+ stats["filtered"] += 1
801
+ continue
802
+
803
+ combo_name = get_combo_name(operations)
804
+ marked_content = cleaner.add_line_id_markers(original_content)
805
+ simple_func = cleaner.generate_simple_function(operations)
806
+
807
+ result = {
808
+ "combo": combo_name,
809
+ "messages": [
810
+ {"role": "user", "content": marked_content},
811
+ {"role": "assistant", "content": "<think>\n\n</think>\n\n" + simple_func}
812
+ ]
813
+ }
814
+ results.append(result)
815
+ stats["processed"] += 1
816
+
817
+ except Exception as e:
818
+ stats["failed"] += 1
819
+ if stats["failed"] <= 3:
820
+ logger.warning(f"Error processing data ({relative_path}): {type(e).__name__}: {e}")
821
+
822
+ if results:
823
+ with open(output_json, 'w', encoding='utf-8') as f:
824
+ for result in results:
825
+ f.write(json.dumps(result, ensure_ascii=False) + '\n')
826
+
827
+ logger.info(f"Done: {relative_path}, processed={stats['processed']}, filtered={stats['filtered']}, skipped={stats['skipped']}, failed={stats['failed']}")
828
+
829
+ except Exception as e:
830
+ logger.error(f"Failed to process file {parquet_file.name}: {e}")
831
+
832
+ return stats
833
+
834
+
835
+ def merge_by_combo(output_dir: Path):
836
+ """Merge per-parquet JSONL files by function combo into by_combo/ directory."""
837
+ combo_dir = output_dir / "by_combo"
838
+ combo_dir.mkdir(parents=True, exist_ok=True)
839
+
840
+ combo_file_handles = {}
841
+ combo_counts = defaultdict(int)
842
+
843
+ raw_dirs = [d for d in output_dir.iterdir() if d.is_dir() and d.name != 'by_combo']
844
+ all_jsonl_files = []
845
+ for d in raw_dirs:
846
+ all_jsonl_files.extend(sorted(d.rglob("*.jsonl")))
847
+
848
+ logger.info(f"Merging by function combo, {len(all_jsonl_files)} files total...")
849
+
850
+ for jsonl_file in all_jsonl_files:
851
+ with open(jsonl_file, 'r', encoding='utf-8') as f:
852
+ for line in f:
853
+ line = line.strip()
854
+ if not line:
855
+ continue
856
+ try:
857
+ data = json.loads(line)
858
+ combo = data.pop("combo", "unknown")
859
+ clean_line = json.dumps(data, ensure_ascii=False)
860
+
861
+ if combo not in combo_file_handles:
862
+ combo_file_handles[combo] = open(
863
+ combo_dir / f"{combo}.jsonl", 'w', encoding='utf-8')
864
+ combo_file_handles[combo].write(clean_line + '\n')
865
+ combo_counts[combo] += 1
866
+ except Exception:
867
+ pass
868
+
869
+ for fh in combo_file_handles.values():
870
+ fh.close()
871
+
872
+ logger.info("=" * 50)
873
+ logger.info("Merge by function combo complete:")
874
+ total = sum(combo_counts.values())
875
+ for combo in sorted(combo_counts.keys()):
876
+ cnt = combo_counts[combo]
877
+ pct = cnt / total * 100 if total > 0 else 0
878
+ logger.info(f" {combo}.jsonl: {cnt} entries ({pct:.2f}%)")
879
+ logger.info(f" Total: {total} entries")
880
+ logger.info(f" Output directory: {combo_dir}")
881
+ logger.info("=" * 50)
882
+
883
+
884
+ def main():
885
+ parser = argparse.ArgumentParser(
886
+ description="LAM + DCR Function Construction: convert (original, refined) text pairs "
887
+ "into structured cleaning-function training data."
888
+ )
889
+ parser.add_argument("--input_dir", type=str, required=True,
890
+ help="Directory containing input parquet files with columns: "
891
+ "original_content, refined_content, refinement_success")
892
+ parser.add_argument("--output_dir", type=str, required=True,
893
+ help="Directory to write output JSONL training data")
894
+ parser.add_argument("--num_workers", type=int, default=64,
895
+ help="Number of parallel worker processes (default: 64)")
896
+ args = parser.parse_args()
897
+
898
+ input_dir = Path(args.input_dir)
899
+ output_dir = Path(args.output_dir)
900
+ output_dir.mkdir(parents=True, exist_ok=True)
901
+
902
+ parquet_files = sorted(input_dir.rglob("*.parquet"))
903
+ if not parquet_files:
904
+ logger.warning("No parquet files found")
905
+ return
906
+
907
+ total_files = len(parquet_files)
908
+ logger.info(f"Found {total_files} parquet files")
909
+ logger.info(f"Input directory: {input_dir}")
910
+ logger.info(f"Output directory: {output_dir}")
911
+
912
+ start_time = datetime.now()
913
+
914
+ total_stats = {"processed": 0, "filtered": 0, "skipped": 0, "failed": 0}
915
+ process_func = partial(process_single_file, input_dir=input_dir, output_dir=output_dir)
916
+
917
+ with Pool(processes=args.num_workers) as pool:
918
+ for i, stats in enumerate(pool.imap_unordered(process_func, parquet_files), 1):
919
+ for key in total_stats:
920
+ total_stats[key] += stats[key]
921
+ if i % 500 == 0 or i == total_files:
922
+ elapsed = (datetime.now() - start_time).total_seconds()
923
+ speed = i / elapsed if elapsed > 0 else 0
924
+ eta = (total_files - i) / speed if speed > 0 else 0
925
+ logger.info(f"Progress: {i}/{total_files} ({i/total_files*100:.1f}%) | "
926
+ f"Speed: {speed:.1f} files/sec | ETA: {eta/60:.1f} min | "
927
+ f"Processed: {total_stats['processed']} Filtered: {total_stats['filtered']}")
928
+
929
+ end_time = datetime.now()
930
+
931
+ logger.info("=" * 50)
932
+ logger.info("Processing complete")
933
+ logger.info(f"Total files: {total_files}")
934
+ logger.info(f"Processed: {total_stats['processed']} entries")
935
+ logger.info(f"Filtered: {total_stats['filtered']} entries")
936
+ logger.info(f"Skipped (not refined): {total_stats['skipped']} entries")
937
+ logger.info(f"Failed: {total_stats['failed']} entries")
938
+ logger.info(f"Elapsed time: {end_time - start_time}")
939
+ logger.info("=" * 50)
940
+
941
+ logger.info("Starting merge by combo...")
942
+ merge_by_combo(output_dir)
943
+
944
+ logger.info("All done!")
945
+
946
+
947
+ if __name__ == "__main__":
948
+ main()
code/stage1_model_construction/model_training/train.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # UltraX: Train the refinement model (Qwen3-0.6B full-parameter SFT)
3
+ # Framework: ms-swift with DeepSpeed ZeRO3
4
+ # Hardware: 8x GPU
5
+
6
+ # Activate your conda environment and navigate to ms-swift directory
7
+ # source /path/to/conda/etc/profile.d/conda.sh
8
+ # conda activate your_env
9
+ # cd /path/to/ms-swift
10
+
11
+ export PYTHONNOUSERSITE=1
12
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
13
+ export NPROC_PER_NODE=8
14
+
15
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 swift sft \
16
+ --model Qwen/Qwen3-0.6B \
17
+ --train_type full \
18
+ --loss_scale ignore_empty_think \
19
+ --dataset /path/to/train_data_with_instruction \
20
+ --torch_dtype bfloat16 \
21
+ --max_steps 5530 \
22
+ --streaming true \
23
+ --per_device_train_batch_size 24 \
24
+ --gradient_accumulation_steps 3 \
25
+ --learning_rate 3e-5 \
26
+ --warmup_ratio 0.03 \
27
+ --lr_scheduler_type cosine_with_min_lr \
28
+ --lr_scheduler_kwargs '{"min_lr": 3e-6}' \
29
+ --packing false \
30
+ --max_length 20480 \
31
+ --attn_impl flash_attn \
32
+ --save_steps 2765 \
33
+ --logging_steps 10 \
34
+ --dataloader_num_workers 8 \
35
+ --dataset_num_proc 8 \
36
+ --save_total_limit 3 \
37
+ --save_only_model true \
38
+ --output_dir /path/to/output_model \
39
+ --deepspeed zero3 \
40
+ --use_liger_kernel true
code/stage1_model_construction/prompt_optimization/api_client.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unified API client with concurrency support.
3
+
4
+ - REFINE_MODEL → End-to-end data refinement
5
+ - JUDGE_MODEL → Evaluation / Meta-Optimizer / Dataset profiling
6
+ """
7
+
8
+ import threading
9
+ import time
10
+ import logging
11
+ from concurrent.futures import ThreadPoolExecutor, as_completed
12
+
13
+ import requests
14
+
15
+ import config as cfg
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class LLMClient:
21
+ """Thread-safe wrapper with built-in concurrency pool."""
22
+
23
+ def __init__(self, api_key: str | None = None):
24
+ self.url = cfg.API_URL
25
+ self.headers = {
26
+ "Content-Type": "application/json",
27
+ "Authorization": f"Bearer {api_key or cfg.API_KEY}",
28
+ }
29
+ self._lock = threading.Lock()
30
+ self._total_calls = 0
31
+ self._total_tokens_est = 0
32
+
33
+ # ------------------------------------------------------------------
34
+ def call(
35
+ self,
36
+ system_prompt: str,
37
+ user_content: str = "",
38
+ *,
39
+ model: str | None = None,
40
+ max_tokens: int | None = None,
41
+ temperature: float | None = None,
42
+ ) -> str:
43
+ """Single chat completion request (thread-safe)."""
44
+ messages = [{"role": "system", "content": system_prompt}]
45
+ if user_content:
46
+ messages.append({"role": "user", "content": user_content})
47
+
48
+ resolved_model = model or cfg.REFINE_MODEL
49
+ if temperature is not None:
50
+ resolved_temp = temperature
51
+ elif resolved_model == cfg.REFINE_MODEL:
52
+ resolved_temp = cfg.REFINE_TEMPERATURE
53
+ else:
54
+ resolved_temp = cfg.JUDGE_TEMPERATURE
55
+
56
+ body = {
57
+ "model": resolved_model,
58
+ "messages": messages,
59
+ "temperature": resolved_temp,
60
+ "max_tokens": max_tokens or cfg.API_MAX_TOKENS,
61
+ "enable_thinking": False,
62
+ }
63
+
64
+ last_exc = None
65
+ for attempt in range(1, cfg.API_RETRY_TIMES + 1):
66
+ try:
67
+ resp = requests.post(
68
+ self.url,
69
+ json=body,
70
+ headers=self.headers,
71
+ timeout=cfg.API_TIMEOUT,
72
+ )
73
+ resp.raise_for_status()
74
+ data = resp.json()
75
+
76
+ content = data["choices"][0]["message"]["content"]
77
+
78
+ with self._lock:
79
+ self._total_calls += 1
80
+ usage = data.get("usage", {})
81
+ if usage:
82
+ self._total_tokens_est += usage.get("total_tokens", 0)
83
+
84
+ return content
85
+
86
+ except Exception as exc:
87
+ last_exc = exc
88
+ logger.warning(
89
+ "API [%s] attempt %d/%d failed: %s",
90
+ resolved_model,
91
+ attempt,
92
+ cfg.API_RETRY_TIMES,
93
+ exc,
94
+ )
95
+ if attempt < cfg.API_RETRY_TIMES:
96
+ time.sleep(cfg.API_RETRY_DELAY * attempt)
97
+
98
+ raise RuntimeError(
99
+ f"API call failed after {cfg.API_RETRY_TIMES} attempts: {last_exc}"
100
+ )
101
+
102
+ # ------------------------------------------------------------------
103
+ def call_batch(
104
+ self,
105
+ tasks: list[dict],
106
+ max_workers: int | None = None,
107
+ ) -> list[str]:
108
+ """
109
+ Concurrently execute multiple call() requests.
110
+
111
+ Parameters
112
+ ----------
113
+ tasks : list of dict
114
+ Each dict is passed as kwargs to call(), e.g.
115
+ {"system_prompt": "...", "user_content": "...", "model": "..."}
116
+ max_workers : int, optional
117
+ Concurrency limit. Defaults to cfg.API_CONCURRENCY.
118
+
119
+ Returns
120
+ -------
121
+ list[str] — results in the SAME order as *tasks*.
122
+ """
123
+ workers = max_workers or cfg.API_CONCURRENCY
124
+ results: list[str] = ["[REFINEMENT_ERROR]"] * len(tasks)
125
+
126
+ with ThreadPoolExecutor(max_workers=workers) as pool:
127
+ future_to_idx = {}
128
+ for idx, task in enumerate(tasks):
129
+ try:
130
+ future_to_idx[pool.submit(self.call, **task)] = idx
131
+ except Exception as exc:
132
+ logger.error("Failed to submit batch item %d: %s", idx, exc)
133
+
134
+ for future in as_completed(future_to_idx):
135
+ idx = future_to_idx[future]
136
+ try:
137
+ results[idx] = future.result()
138
+ except Exception as exc:
139
+ logger.error("Batch item %d failed: %s", idx, exc)
140
+
141
+ return results
142
+
143
+ # ------------------------------------------------------------------
144
+ @property
145
+ def stats(self) -> dict:
146
+ with self._lock:
147
+ return {
148
+ "total_calls": self._total_calls,
149
+ "total_tokens_est": self._total_tokens_est,
150
+ }
code/stage1_model_construction/prompt_optimization/config.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ # ============================================================
4
+ # API Configuration
5
+ # ============================================================
6
+ API_URL = os.environ.get("API_URL", "")
7
+ API_KEY = os.environ.get("API_KEY", "")
8
+
9
+ REFINE_MODEL = os.environ.get("REFINE_MODEL", "")
10
+ JUDGE_MODEL = os.environ.get("JUDGE_MODEL", "")
11
+
12
+ REFINE_TEMPERATURE = 0
13
+ JUDGE_TEMPERATURE = 0.4
14
+ API_MAX_TOKENS = 24000
15
+ API_TIMEOUT = 180
16
+ API_RETRY_TIMES = 5
17
+ API_RETRY_DELAY = 5
18
+ API_CONCURRENCY = 5
19
+ API_CONCURRENCY_TEST = 30
20
+
21
+ # ============================================================
22
+ # Data Paths
23
+ # ============================================================
24
+ BASE_DIR = os.environ.get("BASE_DIR", "")
25
+ SEED_DATA_DIR = os.path.join(BASE_DIR, "seed_data")
26
+ PROMPT_REFERENCE_DIR = os.path.join(BASE_DIR, "prompt_reference")
27
+ BASE_PROMPT_FILE = os.environ.get(
28
+ "BASE_PROMPT_FILE",
29
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "refinement_prompt_en.txt"),
30
+ )
31
+ OUTPUT_DIR = os.path.join(BASE_DIR, "prompt_optimizer_outputs")
32
+
33
+ # ============================================================
34
+ # Sampling
35
+ # ============================================================
36
+ OPT_SAMPLE_SIZE = 1000
37
+ TEST_SAMPLE_SIZE = 1000
38
+ TEXT_COLUMN = "content"
39
+
40
+ # ============================================================
41
+ # Optimization Loop
42
+ # ============================================================
43
+ MAX_ITERATIONS = 200
44
+ REFINE_BATCH_SIZE = 5
45
+ MAX_INNER_RETRIES = 5
code/stage1_model_construction/prompt_optimization/data_sampler.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Randomly sample records from each parquet-based dataset.
3
+
4
+ Key design: optimisation set and test set are drawn with **different
5
+ random seeds** so they are fully independent (no overlap).
6
+ """
7
+
8
+ import os
9
+ import random
10
+ import logging
11
+
12
+ import pyarrow.parquet as pq
13
+
14
+ import config as cfg
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ def list_datasets() -> list[str]:
20
+ """Return sorted list of dataset directory names."""
21
+ return sorted(
22
+ d
23
+ for d in os.listdir(cfg.SEED_DATA_DIR)
24
+ if os.path.isdir(os.path.join(cfg.SEED_DATA_DIR, d))
25
+ )
26
+
27
+
28
+ def _parquet_files(dataset_name: str) -> list[str]:
29
+ folder = os.path.join(cfg.SEED_DATA_DIR, dataset_name)
30
+ return sorted(
31
+ os.path.join(folder, f)
32
+ for f in os.listdir(folder)
33
+ if f.endswith(".parquet")
34
+ )
35
+
36
+
37
+ def _count_rows(files: list[str]) -> tuple[list[int], int]:
38
+ counts = []
39
+ total = 0
40
+ for pf in files:
41
+ c = pq.read_metadata(pf).num_rows
42
+ counts.append(c)
43
+ total += c
44
+ return counts, total
45
+
46
+
47
+ def _fetch_by_global_indices(
48
+ files: list[str],
49
+ file_row_counts: list[int],
50
+ indices: list[int],
51
+ ) -> list[str]:
52
+ """Load only the parquet files that contain requested rows."""
53
+ indices = sorted(indices)
54
+ texts: list[str] = []
55
+ cum = 0
56
+ ptr = 0
57
+ for pf, cnt in zip(files, file_row_counts):
58
+ local = []
59
+ while ptr < len(indices) and indices[ptr] < cum + cnt:
60
+ local.append(indices[ptr] - cum)
61
+ ptr += 1
62
+ if local:
63
+ col = pq.read_table(pf, columns=[cfg.TEXT_COLUMN]).column(cfg.TEXT_COLUMN)
64
+ for idx in local:
65
+ texts.append(col[idx].as_py())
66
+ cum += cnt
67
+ if ptr >= len(indices):
68
+ break
69
+ return texts
70
+
71
+
72
+ def sample_dataset_pair(
73
+ dataset_name: str,
74
+ opt_n: int = cfg.OPT_SAMPLE_SIZE,
75
+ test_n: int = cfg.TEST_SAMPLE_SIZE,
76
+ seed: int = 42,
77
+ ) -> tuple[list[str], list[str]]:
78
+ """
79
+ Draw two **non-overlapping** samples from *dataset_name* using a
80
+ single random draw then split.
81
+
82
+ Returns (optimisation_set, test_set).
83
+ """
84
+ files = _parquet_files(dataset_name)
85
+ if not files:
86
+ raise FileNotFoundError(f"No parquet files in dataset '{dataset_name}'")
87
+
88
+ file_row_counts, total_rows = _count_rows(files)
89
+
90
+ need = opt_n + test_n
91
+ if need > total_rows:
92
+ raise ValueError(
93
+ f"Dataset '{dataset_name}' has only {total_rows} rows, "
94
+ f"but {opt_n}+{test_n}={need} requested"
95
+ )
96
+
97
+ rng = random.Random(seed)
98
+ all_indices = rng.sample(range(total_rows), need)
99
+ opt_indices = all_indices[:opt_n]
100
+ test_indices = all_indices[opt_n:]
101
+
102
+ logger.info(
103
+ "Dataset %-45s rows=%d files=%d opt=%d test=%d",
104
+ dataset_name, total_rows, len(files), opt_n, test_n,
105
+ )
106
+
107
+ opt_texts = _fetch_by_global_indices(files, file_row_counts, opt_indices)
108
+ test_texts = _fetch_by_global_indices(files, file_row_counts, test_indices)
109
+
110
+ rng.shuffle(opt_texts)
111
+ rng.shuffle(test_texts)
112
+
113
+ return opt_texts, test_texts
code/stage1_model_construction/prompt_optimization/evaluator.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LLM-based quality evaluator for text refinement results.
3
+
4
+ Sends a batch of (original, refined) pairs to the judge model and
5
+ returns structured scores + issue descriptions that feed into the
6
+ meta-optimizer.
7
+ """
8
+
9
+ import json
10
+ import re
11
+ import logging
12
+
13
+ from api_client import LLMClient
14
+ import config as cfg
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ # ------------------------------------------------------------------ #
19
+ # Judge system prompt #
20
+ # ------------------------------------------------------------------ #
21
+ JUDGE_SYSTEM_PROMPT = """\
22
+ You are a strict Quality Assurance Judge for a **web-text cleaning pipeline**
23
+ whose sole purpose is to improve pre-training corpus quality.
24
+
25
+ CRITICAL CONTEXT — this is a CLEANING task, NOT a rewriting task:
26
+ - The model should ONLY delete noise (ads, navigation, HTML tags, boilerplate,
27
+ gibberish, engagement bait, contact info, etc.).
28
+ - Clean text that needs no modification MUST be output **exactly as-is**,
29
+ character-for-character. Any unnecessary rewriting, paraphrasing,
30
+ summarizing, or "style improvement" is a FAILURE.
31
+ - Completely valueless content (pure ads, gibberish, spam) should be
32
+ replaced with exactly: `[Content valueless, deleted]`
33
+
34
+ You will receive multiple (Original, Refined) text pairs. For **each** pair,
35
+ evaluate on these five dimensions (0-2 each, 10 total):
36
+
37
+ 1. **Noise Removal** (0-2)
38
+ 2 = all noise properly removed (ads, nav bars, boilerplate, HTML tags, gibberish)
39
+ 1 = some noise remains
40
+ 0 = significant noise left untouched
41
+
42
+ 2. **No Over-Editing** (0-2) ← MOST IMPORTANT
43
+ 2 = clean portions of the text are completely untouched; zero unnecessary changes
44
+ 1 = minor unnecessary edits (rephrasing, word changes, reordering)
45
+ 0 = significant rewriting, summarizing, or adding content not in the original
46
+
47
+ 3. **Content Preservation** (0-2)
48
+ 2 = all valuable content kept intact (nothing useful was deleted)
49
+ 1 = minor valuable content lost
50
+ 0 = significant content wrongly removed
51
+
52
+ 4. **Format Integrity** (0-2)
53
+ 2 = markdown headers, lists, tables, code blocks preserved correctly
54
+ 1 = minor format issues
55
+ 0 = structure broken or stripped
56
+
57
+ 5. **Valueless Detection** (0-2)
58
+ 2 = purely valueless content correctly tagged "[Content valueless, deleted]";
59
+ valuable content correctly kept
60
+ 1 = borderline call
61
+ 0 = wrong decision (valuable content deleted, or pure junk fully kept)
62
+
63
+ For each sample also list concrete **issues** (short phrases) and a
64
+ **severity** tag: "none", "minor", or "major".
65
+
66
+ Return **ONLY** valid JSON (no markdown fences, no explanation), schema:
67
+
68
+ {
69
+ "evaluations": [
70
+ {
71
+ "sample_id": <int>,
72
+ "scores": {
73
+ "noise_removal": <0-2>,
74
+ "no_over_editing": <0-2>,
75
+ "content_preservation": <0-2>,
76
+ "format_integrity": <0-2>,
77
+ "valueless_detection": <0-2>
78
+ },
79
+ "total_score": <0-10>,
80
+ "issues": ["issue description", ...],
81
+ "severity": "none|minor|major"
82
+ }
83
+ ]
84
+ }
85
+ """
86
+
87
+
88
+ # no truncation — full text sent to judge
89
+
90
+
91
+ # ------------------------------------------------------------------ #
92
+ # Evaluator class #
93
+ # ------------------------------------------------------------------ #
94
+ class RefinementEvaluator:
95
+ def __init__(self, client: LLMClient):
96
+ self.client = client
97
+
98
+ # ---- public API ------------------------------------------------
99
+ def evaluate_batch(
100
+ self,
101
+ originals: list[str],
102
+ refinements: list[str],
103
+ ) -> list[dict]:
104
+ """Evaluate a batch; returns list of per-sample dicts."""
105
+ user_msg = self._build_user_message(originals, refinements)
106
+ try:
107
+ raw = self.client.call(
108
+ system_prompt=JUDGE_SYSTEM_PROMPT,
109
+ user_content=user_msg,
110
+ model=cfg.JUDGE_MODEL,
111
+ )
112
+ return self._parse(raw, len(originals))
113
+ except Exception as exc:
114
+ logger.error("Batch evaluation failed: %s", exc)
115
+ return self._defaults(len(originals))
116
+
117
+ def summarize(self, evaluations: list[dict]) -> dict:
118
+ """Aggregate per-sample evaluations into a compact summary."""
119
+ scores = [e.get("total_score", 5) for e in evaluations]
120
+ avg = sum(scores) / len(scores) if scores else 0.0
121
+
122
+ severity_cnt = {"none": 0, "minor": 0, "major": 0}
123
+ issue_freq: dict[str, int] = {}
124
+ for e in evaluations:
125
+ sev = e.get("severity", "minor")
126
+ severity_cnt[sev] = severity_cnt.get(sev, 0) + 1
127
+ for iss in e.get("issues", []):
128
+ issue_freq[iss] = issue_freq.get(iss, 0) + 1
129
+
130
+ return {
131
+ "avg_score": round(avg, 2),
132
+ "severity_distribution": severity_cnt,
133
+ "top_issues": sorted(issue_freq.items(), key=lambda x: -x[1])[:10],
134
+ "total_samples": len(evaluations),
135
+ "major_count": severity_cnt.get("major", 0),
136
+ }
137
+
138
+ # ---- internal --------------------------------------------------
139
+ def _build_user_message(self, originals, refinements):
140
+ parts = []
141
+ for i, (o, r) in enumerate(zip(originals, refinements)):
142
+ parts.append(
143
+ f"=== Sample {i} ===\n"
144
+ f"[Original]\n{o}\n\n"
145
+ f"[Refined]\n{r}\n"
146
+ )
147
+ return "\n".join(parts)
148
+
149
+ def _parse(self, raw: str, n: int) -> list[dict]:
150
+ try:
151
+ m = re.search(r"\{[\s\S]*\}", raw)
152
+ if m:
153
+ data = json.loads(m.group())
154
+ evals = data.get("evaluations", [])
155
+ if len(evals) == n:
156
+ return evals
157
+ logger.warning(
158
+ "Judge returned %d evaluations, expected %d", len(evals), n
159
+ )
160
+ if evals:
161
+ return evals
162
+ except json.JSONDecodeError:
163
+ logger.warning("Judge response is not valid JSON")
164
+ return self._defaults(n)
165
+
166
+ @staticmethod
167
+ def _defaults(n: int) -> list[dict]:
168
+ return [
169
+ {
170
+ "sample_id": i,
171
+ "scores": {
172
+ "noise_removal": 1,
173
+ "no_over_editing": 1,
174
+ "content_preservation": 1,
175
+ "format_integrity": 1,
176
+ "valueless_detection": 1,
177
+ },
178
+ "total_score": 5,
179
+ "issues": ["evaluation_parse_failed"],
180
+ "severity": "minor",
181
+ }
182
+ for i in range(n)
183
+ ]
code/stage1_model_construction/prompt_optimization/main.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ End-to-End Data Refinement Prompt Auto-Optimizer
4
+ =================================================
5
+
6
+ For each dataset in seed_data_sample_split_12k:
7
+ 1. Independently sample 100 texts for optimisation + 100 for testing
8
+ 2. Profile the dataset's dirty-data patterns
9
+ 3. Iteratively optimise a refinement prompt via multi-round LLM feedback
10
+ 4. Evaluate the best prompt on the independent test set
11
+ 5. Persist everything (samples, intermediate outputs, prompts, scores)
12
+
13
+ Usage:
14
+ # Optimise all datasets
15
+ python main.py --api-key <KEY>
16
+
17
+ # Optimise specific datasets
18
+ python main.py --api-key <KEY> --datasets fineweb stack_overflow
19
+
20
+ # Customise parameters
21
+ python main.py --api-key <KEY> --max-iterations 3 --batch-size 8
22
+
23
+ # Resume (skip datasets whose outputs already exist)
24
+ python main.py --api-key <KEY> --resume
25
+ """
26
+
27
+ import os
28
+ import sys
29
+ import json
30
+ import argparse
31
+ import logging
32
+ from datetime import datetime
33
+
34
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
35
+
36
+ import config as cfg
37
+ from api_client import LLMClient
38
+ from data_sampler import list_datasets, sample_dataset_pair
39
+ from optimizer import PromptOptimizer
40
+
41
+
42
+ def setup_logging():
43
+ logging.basicConfig(
44
+ level=logging.INFO,
45
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
46
+ handlers=[
47
+ logging.StreamHandler(sys.stdout),
48
+ ],
49
+ )
50
+
51
+
52
+ def load_reference_prompts() -> dict[str, str]:
53
+ prompts: dict[str, str] = {}
54
+ for fname in sorted(os.listdir(cfg.PROMPT_REFERENCE_DIR)):
55
+ if fname.endswith(".txt"):
56
+ with open(
57
+ os.path.join(cfg.PROMPT_REFERENCE_DIR, fname), "r", encoding="utf-8"
58
+ ) as f:
59
+ prompts[fname] = f.read()
60
+ return prompts
61
+
62
+
63
+ def load_base_prompt() -> str:
64
+ with open(cfg.BASE_PROMPT_FILE, "r", encoding="utf-8") as f:
65
+ return f.read()
66
+
67
+
68
+ def parse_args():
69
+ p = argparse.ArgumentParser(
70
+ description="End-to-End Data Refinement Prompt Auto-Optimizer"
71
+ )
72
+ p.add_argument("--api-key", type=str, default=None,
73
+ help="DeepSeek API key (or set DEEPSEEK_API_KEY env var)")
74
+ p.add_argument("--datasets", nargs="*", default=None,
75
+ help="Specific dataset names to optimise (default: all)")
76
+ p.add_argument("--max-iterations", type=int, default=None,
77
+ help=f"Max optimisation iterations (default: {cfg.MAX_ITERATIONS})")
78
+ p.add_argument("--batch-size", type=int, default=None,
79
+ help=f"Refinement batch size per iteration (default: {cfg.REFINE_BATCH_SIZE})")
80
+ p.add_argument("--opt-samples", type=int, default=None,
81
+ help=f"Optimisation samples per dataset (default: {cfg.OPT_SAMPLE_SIZE})")
82
+ p.add_argument("--test-samples", type=int, default=None,
83
+ help=f"Test samples per dataset (default: {cfg.TEST_SAMPLE_SIZE})")
84
+ p.add_argument("--resume", action="store_true",
85
+ help="Skip datasets that already have optimized_prompt.txt")
86
+ return p.parse_args()
87
+
88
+
89
+ def apply_overrides(args):
90
+ if args.api_key:
91
+ cfg.API_KEY = args.api_key
92
+ if args.opt_samples is not None:
93
+ cfg.OPT_SAMPLE_SIZE = args.opt_samples
94
+ if args.test_samples is not None:
95
+ cfg.TEST_SAMPLE_SIZE = args.test_samples
96
+
97
+ if args.batch_size is not None:
98
+ cfg.REFINE_BATCH_SIZE = args.batch_size
99
+ if args.max_iterations is not None:
100
+ cfg.MAX_ITERATIONS = args.max_iterations
101
+ else:
102
+ # Ensure MAX_ITERATIONS × REFINE_BATCH_SIZE == OPT_SAMPLE_SIZE
103
+ cfg.MAX_ITERATIONS = max(1, cfg.OPT_SAMPLE_SIZE // cfg.REFINE_BATCH_SIZE)
104
+
105
+
106
+ def main():
107
+ args = parse_args()
108
+ apply_overrides(args)
109
+
110
+ setup_logging()
111
+ logger = logging.getLogger("main")
112
+
113
+ logger.info("=" * 70)
114
+ logger.info(" End-to-End Data Refinement Prompt Auto-Optimizer")
115
+ logger.info("=" * 70)
116
+ logger.info(" Refine model : %s (temp=%.1f)", cfg.REFINE_MODEL, cfg.REFINE_TEMPERATURE)
117
+ logger.info(" Judge model : %s (temp=%.1f)", cfg.JUDGE_MODEL, cfg.JUDGE_TEMPERATURE)
118
+ logger.info(" Opt samples : %d", cfg.OPT_SAMPLE_SIZE)
119
+ logger.info(" Test samples : %d", cfg.TEST_SAMPLE_SIZE)
120
+ logger.info(" Max iterations : %d", cfg.MAX_ITERATIONS)
121
+ logger.info(" Batch size : %d", cfg.REFINE_BATCH_SIZE)
122
+ logger.info(" Coverage : %d × %d = %d / %d opt samples",
123
+ cfg.MAX_ITERATIONS, cfg.REFINE_BATCH_SIZE,
124
+ cfg.MAX_ITERATIONS * cfg.REFINE_BATCH_SIZE, cfg.OPT_SAMPLE_SIZE)
125
+ logger.info(" Max tokens (out) : %d", cfg.API_MAX_TOKENS)
126
+ logger.info("=" * 70)
127
+
128
+ if not cfg.API_KEY:
129
+ logger.error(
130
+ "No API key provided. Set DEEPSEEK_API_KEY env var or pass --api-key"
131
+ )
132
+ sys.exit(1)
133
+
134
+ reference_prompts = load_reference_prompts()
135
+ base_prompt = load_base_prompt()
136
+ logger.info(
137
+ "Loaded %d reference prompts, base prompt len=%d",
138
+ len(reference_prompts),
139
+ len(base_prompt),
140
+ )
141
+
142
+ client = LLMClient()
143
+ optimizer = PromptOptimizer(client, reference_prompts)
144
+
145
+ all_ds = list_datasets()
146
+ targets = args.datasets if args.datasets else all_ds
147
+ invalid = set(targets) - set(all_ds)
148
+ if invalid:
149
+ logger.error("Unknown datasets: %s", invalid)
150
+ sys.exit(1)
151
+
152
+ if args.resume:
153
+ already = [
154
+ d
155
+ for d in targets
156
+ if os.path.isfile(
157
+ os.path.join(cfg.OUTPUT_DIR, d, "optimized_prompt.txt")
158
+ )
159
+ ]
160
+ if already:
161
+ logger.info(
162
+ "Resuming — skipping %d completed: %s", len(already), already
163
+ )
164
+ targets = [d for d in targets if d not in already]
165
+
166
+ logger.info("Datasets to optimise (%d): %s", len(targets), targets)
167
+
168
+ results = []
169
+ for idx, ds in enumerate(targets):
170
+ logger.info("\n" + "#" * 70)
171
+ logger.info("# [%d/%d] %s", idx + 1, len(targets), ds)
172
+ logger.info("#" * 70)
173
+
174
+ try:
175
+ opt_set, test_set = sample_dataset_pair(
176
+ ds,
177
+ opt_n=cfg.OPT_SAMPLE_SIZE,
178
+ test_n=cfg.TEST_SAMPLE_SIZE,
179
+ )
180
+ logger.info(
181
+ " Sampled: opt=%d test=%d (independent, no overlap)",
182
+ len(opt_set),
183
+ len(test_set),
184
+ )
185
+
186
+ result = optimizer.optimize_dataset(
187
+ dataset_name=ds,
188
+ optimization_set=opt_set,
189
+ test_set=test_set,
190
+ base_prompt=base_prompt,
191
+ )
192
+ results.append(result)
193
+
194
+ except Exception as exc:
195
+ logger.error("Dataset %s FAILED: %s", ds, exc, exc_info=True)
196
+ results.append({"dataset": ds, "error": str(exc)})
197
+
198
+ # ---- overall summary ----
199
+ summary = {
200
+ "run_time": datetime.now().isoformat(),
201
+ "config": {
202
+ "refine_model": cfg.REFINE_MODEL,
203
+ "judge_model": cfg.JUDGE_MODEL,
204
+ "refine_temperature": cfg.REFINE_TEMPERATURE,
205
+ "judge_temperature": cfg.JUDGE_TEMPERATURE,
206
+ "max_iterations": cfg.MAX_ITERATIONS,
207
+ "batch_size": cfg.REFINE_BATCH_SIZE,
208
+ "opt_samples": cfg.OPT_SAMPLE_SIZE,
209
+ "test_samples": cfg.TEST_SAMPLE_SIZE,
210
+ },
211
+ "api_stats": client.stats,
212
+ "results": results,
213
+ }
214
+ os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)
215
+ summary_path = os.path.join(cfg.OUTPUT_DIR, "optimization_summary.json")
216
+ with open(summary_path, "w", encoding="utf-8") as f:
217
+ json.dump(summary, f, ensure_ascii=False, indent=2)
218
+
219
+ logger.info("\n" + "=" * 70)
220
+ logger.info(" OPTIMIZATION COMPLETE")
221
+ logger.info("=" * 70)
222
+ for r in results:
223
+ if "error" in r:
224
+ logger.info(" %-50s FAILED %s", r["dataset"], r["error"][:60])
225
+ else:
226
+ logger.info(
227
+ " %-50s score=%.2f iters=%d",
228
+ r["dataset"],
229
+ r["final_score"],
230
+ r["iterations"],
231
+ )
232
+ logger.info(" Summary → %s", summary_path)
233
+ logger.info(
234
+ " API calls: %d tokens(est): %d",
235
+ client.stats["total_calls"],
236
+ client.stats["total_tokens_est"],
237
+ )
238
+ logger.info("=" * 70)
239
+
240
+
241
+ if __name__ == "__main__":
242
+ main()
code/stage1_model_construction/prompt_optimization/optimizer.py ADDED
@@ -0,0 +1,672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Core prompt-optimization agent.
3
+
4
+ For every dataset the loop is:
5
+ 0. Profile the dataset to understand its dirty-data patterns
6
+ 1. Refine a batch with the current prompt
7
+ 2. Judge the refinements (score + issues)
8
+ 3. Feed failures + dataset profile into a meta-optimizer that rewrites the prompt
9
+ 4. Validate the new prompt on a held-out mini-batch
10
+ 5. Repeat until convergence or MAX_ITERATIONS
11
+
12
+ After the loop the best prompt is evaluated on the **independent** 100-sample
13
+ test set and everything (samples, intermediate refinements, prompts) is
14
+ persisted to OUTPUT_DIR/<dataset>/.
15
+ """
16
+
17
+ import os
18
+ import re
19
+ import json
20
+ import time
21
+ import random
22
+ import logging
23
+ from datetime import datetime
24
+
25
+ from api_client import LLMClient
26
+ from evaluator import RefinementEvaluator
27
+ import config as cfg
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ # ------------------------------------------------------------------ #
33
+ # Dataset profiling prompt #
34
+ # ------------------------------------------------------------------ #
35
+ PROFILE_SYSTEM_PROMPT = """\
36
+ You are a data-quality analyst. You will receive 15 sample texts from a web
37
+ dataset called "{dataset_name}".
38
+
39
+ Produce a JSON profile with these fields (no markdown fences):
40
+ {{
41
+ "dominant_language": "en|zh|mixed|...",
42
+ "content_types": ["article", "forum_post", "code_qa", "product_page", ...],
43
+ "common_noise_patterns": ["navigation bars", "cookie banners", ...],
44
+ "has_code_blocks": true/false,
45
+ "has_tables": true/false,
46
+ "has_math": true/false,
47
+ "avg_quality_impression": "high|medium|low",
48
+ "special_notes": "free text with anything else noteworthy"
49
+ }}
50
+ Be concise. Output ONLY the JSON object.
51
+ """
52
+
53
+
54
+ # ------------------------------------------------------------------ #
55
+ # Meta-optimizer system prompt #
56
+ # ------------------------------------------------------------------ #
57
+ META_SYSTEM_TEMPLATE = """\
58
+ You are a world-class Prompt Engineering Expert.
59
+
60
+ ## Task Context — CRITICAL
61
+ This is a **pre-training corpus CLEANING pipeline**, NOT a rewriting pipeline.
62
+ The fundamental principles are:
63
+ - **Delete only**: remove noise (ads, navigation, HTML, boilerplate, gibberish,
64
+ engagement bait, contact info, broken formatting).
65
+ - **Never rewrite**: clean text must be output character-for-character unchanged.
66
+ No paraphrasing, no summarizing, no "style improvement", no rearranging.
67
+ - **Valueless → delete marker**: purely valueless content (all-ads, pure spam,
68
+ gibberish) should produce exactly `[Content valueless, deleted]`.
69
+ - **Already-clean → pass through**: if the original needs zero changes, output
70
+ it exactly as-is.
71
+
72
+ ## Goal
73
+ Improve the **Data Cleaning Prompt** so it produces higher-quality outputs on
74
+ the "{dataset_name}" dataset.
75
+
76
+ ## Dataset Profile
77
+ {dataset_profile}
78
+
79
+ ## Optimization round {iteration}/{max_iter}
80
+
81
+ ────────────────────────────────────────
82
+ ## Current Prompt Being Optimized
83
+ <CURRENT_PROMPT>
84
+ {current_prompt}
85
+ </CURRENT_PROMPT>
86
+ ────────────────────────────────────────
87
+
88
+ ## Performance on this round's batch
89
+ - Average quality score : {avg_score} / 10
90
+ - Samples with MAJOR issues : {major_count} / {total_samples}
91
+ - Most frequent issues : {top_issues}
92
+
93
+ ## Problematic Examples (original → model output → issues)
94
+ {examples_block}
95
+
96
+ ## Reference Techniques from Other Prompts
97
+ {reference_block}
98
+
99
+ ────────────────────────────────────────
100
+ ## Instructions
101
+
102
+ 1. **Diagnose** — identify root causes. Pay special attention to:
103
+ - Over-editing: did the model rewrite or rephrase clean text?
104
+ - Under-cleaning: did noise survive that should have been removed?
105
+ - Wrong deletions: was valuable content incorrectly removed?
106
+ 2. **Prescribe** — tailor rules to the **Dataset Profile** (e.g. this
107
+ dataset's specific noise patterns, content types, formatting conventions).
108
+ 3. **Output** — the COMPLETE improved prompt between
109
+ `<IMPROVED_PROMPT>` and `</IMPROVED_PROMPT>` tags.
110
+
111
+ Rules for the improved prompt:
112
+ - The output contract is: either the cleaned text or `[Content valueless, deleted]`.
113
+ - Emphasize the NO-REWRITE principle — the single most common failure mode.
114
+ - Preserve rules that already work; only add/modify for observed failures.
115
+ - Add dataset-specific guidance (e.g. how to handle code blocks, tables, Q&A
116
+ threads, academic metadata, forum signatures, etc. for THIS dataset).
117
+ - If adding examples, keep them short and representative.
118
+ - Prompt language MUST remain English.
119
+ - Do NOT add conflicting rules.
120
+ """
121
+
122
+
123
+ def _write_json(path: str, obj):
124
+ with open(path, "w", encoding="utf-8") as f:
125
+ json.dump(obj, f, ensure_ascii=False, indent=2)
126
+
127
+
128
+ def _write_text(path: str, text: str):
129
+ with open(path, "w", encoding="utf-8") as f:
130
+ f.write(text)
131
+
132
+
133
+ # ------------------------------------------------------------------ #
134
+ # Optimizer class #
135
+ # ------------------------------------------------------------------ #
136
+ class PromptOptimizer:
137
+ def __init__(
138
+ self,
139
+ client: LLMClient,
140
+ reference_prompts: dict[str, str],
141
+ ):
142
+ self.client = client
143
+ self.evaluator = RefinementEvaluator(client)
144
+ self.reference_prompts = reference_prompts
145
+
146
+ # ================================================================ #
147
+ # Public entry point #
148
+ # ================================================================ #
149
+ def optimize_dataset(
150
+ self,
151
+ dataset_name: str,
152
+ optimization_set: list[str],
153
+ test_set: list[str],
154
+ base_prompt: str,
155
+ ) -> dict:
156
+ out_dir = os.path.join(cfg.OUTPUT_DIR, dataset_name)
157
+ samples_dir = os.path.join(out_dir, "sampled_data")
158
+ iters_dir = os.path.join(out_dir, "iterations")
159
+ prompts_dir = os.path.join(out_dir, "prompts")
160
+ for d in (out_dir, samples_dir, iters_dir, prompts_dir):
161
+ os.makedirs(d, exist_ok=True)
162
+
163
+ # ---- persist raw sampled data ----
164
+ self._save_raw_samples(samples_dir, optimization_set, test_set)
165
+
166
+ # ---- Step 0: profile dataset ----
167
+ logger.info("=" * 64)
168
+ logger.info(" Dataset : %s", dataset_name)
169
+ logger.info(" Opt set : %d Test set : %d", len(optimization_set), len(test_set))
170
+ logger.info("=" * 64)
171
+
172
+ dataset_profile = self._profile_dataset(dataset_name, optimization_set)
173
+ _write_json(os.path.join(out_dir, "dataset_profile.json"), dataset_profile)
174
+ logger.info(" [profile] %s", json.dumps(dataset_profile, ensure_ascii=False)[:300])
175
+
176
+ # ---- save initial prompt (iteration 0) ----
177
+ _write_text(os.path.join(prompts_dir, "prompt_iter_0_base.txt"), base_prompt)
178
+
179
+ current_prompt = base_prompt
180
+
181
+ log_record = {
182
+ "dataset": dataset_name,
183
+ "started_at": datetime.now().isoformat(),
184
+ "base_prompt_len": len(base_prompt),
185
+ "optimization_set_size": len(optimization_set),
186
+ "test_set_size": len(test_set),
187
+ "dataset_profile": dataset_profile,
188
+ "iterations": [],
189
+ }
190
+
191
+ for it in range(cfg.MAX_ITERATIONS):
192
+ t0 = time.time()
193
+ logger.info("── iteration %d/%d ──", it + 1, cfg.MAX_ITERATIONS)
194
+
195
+ iter_out = os.path.join(iters_dir, f"iter_{it + 1}")
196
+ os.makedirs(iter_out, exist_ok=True)
197
+
198
+ # --- 1. pick a batch (rotate through the optimization set) ---
199
+ start = (it * cfg.REFINE_BATCH_SIZE) % len(optimization_set)
200
+ batch = optimization_set[start : start + cfg.REFINE_BATCH_SIZE]
201
+ if len(batch) < cfg.REFINE_BATCH_SIZE:
202
+ batch += optimization_set[: cfg.REFINE_BATCH_SIZE - len(batch)]
203
+
204
+ # --- 2. refine ---
205
+ logger.info(" [refine] %d samples (attempt 0) ...", len(batch))
206
+ refinements = self._refine_batch(batch, current_prompt)
207
+ batch, refinements = self._exclude_failures(batch, refinements)
208
+
209
+ if not batch:
210
+ logger.warning(" [skip] all samples API-failed, skipping iteration")
211
+ _write_text(os.path.join(prompts_dir, f"prompt_iter_{it + 1}.txt"), current_prompt)
212
+ log_record["iterations"].append({
213
+ "iteration": it + 1, "batch_avg_score": 0, "inner_retries": 0,
214
+ "regression_score": None, "regression_retries": 0,
215
+ "top_issues": [["all_api_failed", cfg.REFINE_BATCH_SIZE]],
216
+ "prompt_len": len(current_prompt), "elapsed_sec": round(time.time() - t0, 1),
217
+ })
218
+ continue
219
+
220
+ # --- persist attempt 0 ---
221
+ self._save_iteration_pairs(iter_out, "refine_attempt_0", batch, refinements)
222
+
223
+ # --- 3. evaluate ---
224
+ logger.info(" [eval] judging quality (attempt 0, %d samples) ...", len(batch))
225
+ evals = self._evaluate_in_chunks(batch, refinements)
226
+ summary = self.evaluator.summarize(evals)
227
+ _write_json(os.path.join(iter_out, "eval_scores_attempt_0.json"), {
228
+ "summary": summary,
229
+ "per_sample": evals,
230
+ })
231
+ logger.info(
232
+ " [eval] avg_score=%.2f major=%d",
233
+ summary["avg_score"],
234
+ summary["major_count"],
235
+ )
236
+
237
+ # --- 4. inner loop: fix problems on THIS batch ---
238
+ actual_retries = 0
239
+ for retry in range(cfg.MAX_INNER_RETRIES):
240
+ problems = [
241
+ (o, r, e)
242
+ for o, r, e in zip(batch, refinements, evals)
243
+ if e.get("total_score", 10) < 8
244
+ or e.get("severity") in ("major", "minor")
245
+ ]
246
+
247
+ all_fallback = all(
248
+ "evaluation_parse_failed" in e.get("issues", []) for e in evals
249
+ )
250
+
251
+ if not problems:
252
+ logger.info(" [fix] all %d samples clean, moving on", len(batch))
253
+ break
254
+
255
+ if all_fallback:
256
+ logger.warning(" [fix] eval API failed, cannot fix this round")
257
+ break
258
+
259
+ logger.info(
260
+ " [fix] retry %d/%d — %d problems remain (avg=%.2f) ...",
261
+ retry + 1, cfg.MAX_INNER_RETRIES, len(problems), summary["avg_score"],
262
+ )
263
+
264
+ new_prompt = self._meta_optimize(
265
+ dataset_name, dataset_profile, current_prompt,
266
+ problems, summary, it,
267
+ )
268
+ if new_prompt and len(new_prompt) > 200 and new_prompt != current_prompt:
269
+ current_prompt = new_prompt
270
+ logger.info(" [fix] prompt updated (len=%d)", len(current_prompt))
271
+ else:
272
+ logger.info(" [fix] prompt unchanged, stopping inner loop")
273
+ break
274
+
275
+ logger.info(" [fix] re-refining %d samples ...", len(batch))
276
+ refinements = self._refine_batch(batch, current_prompt)
277
+ batch, refinements = self._exclude_failures(batch, refinements)
278
+ if not batch:
279
+ logger.warning(" [fix] all failed on re-refine, stopping inner loop")
280
+ break
281
+
282
+ logger.info(" [fix] re-evaluating ...")
283
+ evals = self._evaluate_in_chunks(batch, refinements)
284
+ summary = self.evaluator.summarize(evals)
285
+
286
+ actual_retries += 1
287
+ attempt_tag = f"attempt_{actual_retries}"
288
+ self._save_iteration_pairs(iter_out, f"refine_{attempt_tag}", batch, refinements)
289
+ _write_json(os.path.join(iter_out, f"eval_scores_{attempt_tag}.json"), {
290
+ "summary": summary,
291
+ "per_sample": evals,
292
+ })
293
+ logger.info(
294
+ " [fix] after retry %d: avg_score=%.2f major=%d",
295
+ actual_retries, summary["avg_score"], summary["major_count"],
296
+ )
297
+ else:
298
+ remaining = [
299
+ e for e in evals
300
+ if e.get("total_score", 10) < 8 or e.get("severity") in ("major", "minor")
301
+ ]
302
+ if remaining:
303
+ logger.warning(
304
+ " [fix] max retries reached, %d problems unresolved", len(remaining)
305
+ )
306
+
307
+ # --- 5. regression check: test on 5 random historical samples ---
308
+ regression_score = None
309
+ regression_retries = 0
310
+ if actual_retries > 0 and it > 0:
311
+ past_end = it * cfg.REFINE_BATCH_SIZE
312
+ past_pool = optimization_set[:past_end]
313
+ reg_size = min(5, len(past_pool))
314
+ reg_batch = random.sample(past_pool, reg_size)
315
+
316
+ logger.info(" [regr] testing %d historical samples ...", reg_size)
317
+ reg_refs = self._refine_batch(reg_batch, current_prompt)
318
+ reg_batch, reg_refs = self._exclude_failures(reg_batch, reg_refs)
319
+
320
+ if not reg_batch:
321
+ logger.warning(" [regr] all regression samples API-failed, skipping regression")
322
+ else:
323
+ reg_evals = self._evaluate_in_chunks(reg_batch, reg_refs)
324
+ reg_summary = self.evaluator.summarize(reg_evals)
325
+ regression_score = reg_summary["avg_score"]
326
+
327
+ self._save_iteration_pairs(iter_out, "regression_attempt_0", reg_batch, reg_refs)
328
+ _write_json(os.path.join(iter_out, "regression_scores_attempt_0.json"), {
329
+ "summary": reg_summary,
330
+ "per_sample": reg_evals,
331
+ })
332
+
333
+ reg_problems = [
334
+ (o, r, e) for o, r, e in zip(reg_batch, reg_refs, reg_evals)
335
+ if e.get("total_score", 10) < 8 or e.get("severity") in ("major", "minor")
336
+ ]
337
+
338
+ if not reg_problems:
339
+ logger.info(" [regr] no regression (avg=%.2f)", regression_score)
340
+ else:
341
+ logger.warning(
342
+ " [regr] regression detected! %d/%d degraded (avg=%.2f)",
343
+ len(reg_problems), reg_size, regression_score,
344
+ )
345
+ for reg_retry in range(cfg.MAX_INNER_RETRIES):
346
+ logger.info(
347
+ " [regr] fix retry %d/%d — feeding %d regressed samples to meta ...",
348
+ reg_retry + 1, cfg.MAX_INNER_RETRIES, len(reg_problems),
349
+ )
350
+ new_prompt = self._meta_optimize(
351
+ dataset_name, dataset_profile, current_prompt,
352
+ reg_problems, reg_summary, it,
353
+ )
354
+ if new_prompt and len(new_prompt) > 200 and new_prompt != current_prompt:
355
+ current_prompt = new_prompt
356
+ logger.info(" [regr] prompt updated (len=%d)", len(current_prompt))
357
+ else:
358
+ logger.info(" [regr] prompt unchanged, stopping")
359
+ break
360
+
361
+ reg_refs = self._refine_batch(reg_batch, current_prompt)
362
+ reg_batch, reg_refs = self._exclude_failures(reg_batch, reg_refs)
363
+ if not reg_batch:
364
+ logger.warning(" [regr] all failed on re-refine, stopping")
365
+ break
366
+ reg_evals = self._evaluate_in_chunks(reg_batch, reg_refs)
367
+ reg_summary = self.evaluator.summarize(reg_evals)
368
+ regression_score = reg_summary["avg_score"]
369
+ regression_retries += 1
370
+
371
+ rtag = f"attempt_{regression_retries}"
372
+ self._save_iteration_pairs(iter_out, f"regression_{rtag}", reg_batch, reg_refs)
373
+ _write_json(os.path.join(iter_out, f"regression_scores_{rtag}.json"), {
374
+ "summary": reg_summary,
375
+ "per_sample": reg_evals,
376
+ })
377
+
378
+ reg_problems = [
379
+ (o, r, e) for o, r, e in zip(reg_batch, reg_refs, reg_evals)
380
+ if e.get("total_score", 10) < 8 or e.get("severity") in ("major", "minor")
381
+ ]
382
+ if not reg_problems:
383
+ logger.info(" [regr] regression fixed (avg=%.2f)", regression_score)
384
+ break
385
+ logger.info(
386
+ " [regr] after retry %d: %d still degraded (avg=%.2f)",
387
+ regression_retries, len(reg_problems), regression_score,
388
+ )
389
+ else:
390
+ if reg_problems:
391
+ logger.warning(" [regr] max retries, %d regressions unresolved", len(reg_problems))
392
+
393
+ # --- save this iteration's prompt ---
394
+ _write_text(
395
+ os.path.join(prompts_dir, f"prompt_iter_{it + 1}.txt"),
396
+ current_prompt,
397
+ )
398
+
399
+ elapsed = time.time() - t0
400
+ iter_log = {
401
+ "iteration": it + 1,
402
+ "batch_avg_score": summary["avg_score"],
403
+ "inner_retries": actual_retries,
404
+ "regression_score": regression_score,
405
+ "regression_retries": regression_retries,
406
+ "top_issues": summary["top_issues"][:5],
407
+ "prompt_len": len(current_prompt),
408
+ "elapsed_sec": round(elapsed, 1),
409
+ }
410
+ log_record["iterations"].append(iter_log)
411
+
412
+ # ---- final test: use the latest current_prompt (accumulated improvements) ----
413
+ logger.info("── final test (%d independent samples) ──", len(test_set))
414
+
415
+ test_dir = os.path.join(out_dir, "final_test")
416
+ os.makedirs(test_dir, exist_ok=True)
417
+
418
+ test_refs = self._refine_batch(test_set, current_prompt, concurrency=cfg.API_CONCURRENCY_TEST)
419
+ test_evals = self._evaluate_in_chunks(test_set, test_refs, chunk_size=5, concurrency=cfg.API_CONCURRENCY_TEST)
420
+ test_summary = self.evaluator.summarize(test_evals)
421
+ logger.info(" final test score: %.2f / 10", test_summary["avg_score"])
422
+
423
+ # --- persist ALL test pairs (full text, not truncated) ---
424
+ self._save_iteration_pairs(test_dir, "test", test_set, test_refs)
425
+ _write_json(os.path.join(test_dir, "test_eval_scores.json"), {
426
+ "summary": test_summary,
427
+ "per_sample": test_evals,
428
+ })
429
+
430
+ # ---- persist final artefacts ----
431
+ log_record["finished_at"] = datetime.now().isoformat()
432
+ log_record["final_test_score"] = test_summary["avg_score"]
433
+ log_record["final_prompt_is"] = "latest current_prompt after 200 iterations"
434
+ log_record["final_prompt_len"] = len(current_prompt)
435
+ log_record["api_stats"] = self.client.stats
436
+
437
+ _write_text(os.path.join(out_dir, "optimized_prompt.txt"), current_prompt)
438
+ _write_json(os.path.join(out_dir, "optimization_log.json"), log_record)
439
+
440
+ logger.info(" all artefacts saved to %s", out_dir)
441
+
442
+ return {
443
+ "dataset": dataset_name,
444
+ "final_score": test_summary["avg_score"],
445
+ "iterations": len(log_record["iterations"]),
446
+ "prompt_path": os.path.join(out_dir, "optimized_prompt.txt"),
447
+ }
448
+
449
+ # ================================================================ #
450
+ # Internal helpers #
451
+ # ================================================================ #
452
+
453
+ def _evaluate_in_chunks(
454
+ self,
455
+ originals: list[str],
456
+ refinements: list[str],
457
+ chunk_size: int = 5,
458
+ concurrency: int | None = None,
459
+ ) -> list[dict]:
460
+ """Evaluate in chunks of *chunk_size*, chunks run concurrently."""
461
+ chunks = []
462
+ for i in range(0, len(originals), chunk_size):
463
+ chunks.append((i, originals[i:i+chunk_size], refinements[i:i+chunk_size]))
464
+
465
+ from concurrent.futures import ThreadPoolExecutor, as_completed
466
+
467
+ all_evals: list[dict] = [None] * len(chunks)
468
+
469
+ def _eval_chunk(idx, o_chunk, r_chunk):
470
+ evals = self.evaluator.evaluate_batch(o_chunk, r_chunk)
471
+ return idx, evals
472
+
473
+ with ThreadPoolExecutor(max_workers=concurrency or cfg.API_CONCURRENCY) as pool:
474
+ futs = {
475
+ pool.submit(_eval_chunk, ci, oc, rc): ci
476
+ for ci, (_, oc, rc) in enumerate(chunks)
477
+ }
478
+ for fut in as_completed(futs):
479
+ ci = futs[fut]
480
+ try:
481
+ _, evals = fut.result()
482
+ all_evals[ci] = evals
483
+ except Exception as exc:
484
+ logger.error(" eval chunk %d failed: %s", ci, exc)
485
+ all_evals[ci] = self.evaluator._defaults(len(chunks[ci][1]))
486
+
487
+ flat: list[dict] = []
488
+ for ci, (offset, _, _) in enumerate(chunks):
489
+ for ev in (all_evals[ci] or []):
490
+ ev["sample_id"] = ev.get("sample_id", 0) + offset
491
+ flat.append(ev)
492
+ return flat
493
+
494
+ @staticmethod
495
+ def _exclude_failures(originals: list[str], refinements: list[str]) -> tuple[list[str], list[str]]:
496
+ """Remove API-failed pairs. Returns (filtered_originals, filtered_refinements)."""
497
+ ok = [(o, r) for o, r in zip(originals, refinements) if r != "[REFINEMENT_ERROR]"]
498
+ n_dropped = len(originals) - len(ok)
499
+ if n_dropped:
500
+ logger.warning(" excluded %d/%d API-failed samples", n_dropped, len(originals))
501
+ if not ok:
502
+ return [], []
503
+ return [o for o, _ in ok], [r for _, r in ok]
504
+
505
+ def _refine_batch(self, texts: list[str], prompt: str, concurrency: int | None = None) -> list[str]:
506
+ """Refine texts concurrently via call_batch."""
507
+ tasks = [
508
+ {"system_prompt": prompt, "user_content": t}
509
+ for t in texts
510
+ ]
511
+ results = self.client.call_batch(tasks, max_workers=concurrency)
512
+ logger.info(" refined %d/%d OK", sum(1 for r in results if r != "[REFINEMENT_ERROR]"), len(texts))
513
+ return results
514
+
515
+ # ------------------------------------------------------------------
516
+ def _profile_dataset(self, dataset_name: str, samples: list[str]) -> dict:
517
+ """Profile the dataset in 4 calls: 3 batches of 5 full texts, then merge."""
518
+ step = max(1, len(samples) // 15)
519
+ chosen = [samples[i] for i in range(0, len(samples), step)][:15]
520
+
521
+ batches = [chosen[0:5], chosen[5:10], chosen[10:15]]
522
+ profile_sys = PROFILE_SYSTEM_PROMPT.format(dataset_name=dataset_name)
523
+
524
+ tasks = []
525
+ for batch in batches:
526
+ if not batch:
527
+ continue
528
+ user_msg = "\n\n---\n\n".join(
529
+ f"[Sample {i}]\n{t}" for i, t in enumerate(batch)
530
+ )
531
+ tasks.append({
532
+ "system_prompt": profile_sys,
533
+ "user_content": user_msg,
534
+ "model": cfg.JUDGE_MODEL,
535
+ "max_tokens": 2048,
536
+ })
537
+
538
+ results = self.client.call_batch(tasks, max_workers=len(tasks))
539
+ partial_profiles = [r for r in results if r != "[REFINEMENT_ERROR]"]
540
+ logger.info(" profile: %d/3 batches done", len(partial_profiles))
541
+
542
+ if not partial_profiles:
543
+ return {"error": "profiling_failed", "dataset_name": dataset_name}
544
+
545
+ merge_prompt = (
546
+ f'You are a data-quality analyst. Below are {len(partial_profiles)} partial '
547
+ f'profiles of the "{dataset_name}" dataset. Merge them into ONE unified JSON '
548
+ f'profile with these fields (no markdown fences):\n'
549
+ f'{{"dominant_language","content_types","common_noise_patterns",'
550
+ f'"has_code_blocks","has_tables","has_math","avg_quality_impression","special_notes"}}\n'
551
+ f'Output ONLY the merged JSON object.'
552
+ )
553
+ merge_user = "\n\n---\n\n".join(
554
+ f"[Partial profile {i+1}]\n{p}" for i, p in enumerate(partial_profiles)
555
+ )
556
+ try:
557
+ raw = self.client.call(
558
+ system_prompt=merge_prompt,
559
+ user_content=merge_user,
560
+ model=cfg.JUDGE_MODEL,
561
+ max_tokens=2048,
562
+ )
563
+ m = re.search(r"\{[\s\S]*\}", raw)
564
+ if m:
565
+ logger.info(" profile merge done")
566
+ return json.loads(m.group())
567
+ except Exception as exc:
568
+ logger.warning("Profile merge failed: %s", exc)
569
+
570
+ return {"error": "profiling_failed", "dataset_name": dataset_name}
571
+
572
+ # ------------------------------------------------------------------
573
+ def _meta_optimize(
574
+ self,
575
+ dataset_name: str,
576
+ dataset_profile: dict,
577
+ current_prompt: str,
578
+ problems: list[tuple[str, str, dict]],
579
+ summary: dict,
580
+ iteration: int,
581
+ ) -> str:
582
+ examples_block = self._format_examples(problems[:5])
583
+ reference_block = self._format_references()
584
+
585
+ system = META_SYSTEM_TEMPLATE.format(
586
+ dataset_name=dataset_name,
587
+ dataset_profile=json.dumps(dataset_profile, ensure_ascii=False, indent=2),
588
+ iteration=iteration + 1,
589
+ max_iter=cfg.MAX_ITERATIONS,
590
+ current_prompt=current_prompt,
591
+ avg_score=summary["avg_score"],
592
+ major_count=summary["major_count"],
593
+ total_samples=summary["total_samples"],
594
+ top_issues=json.dumps(summary["top_issues"][:5], ensure_ascii=False),
595
+ examples_block=examples_block,
596
+ reference_block=reference_block,
597
+ )
598
+
599
+ try:
600
+ resp = self.client.call(
601
+ system_prompt=system,
602
+ user_content="Analyze the issues and produce an improved prompt.",
603
+ model=cfg.JUDGE_MODEL,
604
+ )
605
+ return self._extract_improved_prompt(resp)
606
+ except Exception as exc:
607
+ logger.error("Meta-optimization call failed: %s", exc)
608
+ return current_prompt
609
+
610
+ # ------------------------------------------------------------------
611
+ def _extract_improved_prompt(self, text: str) -> str:
612
+ m = re.search(
613
+ r"<IMPROVED_PROMPT>(.*?)</IMPROVED_PROMPT>", text, re.DOTALL
614
+ )
615
+ if m:
616
+ return m.group(1).strip()
617
+ logger.warning("No <IMPROVED_PROMPT> tags found; using full response")
618
+ return text.strip()
619
+
620
+ # ------------------------------------------------------------------
621
+ @staticmethod
622
+ def _format_examples(problems: list[tuple[str, str, dict]]) -> str:
623
+ parts = []
624
+ for i, (orig, refined, ev) in enumerate(problems):
625
+ issues = ev.get("issues", [])
626
+ score = ev.get("total_score", "?")
627
+ parts.append(
628
+ f"### Problematic sample {i+1} (score {score}/10)\n"
629
+ f"**Original:**\n{orig}\n\n"
630
+ f"**Model output:**\n{refined}\n\n"
631
+ f"**Issues:** {', '.join(issues) if issues else 'none'}\n"
632
+ )
633
+ return "\n".join(parts) if parts else "(all samples scored well)"
634
+
635
+ def _format_references(self) -> str:
636
+ parts = []
637
+ for name, content in self.reference_prompts.items():
638
+ if name == "refinement_prompt_en.txt":
639
+ continue
640
+ parts.append(f"#### {name}\n{content}\n")
641
+ return "\n".join(parts) if parts else "(no additional references)"
642
+
643
+ # ------------------------------------------------------------------
644
+ @staticmethod
645
+ def _save_raw_samples(
646
+ samples_dir: str,
647
+ opt_set: list[str],
648
+ test_set: list[str],
649
+ ):
650
+ """Persist every sampled text so they can be reproduced / audited."""
651
+ _write_json(
652
+ os.path.join(samples_dir, "optimization_set.json"),
653
+ [{"id": i, "text": t} for i, t in enumerate(opt_set)],
654
+ )
655
+ _write_json(
656
+ os.path.join(samples_dir, "test_set.json"),
657
+ [{"id": i, "text": t} for i, t in enumerate(test_set)],
658
+ )
659
+
660
+ @staticmethod
661
+ def _save_iteration_pairs(
662
+ iter_dir: str,
663
+ prefix: str,
664
+ originals: list[str],
665
+ refinements: list[str],
666
+ ):
667
+ """Save every (original, refined) pair for an iteration — full text."""
668
+ records = [
669
+ {"id": i, "original": o, "refined": r}
670
+ for i, (o, r) in enumerate(zip(originals, refinements))
671
+ ]
672
+ _write_json(os.path.join(iter_dir, f"{prefix}_pairs.json"), records)
code/stage1_model_construction/prompt_optimization/refinement_prompt_en.txt ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a Data Refinement Expert. Upon receiving a "Text Content", first determine if it has retentive value. The criteria include but are not limited to: whether it contains valid information (opinions, facts, methods, conclusions, steps, data, problem descriptions, etc.); whether it is intelligible natural language; whether it is purely advertisement, marketing, contact info, clickbait, purely decorative, gibberish, or extremely short and meaningless fragments.
2
+
3
+ - If the content is valueless (purely ads/clickbait, pure gibberish, only contact info, no informational content, or too short to be meaningful), output directly and uniquely:
4
+ [Content valueless, deleted]
5
+
6
+ - If the content has value, output the refined, clean text directly. Adhere to the following specific rules (make only necessary modifications to remove valueless content, while preserving the original wording and flow as much as possible):
7
+
8
+ 1. **Retain core information and ORIGINAL WORDING**. Do NOT summarize, rewrite, or "polish" the text. If the original text has poor grammar or awkward phrasing but is understandable, **KEEP IT AS IS**.
9
+ 2. **Remove all advertisements and traffic-driving info** (phone numbers, email addresses, social media handles like Twitter/WeChat/Discord, QR code descriptions, "follow for more", affiliate links, paid course promos, etc.).
10
+ 3. **Remove engagement bait** (e.g., "Smash that like button", "Don't forget to subscribe", "Share this post").
11
+ 4. **Remove purely decorative symbols, repetitive separators, and excessive ASCII art/borders**. CRITICAL EXCEPTION: Strictly PRESERVE Markdown structural characters (e.g., # for headers, * or - for lists, | for tables, > for quotes). Do NOT treat them as decorative symbols.
12
+ 5. **Remove HTML/XML tags** (e.g., <div>, <p>, &nbsp;, <s>). However, DO NOT remove Markdown formatting unless it is broken. Specifically, ALWAYS keep the # symbols in headers (e.g., convert <h1>Title</h1> to # Title, and keep existing # Title as is).
13
+ 6. **Clean up obvious gibberish** and unreadable characters (including long strings of meaningless garbage, encoding error symbols like ``).
14
+ 7. **Fix broken formatting ONLY**: Merge lines that were unnecessarily split by newlines (e.g., "commu-\nication"). **DO NOT rephrase sentences** to improve flow or style.
15
+ 8. **Merge paragraphs cautiously**: Maintain the document hierarchy. Retain all sub-headers/titles exactly as they are (including their # prefix). Do not merge a header into the following paragraph or strip its formatting level.
16
+ 9. **Remove meaningless image placeholders** (e.g., text like "See Figure 1", "Image missing", "[Image]" if they are just placeholders without the actual image).
17
+ 10. **Simplify excessive slang or internet shorthand** (make the expression more professional and clear without changing the original meaning); however, if the slang aids understanding or is part of the original flavor/context, it can be retained.
18
+ 11. **Retain useful citations/sources** (if it is a necessary academic reference, keep the citation marker and identifiable info, but remove unparsed, long, raw URLs).
19
+ 12. **Output format**: Remove extra spaces, repetitive blank lines, and tabs. The text should be fluent, professional, and ready for use.
20
+
21
+ **Extra Rules:**
22
+ - **Output Language**: English. Keep the output in English! Do NOT translate English text to other languages.
23
+ - **Final Output**: Only the refined English text (without any quotes or prefixes) OR the exact string `[Content valueless, deleted]`.
24
+ - **Markdown Structure Protection**: The output MUST be valid Markdown. Never strip the # from headers. If the original text is # Context, the output must be # Context, not just Context.
25
+ - **STRICT FIDELITY (Crucial)**: You are a text CLEANER, not an EDITOR. Do not improve the writing style. Do not remove sections just because they seem "boring" (like lists or credits) if they contain valid entities.
26
+
27
+ **Examples for Reference:**
28
+
29
+ - **Original Data 1:**
30
+ <div class="content">
31
+ <h1>FCC Regulations Overview</h1>
32
+ 1. According to the <br>
33
+ Federal Communications Commission
34
+ rules, Section 10. &nbsp;This section defines the requirements for broadcasting.
35
+ <p>(1) Broadcast stations must be licensed.</p>
36
+ <p>(2) No entity shall operate without authorization!</p>
37
+ <p>Scan QR code to join our Crypto Group for free money!!!</p>
38
+ <script>alert("Ad Script")</script>
39
+ <p>Call us: 1-800-555-0199 / Twitter: @crypto_king</p>
40
+ </div>
41
+
42
+ - **Refined Data 1:**
43
+ FCC Regulations Overview
44
+ 1. According to the Federal Communications Commission rules, Section 10. This section defines the requirements for broadcasting.
45
+ (1) Broadcast stations must be licensed.
46
+ (2) No entity shall operate without authorization!
47
+
48
+ - **Original Data 2:**
49
+ 【●●Hot Topic●●】
50
+ Today let's talk about Spark RDD mechanism——
51
+ Umm, this thing is kinda god-tier lol 2333
52
+ RDD is a "Resilient Distributed Dataset", basically an abstract collection of data.
53
+ RDD supports fault tolerance,
54
+ supports DAG scheduling
55
+ DAG scheduling
56
+ DAG scheduling
57
+ (Repeated many times)
58
+ Want to know more? Add my Discord: rdd_master666!
59
+ 💥💥Click to save and don't get lost💥💥
60
+
61
+ - **Refined Data 2:**
62
+ 【Hot Topic】
63
+ Today let's talk about Spark RDD mechanism——
64
+ This thing is actually quite powerful.
65
+ RDD is a "Resilient Distributed Dataset", basically an abstract collection of data.
66
+ RDD supports fault tolerance,
67
+ supports DAG scheduling.
68
+ (Repeated many times)
69
+
70
+ - **Original Data 3:**
71
+ Python Anomaly Detection
72
+ ——log-based anomaly detection✨✨
73
+ This article introduces how to use Spark for log analysis.
74
+ (Content omitted due to length)
75
+ Copyright belongs to the author.
76
+ 💬💬💬If you like it, please smash that like button💬💬💬
77
+ <a href="http://spam-link.com">Click to download resources</a>
78
+ The configuration mentioned below is:
79
+ a_n+1=1/(2+a_n)
80
+ a_n+1=1/(2+a_n)
81
+ Garbage chars: #¥@%……&*
82
+ <IMG alt="Fig1">Image placeholder here</IMG>
83
+
84
+ - **Refined Data 3:**
85
+ Python Anomaly Detection
86
+ ——log-based anomaly detection
87
+ This article introduces how to use Spark for log analysis.
88
+ The configuration mentioned below is:
89
+ a_n+1=1/(2+a_n)
90
+
91
+ - **Original Data 4:**
92
+ Breaking News
93
+ Today we report a major event police stopped an illegal gathering on the street citizens fled the scene please stay safe
94
+ Some people tried to spread rumors political sensitivity info should be deleted
95
+ This incident involves violent behavior criminals were caught
96
+ Also note, pandemic measures are still in effect
97
+ Safety measures in place
98
+
99
+ Please stay calm
100
+
101
+ - **Refined Data 4:**
102
+ Breaking News. Today we report a major event; police stopped an illegal gathering on the street. Please stay safe. Some people tried to spread rumors, which should be deleted. This incident involves violent behavior, and criminals were caught. Also note, pandemic measures are still in effect. Safety measures in place. Please stay calm.
103
+
104
+ - **Original Data 5:**
105
+ <s> 2. Step Two: Check the power supply (Like and Subscribe)
106
+ 3. Step Three: Verify the network connection (Like and Subscribe)
107
+ 4. Step Four: Reboot the router (Like and Subscribe)
108
+ 5. Step Five: Ping the gateway (Like and Subscribe)
109
+ 6. Step Six: Check DNS settings (Like and Subscribe)
110
+ This is the standard troubleshooting guide. If you think it works, please share it, retweet it, thanks a lot!</s>
111
+
112
+ - **Refined Data 5:**
113
+ Standard Troubleshooting Guide
114
+ 2. Step Two: Check the power supply.
115
+ 3. Step Three: Verify the network connection.
116
+ 4. Step Four: Reboot the router.
117
+ 5. Step Five: Ping the gateway.
118
+ 6. Step Six: Check DNS settings.
119
+ This is the standard troubleshooting guide.
120
+
121
+ - **Original Data 6:**
122
+ AD: Want to open an online store? "ShopMaster" is the leading platform. 1-on-1 coaching. ^^ We solve all newbie problems. Guaranteed traffic, guaranteed sales. One-stop solution...
123
+ AD: "John Doe" teaches you 5 steps to wealth; 1. Mindset 2. Action 3. Investment... ^^ The market price is huge...
124
+ AD: Best Crypto Wallet — released timely, accurate info! ^^ Professional ranking / price list...
125
+ AD: "Magic Pills" 21 years of experience, handmade, 30 days return ^^, fair price, trustworthy quality...
126
+
127
+ - **Refined Data 6:**
128
+ [Content valueless, deleted]
129
+
130
+ - **Original Data 7:**
131
+ # FAG CSCA040 Bearing
132
+
133
+ | Name | Model | Brand | Series | Inner Dia |
134
+ | ---- | ---- | ---- | ---- | ---- |
135
+ | FAG CSCA040 Bearing | CSCA040 | FAG | Thin Section | 101.6mm |
136
+ ## Dimensions
137
+ OD: 114.3mm Thickness: 6.35mm
138
+ ## Sample Image
139
+
140
+ - **Refined Data 7:**
141
+ # FAG CSCA040 Bearing
142
+
143
+ | Name | Model | Brand | Series | Inner Dia |
144
+ | ---- | ---- | ---- | ---- | ---- |
145
+ | FAG CSCA040 Bearing | CSCA040 | FAG | Thin Section | 101.6mm |
146
+ ## Dimensions
147
+ OD: 114.3mm Thickness: 6.35mm
code/stage1_model_construction/seed_preprocessing/sliding_window_splitter.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Sliding window splitter for long documents (multi-process version).
5
+ Splits documents exceeding max_tokens into overlapping windows at line boundaries.
6
+ Uses a configurable tokenizer for token counting.
7
+ """
8
+
9
+ import os
10
+ import math
11
+ import argparse
12
+ import pandas as pd
13
+ import pyarrow.parquet as pq
14
+ from pathlib import Path
15
+ from typing import List, Tuple, Dict
16
+ from multiprocessing import Pool
17
+ from transformers import AutoTokenizer
18
+
19
+ _tokenizer = None
20
+ _max_tokens = None
21
+ _step_tokens = None
22
+
23
+
24
+ def _init_worker(tokenizer_path: str, max_tokens: int, overlap_ratio: float):
25
+ global _tokenizer, _max_tokens, _step_tokens
26
+ _tokenizer = AutoTokenizer.from_pretrained(
27
+ tokenizer_path, trust_remote_code=True, model_max_length=10**8
28
+ )
29
+ _max_tokens = max_tokens
30
+ _step_tokens = int(max_tokens * (1 - overlap_ratio))
31
+
32
+
33
+ def _count_tokens(text: str) -> int:
34
+ if pd.isna(text) or text == "":
35
+ return 0
36
+ return len(_tokenizer.encode(text, add_special_tokens=False))
37
+
38
+
39
+ def _normalize_newlines(text: str) -> str:
40
+ return text.replace('\r\n', '\n').replace('\r', '\n')
41
+
42
+
43
+ def _split_content(content: str) -> List[str]:
44
+ content = _normalize_newlines(content)
45
+ total_tokens = _count_tokens(content)
46
+ if total_tokens <= _max_tokens:
47
+ return [content]
48
+
49
+ lines = content.split('\n')
50
+ chunks = []
51
+ start_idx = 0
52
+
53
+ while start_idx < len(lines):
54
+ current_chunk_lines = []
55
+ current_tokens = 0
56
+ idx = start_idx
57
+
58
+ while idx < len(lines):
59
+ line = lines[idx]
60
+ line_tokens = _count_tokens(line + '\n')
61
+ if current_tokens + line_tokens <= _max_tokens:
62
+ current_chunk_lines.append(line)
63
+ current_tokens += line_tokens
64
+ idx += 1
65
+ else:
66
+ if not current_chunk_lines:
67
+ current_chunk_lines.append(line)
68
+ current_tokens += line_tokens
69
+ idx += 1
70
+ break
71
+
72
+ if current_chunk_lines:
73
+ chunks.append('\n'.join(current_chunk_lines))
74
+
75
+ if idx >= len(lines):
76
+ break
77
+
78
+ accumulated_tokens = 0
79
+ next_start_idx = start_idx
80
+ while next_start_idx < idx and accumulated_tokens < _step_tokens:
81
+ line_tokens = _count_tokens(lines[next_start_idx] + '\n')
82
+ accumulated_tokens += line_tokens
83
+ next_start_idx += 1
84
+
85
+ if next_start_idx == start_idx:
86
+ next_start_idx += 1
87
+ start_idx = next_start_idx
88
+
89
+ return chunks if chunks else [content]
90
+
91
+
92
+ def _process_single_file(args: Tuple[str, str]) -> Dict:
93
+ input_path, output_path = args
94
+ input_path, output_path = Path(input_path), Path(output_path)
95
+
96
+ stats = {
97
+ "input_file": input_path.name,
98
+ "dataset": input_path.parent.name,
99
+ "total_rows": 0,
100
+ "rows_under_limit": 0,
101
+ "rows_split": 0,
102
+ "output_chunks": 0,
103
+ "total_tokens_after_split": 0,
104
+ "error": None,
105
+ }
106
+
107
+ try:
108
+ parquet_file = pq.ParquetFile(input_path)
109
+ if 'content' not in parquet_file.schema.names:
110
+ stats["error"] = "missing content column"
111
+ return stats
112
+
113
+ all_chunks = []
114
+ for batch in parquet_file.iter_batches(batch_size=500, columns=['content']):
115
+ df_batch = batch.to_pandas()
116
+ for content in df_batch['content']:
117
+ stats["total_rows"] += 1
118
+ if pd.isna(content) or not content.strip():
119
+ continue
120
+
121
+ token_count = _count_tokens(content)
122
+ if token_count <= _max_tokens:
123
+ stats["rows_under_limit"] += 1
124
+ stats["output_chunks"] += 1
125
+ normalized = _normalize_newlines(content)
126
+ all_chunks.append(normalized)
127
+ stats["total_tokens_after_split"] += token_count
128
+ else:
129
+ stats["rows_split"] += 1
130
+ chunks = _split_content(content)
131
+ stats["output_chunks"] += len(chunks)
132
+ all_chunks.extend(chunks)
133
+ for c in chunks:
134
+ stats["total_tokens_after_split"] += _count_tokens(c)
135
+
136
+ output_path.parent.mkdir(parents=True, exist_ok=True)
137
+ if all_chunks:
138
+ df = pd.DataFrame({"content": all_chunks})
139
+ df.to_parquet(output_path, engine='pyarrow', index=False)
140
+
141
+ except Exception as e:
142
+ stats["error"] = str(e)
143
+
144
+ return stats
145
+
146
+
147
+ def main():
148
+ parser = argparse.ArgumentParser(description="Sliding window splitter for long documents")
149
+ parser.add_argument("--input_dir", type=str, required=True, help="Input directory containing parquet files")
150
+ parser.add_argument("--output_dir", type=str, required=True, help="Output directory for split parquet files")
151
+ parser.add_argument("--tokenizer_path", type=str, required=True, help="Path to tokenizer (e.g., Qwen3-1.7B)")
152
+ parser.add_argument("--max_tokens", type=int, default=12000, help="Maximum tokens per window (default: 12000)")
153
+ parser.add_argument("--overlap_ratio", type=float, default=0.2, help="Overlap ratio between windows (default: 0.2)")
154
+ args = parser.parse_args()
155
+
156
+ source_root = Path(args.input_dir)
157
+ output_root = Path(args.output_dir)
158
+ tokenizer_path = args.tokenizer_path
159
+ max_tokens = args.max_tokens
160
+ overlap_ratio = args.overlap_ratio
161
+
162
+ cpu_count = os.cpu_count() or 4
163
+ num_workers = max(1, math.floor(cpu_count * 0.8))
164
+
165
+ print("=" * 80)
166
+ print("Sliding Window Document Splitter")
167
+ print(f"Source directory : {source_root}")
168
+ print(f"Output directory : {output_root}")
169
+ print(f"Max tokens : {max_tokens}")
170
+ print(f"Overlap ratio : {overlap_ratio:.0%}")
171
+ print(f"Step tokens : {int(max_tokens * (1 - overlap_ratio))}")
172
+ print(f"CPU cores : {cpu_count}")
173
+ print(f"Workers : {num_workers}")
174
+ print("=" * 80)
175
+
176
+ tasks: List[Tuple[str, str]] = []
177
+ skipped = 0
178
+ datasets = sorted([d for d in source_root.iterdir() if d.is_dir()])
179
+
180
+ for dataset_path in datasets:
181
+ dataset_name = dataset_path.name
182
+ parquet_files = sorted([f for f in dataset_path.iterdir() if f.suffix == '.parquet'])
183
+ for pf in parquet_files:
184
+ out_file = output_root / dataset_name / pf.name
185
+ if out_file.exists():
186
+ skipped += 1
187
+ else:
188
+ tasks.append((str(pf), str(out_file)))
189
+
190
+ print(f"\nFound {len(datasets)} datasets")
191
+ print(f" To process: {len(tasks)} files")
192
+ print(f" Skipped : {skipped} files (output exists)\n")
193
+
194
+ if not tasks:
195
+ print("No new files to process")
196
+ return
197
+
198
+ output_root.mkdir(parents=True, exist_ok=True)
199
+
200
+ print(f"Starting {num_workers} workers...\n")
201
+ with Pool(
202
+ processes=num_workers,
203
+ initializer=_init_worker,
204
+ initargs=(tokenizer_path, max_tokens, overlap_ratio),
205
+ ) as pool:
206
+ results = []
207
+ for stats in pool.imap_unordered(_process_single_file, tasks):
208
+ results.append(stats)
209
+ tag = f"[{stats['dataset']}/{stats['input_file']}]"
210
+ if stats["error"]:
211
+ print(f" x {tag} Error: {stats['error']}")
212
+ else:
213
+ print(f" + {tag} {stats['total_rows']} rows -> "
214
+ f"{stats['output_chunks']} chunks, "
215
+ f"tokens={stats['total_tokens_after_split']:,}")
216
+
217
+ total_rows = sum(r["total_rows"] for r in results)
218
+ total_under = sum(r["rows_under_limit"] for r in results)
219
+ total_split = sum(r["rows_split"] for r in results)
220
+ total_chunks = sum(r["output_chunks"] for r in results)
221
+ total_tokens = sum(r["total_tokens_after_split"] for r in results)
222
+ total_errors = sum(1 for r in results if r["error"])
223
+
224
+ ds_stats: Dict[str, Dict] = {}
225
+ for r in results:
226
+ ds = r["dataset"]
227
+ if ds not in ds_stats:
228
+ ds_stats[ds] = {"rows": 0, "chunks": 0, "tokens": 0, "files": 0}
229
+ ds_stats[ds]["rows"] += r["total_rows"]
230
+ ds_stats[ds]["chunks"] += r["output_chunks"]
231
+ ds_stats[ds]["tokens"] += r["total_tokens_after_split"]
232
+ ds_stats[ds]["files"] += 1
233
+
234
+ print("\n" + "=" * 80)
235
+ print("Per-dataset statistics:")
236
+ print("-" * 80)
237
+ for ds_name in sorted(ds_stats):
238
+ s = ds_stats[ds_name]
239
+ print(f" {ds_name:30s} files={s['files']:>4d} "
240
+ f"rows={s['rows']:>8,} chunks={s['chunks']:>8,} "
241
+ f"tokens={s['tokens']:>14,}")
242
+
243
+ print("\n" + "=" * 80)
244
+ print("Summary:")
245
+ print(f" Files processed : {len(results)}")
246
+ print(f" Errors : {total_errors}")
247
+ print(f" Total rows : {total_rows:,}")
248
+ print(f" Rows not split : {total_under:,}")
249
+ print(f" Rows split : {total_split:,}")
250
+ print(f" Output chunks : {total_chunks:,}")
251
+ print(f" Total tokens : {total_tokens:,}")
252
+ print("=" * 80)
253
+
254
+
255
+ if __name__ == "__main__":
256
+ main()
code/stage1_model_construction/sft_data_building/sample_and_format.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Sample and format training data for SFT.
4
+
5
+ Samples data from each function combo category according to target counts
6
+ (with oversampling for underrepresented combos), adds system instructions,
7
+ and writes shuffled output as JSONL shards.
8
+ """
9
+
10
+ import argparse
11
+ import json
12
+ import random
13
+ from pathlib import Path
14
+ from collections import defaultdict
15
+
16
+ random.seed(42)
17
+
18
+ LINES_PER_FILE = 1000
19
+
20
+ SKIP_DATASETS = {"by_combo"}
21
+
22
+ SYSTEM_INSTRUCTION = """\
23
+ You are a web text cleaner for LLM pre-training data. Clean the given web-crawled text by removing noise while maximally preserving valuable content.
24
+
25
+ Input: each line is prefixed with <lid:N> (1-indexed line number).
26
+
27
+ ## Operations
28
+ - keep_all() — Text is already clean, no changes needed
29
+ - remove_all() — Entire document is valueless (e.g., error pages, login walls, garbled text)
30
+ - remove_lines(start, end) — Remove lines start to end inclusive
31
+ - replace_str(line_number, 'old', 'new') — Replace substring within a line (for inline noise removal, line merging, or fixing HTML entities)
32
+ - add_line(base_position, sub_index, 'content') — Insert a new line near base_position
33
+
34
+ ## Rules
35
+ 1. REMOVE: navigation/breadcrumbs, ads/banners, copyright/cookie notices, "Share"/"Subscribe"/"Sign up" prompts, SEO stuffing, boilerplate templates, e-commerce UI elements (prices, "Add to cart", stock status), "Related posts"/"You may also like" sections, and comment section headers
36
+ 2. PRESERVE: article body, factual content, quotes, data, author info with context, dates in narrative
37
+ 3. When in doubt, KEEP the content — over-deletion is worse than under-deletion
38
+ 4. Prefer remove_lines when entire lines are noise; use replace_str only for inline noise within otherwise valuable lines
39
+ 5. Use remove_all() only when the document has absolutely zero informational value
40
+ 6. Output operations only, one per line"""
41
+
42
+ # ============================================================
43
+ # Sampling configuration
44
+ # ============================================================
45
+
46
+ COMBO_TARGETS = {
47
+ "remove_lines_replace_str": 731340,
48
+ "remove_lines": 231148,
49
+ "replace_str": 146613,
50
+ "remove_all": 82544,
51
+ "add_line_remove_lines_replace_str": 6861,
52
+ "add_line_remove_lines": 4588,
53
+ "add_line_replace_str": 1075,
54
+ "add_line": 40,
55
+ }
56
+
57
+ KEEP_ALL_TARGET = 1806314
58
+
59
+
60
+ def oversample(data: list, target: int) -> list:
61
+ if len(data) == 0:
62
+ return []
63
+ if len(data) >= target:
64
+ return random.sample(data, target)
65
+ result = list(data)
66
+ remaining = target - len(data)
67
+ result.extend(random.choices(data, k=remaining))
68
+ return result
69
+
70
+
71
+ def add_instruction(raw_json_str: str) -> str:
72
+ """Add system instruction to a JSON data entry, returning the new JSON string."""
73
+ data = json.loads(raw_json_str)
74
+ old_messages = data["messages"]
75
+ data["messages"] = [
76
+ {"role": "system", "content": SYSTEM_INSTRUCTION},
77
+ *old_messages,
78
+ ]
79
+ return json.dumps(data, ensure_ascii=False)
80
+
81
+
82
+ def load_all_data_by_combo(train_data_dir: Path):
83
+ combo_data = defaultdict(list)
84
+ keep_all_data = []
85
+
86
+ dataset_dirs = [
87
+ d for d in train_data_dir.iterdir()
88
+ if d.is_dir() and d.name not in SKIP_DATASETS
89
+ ]
90
+
91
+ print(f" Scanning {len(dataset_dirs)} dataset directories...")
92
+
93
+ for ds_dir in sorted(dataset_dirs):
94
+ ds_name = ds_dir.name
95
+ file_count = 0
96
+ ds_keep_all = 0
97
+ ds_other = 0
98
+ for jsonl_file in ds_dir.rglob("*.jsonl"):
99
+ file_count += 1
100
+ with open(jsonl_file, "r", encoding="utf-8") as f:
101
+ for line in f:
102
+ line = line.strip()
103
+ if not line:
104
+ continue
105
+ try:
106
+ data = json.loads(line)
107
+ combo = data.pop("combo", "unknown")
108
+ clean_line = json.dumps(data, ensure_ascii=False)
109
+
110
+ if combo == "keep_all":
111
+ keep_all_data.append(clean_line)
112
+ ds_keep_all += 1
113
+ else:
114
+ combo_data[combo].append(clean_line)
115
+ ds_other += 1
116
+ except Exception:
117
+ pass
118
+ print(f" {ds_name}: {file_count} files, keep_all={ds_keep_all}, other={ds_other}")
119
+
120
+ return dict(combo_data), keep_all_data
121
+
122
+
123
+ def write_output(all_lines: list, output_dir: Path):
124
+ output_dir.mkdir(parents=True, exist_ok=True)
125
+
126
+ random.shuffle(all_lines)
127
+
128
+ total = len(all_lines)
129
+ file_idx = 0
130
+ for start in range(0, total, LINES_PER_FILE):
131
+ batch = all_lines[start:start + LINES_PER_FILE]
132
+ output_file = output_dir / f"train_{file_idx:05d}.jsonl"
133
+ with open(output_file, "w", encoding="utf-8") as f:
134
+ for line in batch:
135
+ f.write(line + "\n")
136
+ file_idx += 1
137
+
138
+ print(f"\nOutput complete:")
139
+ print(f" Total entries: {total}")
140
+ print(f" Number of files: {file_idx}")
141
+ print(f" Output directory: {output_dir}")
142
+
143
+
144
+ def main():
145
+ parser = argparse.ArgumentParser(
146
+ description="Sample training data by combo category and add system instructions."
147
+ )
148
+ parser.add_argument("--train_data_dir", type=str, required=True,
149
+ help="Directory containing per-file JSONL training data "
150
+ "(output of function_construction.py)")
151
+ parser.add_argument("--output_dir", type=str, required=True,
152
+ help="Directory to write sampled and formatted output JSONL shards")
153
+ args = parser.parse_args()
154
+
155
+ train_data_dir = Path(args.train_data_dir)
156
+ output_dir = Path(args.output_dir)
157
+
158
+ # 1. Load data
159
+ print("=" * 60)
160
+ print("Step 1: Load data")
161
+ print("=" * 60)
162
+
163
+ combo_data, keep_all_data = load_all_data_by_combo(train_data_dir)
164
+
165
+ print(f"\n Data counts per combo:")
166
+ for combo in sorted(combo_data.keys()):
167
+ print(f" {combo}: {len(combo_data[combo])}")
168
+ print(f" keep_all: {len(keep_all_data)}")
169
+
170
+ # 2. Sample non-keep_all categories
171
+ all_sampled = []
172
+
173
+ print()
174
+ print("=" * 60)
175
+ print("Step 2: Sample non-keep_all categories")
176
+ print("=" * 60)
177
+
178
+ for combo_name, target in COMBO_TARGETS.items():
179
+ data = combo_data.get(combo_name, [])
180
+ sampled = oversample(data, target)
181
+ all_sampled.extend(sampled)
182
+ ratio = target / len(data) if data else 0
183
+ print(f" {combo_name}: {len(data)} -> {len(sampled)} ({ratio:.2f}x)")
184
+
185
+ non_keep_all_total = len(all_sampled)
186
+
187
+ # 3. Oversample keep_all to target count
188
+ print()
189
+ print("=" * 60)
190
+ print("Step 3: Oversample keep_all")
191
+ print("=" * 60)
192
+
193
+ print(f" Original keep_all data: {len(keep_all_data)} entries")
194
+ print(f" Target count: {KEEP_ALL_TARGET} entries")
195
+
196
+ keep_all_sampled = oversample(keep_all_data, KEEP_ALL_TARGET)
197
+ all_sampled.extend(keep_all_sampled)
198
+
199
+ print(f" Sampled: {len(keep_all_sampled)} entries (oversampled {len(keep_all_sampled)/len(keep_all_data):.2f}x)")
200
+
201
+ # 4. Add system instruction
202
+ print()
203
+ print("=" * 60)
204
+ print("Step 4: Add system instruction")
205
+ print("=" * 60)
206
+
207
+ all_sampled = [add_instruction(line) for line in all_sampled]
208
+ print(f" Added instruction to {len(all_sampled)} entries")
209
+
210
+ # 5. Write output
211
+ print()
212
+ print("=" * 60)
213
+ print("Step 5: Shuffle and write output files")
214
+ print("=" * 60)
215
+
216
+ write_output(all_sampled, output_dir)
217
+
218
+ # 6. Statistics
219
+ print()
220
+ print("=" * 60)
221
+ print("Final statistics")
222
+ print("=" * 60)
223
+ total = len(all_sampled)
224
+
225
+ combo_counts = {"keep_all": len(keep_all_sampled)}
226
+ for combo_name, target in COMBO_TARGETS.items():
227
+ combo_counts[combo_name] = target
228
+
229
+ print(f"\n {'combo':<45s} {'count':>10s} {'ratio':>7s}")
230
+ print(f" {'-'*65}")
231
+ for combo_name in sorted(combo_counts.keys()):
232
+ cnt = combo_counts[combo_name]
233
+ print(f" {combo_name:<45s} {cnt:>10,} ({cnt/total*100:5.2f}%)")
234
+ print(f" {'-'*65}")
235
+ print(f" {'Total':<45s} {total:>10,} (100.00%)")
236
+ print(f"\n 2-epoch total training volume: {total * 2:,}")
237
+
238
+
239
+ if __name__ == "__main__":
240
+ main()
code/stage2_large_scale_execution/inference/inference.py ADDED
@@ -0,0 +1,990 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ UltraX Large-Scale Inference Script (Data-Parallel, Function-Only Output)
5
+
6
+ This script performs large-scale batch inference using a trained refinement model
7
+ to generate cleaning operations (function calls) for pre-training data.
8
+
9
+ Features:
10
+ 1. Reads parquet files from an input directory (expects 'original' column)
11
+ 2. Applies sliding window segmentation for long documents
12
+ 3. Uses vLLM for batch inference with data parallelism (one model per GPU)
13
+ 4. Merges sliding window results with overlap-aware aggregation
14
+ 5. Outputs model predictions without executing the actual cleaning
15
+
16
+ Output:
17
+ - One output parquet file per input file
18
+ - Two columns: original, model_output
19
+
20
+ Data Parallelism:
21
+ - Each GPU hosts a full model replica
22
+ - Files are distributed across GPUs in round-robin fashion
23
+ - Multiprocessing with one process per GPU
24
+
25
+ Usage:
26
+ python inference.py --input_dir /path/to/data --model_path /path/to/model --output_dir /path/to/output
27
+ """
28
+
29
+ import os
30
+ import re
31
+ import logging
32
+ import time
33
+ import argparse
34
+ import multiprocessing as mp
35
+ from pathlib import Path
36
+ from typing import List, Dict, Optional, Tuple
37
+ from collections import defaultdict
38
+ from dataclasses import dataclass, field
39
+
40
+ import torch
41
+ import pandas as pd
42
+ import pyarrow.parquet as pq
43
+ from transformers import AutoTokenizer
44
+
45
+ SYSTEM_INSTRUCTION = """\
46
+ You are a web text cleaner for LLM pre-training data. Clean the given web-crawled text by removing noise while maximally preserving valuable content.
47
+
48
+ Input: each line is prefixed with <lid:N> (1-indexed line number).
49
+
50
+ ## Operations
51
+ - keep_all() — Text is already clean, no changes needed
52
+ - remove_all() — Entire document is valueless (e.g., error pages, login walls, garbled text)
53
+ - remove_lines(start, end) — Remove lines start to end inclusive
54
+ - replace_str(line_number, 'old', 'new') — Replace substring within a line (for inline noise removal, line merging, or fixing HTML entities)
55
+ - add_line(base_position, sub_index, 'content') — Insert a new line near base_position
56
+
57
+ ## Rules
58
+ 1. REMOVE: navigation/breadcrumbs, ads/banners, copyright/cookie notices, "Share"/"Subscribe"/"Sign up" prompts, SEO stuffing, boilerplate templates, e-commerce UI elements (prices, "Add to cart", stock status), "Related posts"/"You may also like" sections, and comment section headers
59
+ 2. PRESERVE: article body, factual content, quotes, data, author info with context, dates in narrative
60
+ 3. When in doubt, KEEP the content — over-deletion is worse than under-deletion
61
+ 4. Prefer remove_lines when entire lines are noise; use replace_str only for inline noise within otherwise valuable lines
62
+ 5. Use remove_all() only when the document has absolutely zero informational value
63
+ 6. Output operations only, one per line"""
64
+
65
+
66
+ def setup_logger(gpu_id: int = None):
67
+ """Configure logger for the current process."""
68
+ if gpu_id is not None:
69
+ log_format = f'%(asctime)s - GPU{gpu_id} - %(levelname)s - %(message)s'
70
+ else:
71
+ log_format = '%(asctime)s - %(levelname)s - %(message)s'
72
+
73
+ logging.basicConfig(
74
+ level=logging.INFO,
75
+ format=log_format,
76
+ datefmt='%Y-%m-%d %H:%M:%S',
77
+ force=True
78
+ )
79
+ return logging.getLogger(__name__)
80
+
81
+
82
+ # ==================== Configuration ====================
83
+ @dataclass
84
+ class Config:
85
+ """Runtime configuration."""
86
+ input_dir: str
87
+ model_path: str
88
+ output_dir: str
89
+ max_chars: int
90
+ overlap_ratio: float
91
+ gpu_memory_utilization: float
92
+ max_model_len: int
93
+ max_new_tokens: int
94
+ num_gpus: int
95
+ infer_batch_size: int
96
+ read_batch_size: int
97
+
98
+
99
+ # ==================== Function Parsing ====================
100
+
101
+ def parse_quoted_string(s: str, quote_char: str) -> Tuple[str, str]:
102
+ """Parse a quoted string with escape character handling."""
103
+ if not s.startswith(quote_char):
104
+ raise ValueError(f"String does not start with {quote_char}")
105
+
106
+ result = []
107
+ i = 1
108
+ while i < len(s):
109
+ if s[i] == '\\' and i + 1 < len(s):
110
+ next_char = s[i + 1]
111
+ if next_char == 'n':
112
+ result.append('\n')
113
+ elif next_char == 't':
114
+ result.append('\t')
115
+ elif next_char == 'r':
116
+ result.append('\r')
117
+ elif next_char == '\\':
118
+ result.append('\\')
119
+ elif next_char == quote_char:
120
+ result.append(quote_char)
121
+ else:
122
+ result.append('\\')
123
+ result.append(next_char)
124
+ i += 2
125
+ elif s[i] == quote_char:
126
+ return ''.join(result), s[i + 1:]
127
+ else:
128
+ result.append(s[i])
129
+ i += 1
130
+
131
+ raise ValueError("String not properly terminated")
132
+
133
+
134
+ def parse_function_call(func_str: str) -> Optional[Dict]:
135
+ """Parse a function call string into a structured dict."""
136
+ func_str = func_str.strip()
137
+ if not func_str:
138
+ return None
139
+
140
+ if func_str == 'keep_all()':
141
+ return {'operation': 'keep_all'}
142
+
143
+ if func_str == 'remove_all()':
144
+ return {'operation': 'remove_all'}
145
+
146
+ match = re.match(r'remove_lines\((\d+),\s*(\d+)\)', func_str)
147
+ if match:
148
+ return {
149
+ 'operation': 'remove_lines',
150
+ 'start_line': int(match.group(1)),
151
+ 'end_line': int(match.group(2))
152
+ }
153
+
154
+ if func_str.startswith('replace_str('):
155
+ try:
156
+ inner = func_str[len('replace_str('):-1]
157
+ first_comma = inner.find(',')
158
+ if first_comma == -1:
159
+ return None
160
+
161
+ line_num = int(inner[:first_comma].strip())
162
+ rest = inner[first_comma + 1:].strip()
163
+
164
+ if rest.startswith("'"):
165
+ search_content, rest = parse_quoted_string(rest, "'")
166
+ elif rest.startswith('"'):
167
+ search_content, rest = parse_quoted_string(rest, '"')
168
+ else:
169
+ return None
170
+
171
+ rest = rest.lstrip(',').strip()
172
+
173
+ if rest.startswith("'"):
174
+ replace_content, _ = parse_quoted_string(rest, "'")
175
+ elif rest.startswith('"'):
176
+ replace_content, _ = parse_quoted_string(rest, '"')
177
+ else:
178
+ return None
179
+
180
+ return {
181
+ 'operation': 'replace_str',
182
+ 'line_number': line_num,
183
+ 'search_content': search_content,
184
+ 'replace_content': replace_content
185
+ }
186
+ except Exception:
187
+ return None
188
+
189
+ if func_str.startswith('add_line('):
190
+ try:
191
+ inner = func_str[len('add_line('):-1]
192
+ first_comma = inner.find(',')
193
+ if first_comma == -1:
194
+ return None
195
+
196
+ base_pos = int(inner[:first_comma].strip())
197
+ rest = inner[first_comma + 1:].strip()
198
+
199
+ second_comma = rest.find(',')
200
+ if second_comma == -1:
201
+ return None
202
+
203
+ sub_index = int(rest[:second_comma].strip())
204
+ rest = rest[second_comma + 1:].strip()
205
+
206
+ if rest.startswith("'"):
207
+ content, _ = parse_quoted_string(rest, "'")
208
+ elif rest.startswith('"'):
209
+ content, _ = parse_quoted_string(rest, '"')
210
+ else:
211
+ return None
212
+
213
+ return {
214
+ 'operation': 'add_line',
215
+ 'base_position': base_pos,
216
+ 'sub_index': sub_index,
217
+ 'content': content
218
+ }
219
+ except Exception:
220
+ return None
221
+
222
+ return None
223
+
224
+
225
+ def parse_function_list(content: str) -> List[Dict]:
226
+ """Parse a newline-separated list of function calls."""
227
+ if not content or not content.strip():
228
+ return []
229
+
230
+ functions = []
231
+ for line in content.strip().split('\n'):
232
+ line = line.strip()
233
+ if line:
234
+ func_info = parse_function_call(line)
235
+ if func_info:
236
+ functions.append(func_info)
237
+ return functions
238
+
239
+
240
+ def extract_prediction(response: str) -> str:
241
+ """Extract prediction from model output, stripping <think>...</think> prefix."""
242
+ prefix = "<think>\n\n</think>\n\n"
243
+ if response.startswith(prefix):
244
+ return response[len(prefix):]
245
+ return response
246
+
247
+
248
+ def functions_to_string(functions: List[Dict]) -> str:
249
+ """Convert a list of function dicts back to string representation."""
250
+ if not functions:
251
+ return ""
252
+
253
+ lines = []
254
+ for func in functions:
255
+ op = func.get('operation', '')
256
+ if op == 'keep_all':
257
+ lines.append('keep_all()')
258
+ elif op == 'remove_all':
259
+ lines.append('remove_all()')
260
+ elif op == 'remove_lines':
261
+ lines.append(f"remove_lines({func['start_line']}, {func['end_line']})")
262
+ elif op == 'replace_str':
263
+ lines.append(f"replace_str({func['line_number']}, {repr(func['search_content'])}, {repr(func['replace_content'])})")
264
+ elif op == 'add_line':
265
+ lines.append(f"add_line({func['base_position']}, {func['sub_index']}, {repr(func['content'])})")
266
+
267
+ return '\n'.join(lines)
268
+
269
+
270
+ # ==================== Sliding Window ====================
271
+
272
+ def normalize_newlines(text: str) -> str:
273
+ """Normalize \\r\\n and \\r to \\n."""
274
+ return text.replace('\r\n', '\n').replace('\r', '\n')
275
+
276
+
277
+ def add_line_markers(content: str) -> str:
278
+ """Add line number markers (<lid:N>) to each line."""
279
+ lines = normalize_newlines(content).split('\n')
280
+ marked_lines = []
281
+ for i, line in enumerate(lines, start=1):
282
+ marked_lines.append(f"<lid:{i}>{line}")
283
+ return '\n'.join(marked_lines)
284
+
285
+
286
+ @dataclass
287
+ class WindowSegment:
288
+ """A sliding window segment of a document."""
289
+ content: str
290
+ start_line: int
291
+ end_line: int
292
+ overlap_start: int
293
+ is_first: bool = False
294
+
295
+
296
+ def split_by_sliding_window(
297
+ content: str,
298
+ max_chars: int,
299
+ overlap_ratio: float = 0.2
300
+ ) -> List[WindowSegment]:
301
+ """Split content into sliding window segments based on character count."""
302
+ lines = normalize_newlines(content).split('\n')
303
+ total_lines = len(lines)
304
+
305
+ if total_lines == 0:
306
+ return []
307
+
308
+ marked_content = add_line_markers(content)
309
+ total_chars = len(marked_content)
310
+
311
+ if total_chars <= max_chars:
312
+ return [WindowSegment(
313
+ content=marked_content,
314
+ start_line=1,
315
+ end_line=total_lines,
316
+ overlap_start=1,
317
+ is_first=True
318
+ )]
319
+
320
+ segments = []
321
+ current_start = 0
322
+
323
+ while current_start < total_lines:
324
+ left = current_start
325
+ right = total_lines
326
+ best_end = current_start + 1
327
+
328
+ while left < right:
329
+ mid = (left + right + 1) // 2
330
+ segment_lines = lines[current_start:mid]
331
+ marked_segment = []
332
+ for i, line in enumerate(segment_lines, start=current_start + 1):
333
+ marked_segment.append(f"<lid:{i}>{line}")
334
+ marked_content = '\n'.join(marked_segment)
335
+
336
+ chars = len(marked_content)
337
+
338
+ if chars <= max_chars:
339
+ best_end = mid
340
+ left = mid
341
+ else:
342
+ right = mid - 1
343
+
344
+ segment_lines = lines[current_start:best_end]
345
+ marked_segment = []
346
+ for i, line in enumerate(segment_lines, start=current_start + 1):
347
+ marked_segment.append(f"<lid:{i}>{line}")
348
+ marked_content = '\n'.join(marked_segment)
349
+
350
+ is_first = (current_start == 0)
351
+ overlap_start = 1 if is_first else (current_start + 1)
352
+
353
+ segments.append(WindowSegment(
354
+ content=marked_content,
355
+ start_line=current_start + 1,
356
+ end_line=best_end,
357
+ overlap_start=overlap_start,
358
+ is_first=is_first
359
+ ))
360
+
361
+ current_window_chars = len(marked_content)
362
+ overlap_chars = int(current_window_chars * overlap_ratio)
363
+
364
+ overlap_start_line = best_end
365
+ accumulated_chars = 0
366
+ for line_idx in range(best_end - 1, current_start - 1, -1):
367
+ line_with_marker = f"<lid:{line_idx + 1}>{lines[line_idx]}"
368
+ line_chars = len(line_with_marker)
369
+ if accumulated_chars + line_chars <= overlap_chars:
370
+ accumulated_chars += line_chars
371
+ overlap_start_line = line_idx
372
+ else:
373
+ break
374
+
375
+ next_start = overlap_start_line
376
+ if next_start <= current_start:
377
+ next_start = best_end
378
+
379
+ current_start = next_start
380
+
381
+ if best_end >= total_lines:
382
+ break
383
+
384
+ for i in range(1, len(segments)):
385
+ prev_end = segments[i-1].end_line
386
+ segments[i].overlap_start = prev_end + 1
387
+
388
+ return segments
389
+
390
+
391
+ def adjust_function_for_segment(
392
+ func: Dict,
393
+ segment: WindowSegment,
394
+ is_segment_mode: bool = False
395
+ ) -> Optional[Dict]:
396
+ """Adjust function line numbers to only affect the non-overlap region."""
397
+ operation = func.get('operation')
398
+
399
+ if not is_segment_mode:
400
+ return func
401
+
402
+ non_overlap_start = segment.overlap_start
403
+ segment_end = segment.end_line
404
+
405
+ if operation == 'keep_all':
406
+ return None
407
+
408
+ if operation == 'remove_all':
409
+ if non_overlap_start > segment_end:
410
+ return None
411
+ return {
412
+ 'operation': 'remove_lines',
413
+ 'start_line': non_overlap_start,
414
+ 'end_line': segment_end
415
+ }
416
+
417
+ if operation == 'remove_lines':
418
+ start = func['start_line']
419
+ end = func['end_line']
420
+
421
+ if end < non_overlap_start:
422
+ return None
423
+ if start < non_overlap_start:
424
+ start = non_overlap_start
425
+ if end > segment_end:
426
+ end = segment_end
427
+
428
+ return {
429
+ 'operation': 'remove_lines',
430
+ 'start_line': start,
431
+ 'end_line': end
432
+ }
433
+
434
+ if operation == 'replace_str':
435
+ line_num = func['line_number']
436
+ if line_num < non_overlap_start or line_num > segment_end:
437
+ return None
438
+ return func.copy()
439
+
440
+ if operation == 'add_line':
441
+ base_pos = func['base_position']
442
+ if base_pos < non_overlap_start or base_pos > segment_end:
443
+ return None
444
+ return func.copy()
445
+
446
+ return func
447
+
448
+
449
+ def merge_window_functions(
450
+ window_results: List[Tuple[WindowSegment, List[Dict]]],
451
+ total_lines: int
452
+ ) -> Tuple[List[Dict], bool, bool]:
453
+ """Merge function results from all windows with overlap-aware aggregation."""
454
+ if len(window_results) == 0:
455
+ return [], True, False
456
+
457
+ if len(window_results) == 1:
458
+ segment, funcs = window_results[0]
459
+ if len(funcs) == 1:
460
+ if funcs[0]['operation'] == 'keep_all':
461
+ return [], True, False
462
+ if funcs[0]['operation'] == 'remove_all':
463
+ return [], False, True
464
+ return funcs, False, False
465
+
466
+ is_segment_mode = True
467
+ merged_functions = []
468
+
469
+ for segment, funcs in window_results:
470
+ for func in funcs:
471
+ adjusted = adjust_function_for_segment(func, segment, is_segment_mode)
472
+ if adjusted:
473
+ merged_functions.append(adjusted)
474
+
475
+ if not merged_functions:
476
+ return [], True, False
477
+
478
+ all_remove_lines = all(f['operation'] == 'remove_lines' for f in merged_functions)
479
+ if all_remove_lines:
480
+ covered_lines = set()
481
+ for f in merged_functions:
482
+ for ln in range(f['start_line'], f['end_line'] + 1):
483
+ covered_lines.add(ln)
484
+ if covered_lines == set(range(1, total_lines + 1)):
485
+ return [], False, True
486
+
487
+ return merged_functions, False, False
488
+
489
+
490
+ # ==================== Data I/O ====================
491
+
492
+ class PerFileParquetWriter:
493
+ """Writes output parquet files (columns: original, model_output) per input file."""
494
+
495
+ def __init__(self, output_dir: str):
496
+ self.output_dir = Path(output_dir)
497
+ self.output_dir.mkdir(parents=True, exist_ok=True)
498
+ self.file_buffers: Dict[str, List[Dict]] = defaultdict(list)
499
+
500
+ def add(self, filename: str, original: str, model_output: str):
501
+ """Add a record to the buffer."""
502
+ self.file_buffers[filename].append({
503
+ 'original': original,
504
+ 'model_output': model_output
505
+ })
506
+
507
+ def flush_file(self, filename: str):
508
+ """Flush the buffer for a specific file to disk."""
509
+ if filename not in self.file_buffers or not self.file_buffers[filename]:
510
+ return
511
+
512
+ df = pd.DataFrame(self.file_buffers[filename])
513
+ output_file = self.output_dir / filename
514
+ df.to_parquet(output_file, index=False)
515
+
516
+ self.file_buffers[filename] = []
517
+
518
+ def close(self):
519
+ """Flush all remaining buffers to disk."""
520
+ for filename, records in self.file_buffers.items():
521
+ if not records:
522
+ continue
523
+ df = pd.DataFrame(records)
524
+ output_file = self.output_dir / filename
525
+ df.to_parquet(output_file, index=False)
526
+
527
+ self.file_buffers.clear()
528
+
529
+
530
+ # ==================== Binary Batch Inference ====================
531
+
532
+ def binary_batch_inference(
533
+ llm,
534
+ sampling_params,
535
+ prompts: List[str],
536
+ mappings: List[Tuple[int, int]],
537
+ tasks: List,
538
+ logger,
539
+ min_batch_size: int = 1
540
+ ) -> Tuple[int, int]:
541
+ """
542
+ Batch inference with binary split on failure.
543
+
544
+ When a batch fails, it is split in half and each half is retried recursively.
545
+ Prompts that still fail at min_batch_size are marked as keep_all().
546
+
547
+ Returns:
548
+ (success_count, failed_count)
549
+ """
550
+ if not prompts:
551
+ return 0, 0
552
+
553
+ try:
554
+ outputs = llm.generate(prompts, sampling_params)
555
+
556
+ for (task_idx, seg_idx), output in zip(mappings, outputs):
557
+ response = output.outputs[0].text
558
+ task = tasks[task_idx]
559
+ while len(task.segment_responses) <= seg_idx:
560
+ task.segment_responses.append("")
561
+ task.segment_responses[seg_idx] = response
562
+
563
+ return len(prompts), 0
564
+
565
+ except Exception as e:
566
+ batch_size = len(prompts)
567
+
568
+ if batch_size <= min_batch_size:
569
+ failed_count = 0
570
+ for task_idx, seg_idx in mappings:
571
+ task = tasks[task_idx]
572
+ task.failed_segments.add(seg_idx)
573
+ while len(task.segment_responses) <= seg_idx:
574
+ task.segment_responses.append("")
575
+ task.segment_responses[seg_idx] = "keep_all()"
576
+ failed_count += 1
577
+ logger.warning(f"Batch inference failed (size={batch_size}), marking as keep_all: {e}")
578
+ return 0, failed_count
579
+
580
+ mid = batch_size // 2
581
+ logger.warning(f"Batch inference failed (size={batch_size}), splitting and retrying: {e}")
582
+
583
+ left_success, left_failed = binary_batch_inference(
584
+ llm, sampling_params,
585
+ prompts[:mid], mappings[:mid],
586
+ tasks, logger, min_batch_size
587
+ )
588
+
589
+ right_success, right_failed = binary_batch_inference(
590
+ llm, sampling_params,
591
+ prompts[mid:], mappings[mid:],
592
+ tasks, logger, min_batch_size
593
+ )
594
+
595
+ return left_success + right_success, left_failed + right_failed
596
+
597
+
598
+ # ==================== Single-GPU Worker Process ====================
599
+
600
+ @dataclass
601
+ class InferTask:
602
+ """Inference task for a single document."""
603
+ data_idx: int
604
+ filename: str
605
+ content: str
606
+ segments: List[WindowSegment] = field(default_factory=list)
607
+ segment_responses: List[str] = field(default_factory=list)
608
+ failed_segments: set = field(default_factory=set)
609
+
610
+
611
+ def worker_process(
612
+ gpu_id: int,
613
+ config: Config,
614
+ file_list: List[str],
615
+ result_queue: mp.Queue
616
+ ):
617
+ """
618
+ Single-GPU worker process.
619
+
620
+ Args:
621
+ gpu_id: GPU ID to bind to
622
+ config: Runtime configuration
623
+ file_list: List of filenames assigned to this GPU
624
+ result_queue: Queue for reporting results back to main process
625
+ """
626
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
627
+
628
+ logger = setup_logger(gpu_id)
629
+
630
+ logger.info(f"Worker started, assigned {len(file_list)} files")
631
+
632
+ stats = {
633
+ 'total': 0,
634
+ 'success': 0,
635
+ 'failed': 0,
636
+ 'split_count': 0,
637
+ 'keep_all_count': 0,
638
+ 'remove_all_count': 0,
639
+ 'modified_count': 0
640
+ }
641
+
642
+ if not file_list:
643
+ logger.info("No files to process")
644
+ result_queue.put(('done', gpu_id, stats))
645
+ return
646
+
647
+ try:
648
+ logger.info("Loading tokenizer...")
649
+ tokenizer = AutoTokenizer.from_pretrained(
650
+ config.model_path,
651
+ trust_remote_code=True
652
+ )
653
+
654
+ logger.info("Loading vLLM model...")
655
+ from vllm import LLM, SamplingParams
656
+
657
+ llm = LLM(
658
+ model=config.model_path,
659
+ trust_remote_code=True,
660
+ dtype=torch.bfloat16,
661
+ gpu_memory_utilization=config.gpu_memory_utilization,
662
+ max_model_len=config.max_model_len,
663
+ tensor_parallel_size=1,
664
+ enforce_eager=False
665
+ )
666
+
667
+ sampling_params = SamplingParams(
668
+ max_tokens=config.max_new_tokens,
669
+ temperature=0.0,
670
+ top_p=1.0,
671
+ top_k=-1
672
+ )
673
+
674
+ logger.info("Model loaded successfully")
675
+
676
+ output_writer = PerFileParquetWriter(config.output_dir)
677
+
678
+ input_path = Path(config.input_dir)
679
+
680
+ for file_idx, filename in enumerate(file_list):
681
+ logger.info(f"Processing file [{file_idx + 1}/{len(file_list)}]: {filename}")
682
+
683
+ file_path = input_path / filename
684
+ parquet_file = pq.ParquetFile(file_path)
685
+
686
+ total_rows = parquet_file.metadata.num_rows
687
+ logger.info(f"Total rows in file: {total_rows}")
688
+
689
+ file_processed = 0
690
+ batch_idx = 0
691
+
692
+ for record_batch in parquet_file.iter_batches(batch_size=config.read_batch_size, columns=['original']):
693
+ batch_idx += 1
694
+ batch_df = record_batch.to_pandas()
695
+
696
+ if 'original' not in batch_df.columns:
697
+ if batch_idx == 1:
698
+ logger.warning(f"File {filename} missing 'original' column, skipping")
699
+ break
700
+
701
+ contents = batch_df['original'].tolist()
702
+ batch_size = len(contents)
703
+ stats['total'] += batch_size
704
+ file_processed += batch_size
705
+
706
+ logger.info(f" Batch {batch_idx}: processing {batch_size} rows ({file_processed}/{total_rows})")
707
+
708
+ tasks = []
709
+ for idx, content in enumerate(contents):
710
+ task = InferTask(
711
+ data_idx=idx,
712
+ filename=filename,
713
+ content=content if content else ""
714
+ )
715
+
716
+ if content and content.strip():
717
+ segments = split_by_sliding_window(
718
+ content,
719
+ config.max_chars,
720
+ config.overlap_ratio
721
+ )
722
+ task.segments = segments
723
+
724
+ if len(segments) > 1:
725
+ stats['split_count'] += 1
726
+
727
+ tasks.append(task)
728
+
729
+ all_prompts = []
730
+ prompt_to_task_segment = []
731
+
732
+ for task_idx, task in enumerate(tasks):
733
+ for seg_idx, seg in enumerate(task.segments):
734
+ messages = [
735
+ {"role": "system", "content": SYSTEM_INSTRUCTION},
736
+ {"role": "user", "content": seg.content},
737
+ ]
738
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False)
739
+ all_prompts.append(prompt)
740
+ prompt_to_task_segment.append((task_idx, seg_idx))
741
+
742
+ if all_prompts:
743
+ infer_start_time = time.time()
744
+ total_infer_prompts = 0
745
+ skipped_prompts = 0
746
+
747
+ for batch_start in range(0, len(all_prompts), config.infer_batch_size):
748
+ batch_end = min(batch_start + config.infer_batch_size, len(all_prompts))
749
+ batch_prompts = all_prompts[batch_start:batch_end]
750
+ batch_mapping = prompt_to_task_segment[batch_start:batch_end]
751
+
752
+ success, failed = binary_batch_inference(
753
+ llm, sampling_params,
754
+ batch_prompts, batch_mapping,
755
+ tasks, logger, min_batch_size=1
756
+ )
757
+ total_infer_prompts += success
758
+ skipped_prompts += failed
759
+
760
+ infer_time = time.time() - infer_start_time
761
+ throughput = total_infer_prompts / infer_time if infer_time > 0 else 0
762
+ logger.info(f" Inference done: {total_infer_prompts} prompts, {skipped_prompts} failed, {infer_time:.2f}s, {throughput:.1f} prompts/s")
763
+
764
+ for task in tasks:
765
+ try:
766
+ content = task.content
767
+
768
+ if not content or not content.strip():
769
+ output_writer.add(task.filename, content if content else "", "")
770
+ stats['failed'] += 1
771
+ continue
772
+
773
+ if not task.segments:
774
+ output_writer.add(task.filename, content, "")
775
+ stats['failed'] += 1
776
+ continue
777
+
778
+ if len(task.failed_segments) == len(task.segments):
779
+ output_writer.add(task.filename, content, "# all segments failed")
780
+ stats['failed'] += 1
781
+ logger.warning(f"All segments failed, keeping original: {task.filename}, data_idx={task.data_idx}")
782
+ continue
783
+
784
+ while len(task.segment_responses) < len(task.segments):
785
+ task.segment_responses.append("keep_all()")
786
+
787
+ pred_strs = [extract_prediction(r) for r in task.segment_responses]
788
+
789
+ window_results = []
790
+ for seg_idx, (seg, pred_str) in enumerate(zip(task.segments, pred_strs)):
791
+ funcs = parse_function_list(pred_str)
792
+ window_results.append((seg, funcs))
793
+
794
+ total_lines = len(normalize_newlines(content).split('\n'))
795
+ merged_funcs, is_keep_all, is_remove_all = merge_window_functions(
796
+ window_results, total_lines
797
+ )
798
+
799
+ if is_keep_all:
800
+ model_output_str = "keep_all()"
801
+ stats['keep_all_count'] += 1
802
+ elif is_remove_all:
803
+ model_output_str = "remove_all()"
804
+ stats['remove_all_count'] += 1
805
+ else:
806
+ model_output_str = functions_to_string(merged_funcs)
807
+ stats['modified_count'] += 1
808
+ if task.failed_segments:
809
+ model_output_str += f"\n# Failed segments: {sorted(task.failed_segments)}"
810
+
811
+ output_writer.add(task.filename, content, model_output_str)
812
+ stats['success'] += 1
813
+
814
+ except Exception as e:
815
+ output_writer.add(task.filename, task.content if task.content else "", f"# ERROR: {str(e)}")
816
+ stats['failed'] += 1
817
+
818
+ del tasks
819
+ del all_prompts
820
+ del prompt_to_task_segment
821
+
822
+ output_writer.flush_file(filename)
823
+
824
+ logger.info(f"File completed: {filename}, rows processed: {file_processed}")
825
+
826
+ output_writer.close()
827
+
828
+ logger.info("=" * 40)
829
+ logger.info(f"GPU {gpu_id} processing complete")
830
+ logger.info(f"Total rows: {stats['total']}")
831
+ logger.info(f"Success: {stats['success']}, Failed: {stats['failed']}")
832
+ logger.info(f"keep_all: {stats['keep_all_count']}, remove_all: {stats['remove_all_count']}, modified: {stats['modified_count']}")
833
+ logger.info("=" * 40)
834
+
835
+ except Exception as e:
836
+ logger.error(f"GPU {gpu_id} encountered an error: {e}")
837
+ import traceback
838
+ traceback.print_exc()
839
+
840
+ result_queue.put(('done', gpu_id, stats))
841
+
842
+
843
+ # ==================== Main ====================
844
+
845
+ def get_files_to_process(config: Config) -> Tuple[List[str], int]:
846
+ """Get list of files to process, skipping already-completed ones."""
847
+ input_path = Path(config.input_dir)
848
+ output_path = Path(config.output_dir)
849
+
850
+ parquet_files = sorted(input_path.glob("*.parquet"))
851
+
852
+ files_to_process = []
853
+ skipped = 0
854
+
855
+ for pf in parquet_files:
856
+ output_file = output_path / pf.name
857
+ if output_file.exists():
858
+ skipped += 1
859
+ continue
860
+ files_to_process.append(pf.name)
861
+
862
+ return files_to_process, skipped
863
+
864
+
865
+ def main():
866
+ parser = argparse.ArgumentParser(
867
+ description="UltraX large-scale inference: generate cleaning operations via data-parallel vLLM."
868
+ )
869
+ parser.add_argument("--input_dir", type=str, required=True,
870
+ help="Input directory containing parquet files with 'original' column")
871
+ parser.add_argument("--model_path", type=str, required=True,
872
+ help="Path to the trained refinement model")
873
+ parser.add_argument("--output_dir", type=str, required=True,
874
+ help="Output directory for parquet files (columns: original, model_output)")
875
+ parser.add_argument("--max_chars", type=int, default=48000,
876
+ help="Max characters per sliding window segment (default: 48000)")
877
+ parser.add_argument("--overlap_ratio", type=float, default=0.2,
878
+ help="Sliding window overlap ratio (default: 0.2)")
879
+ parser.add_argument("--gpu_memory_utilization", type=float, default=0.85,
880
+ help="vLLM GPU memory utilization (default: 0.85)")
881
+ parser.add_argument("--max_model_len", type=int, default=32768,
882
+ help="vLLM max model length (default: 32768)")
883
+ parser.add_argument("--max_new_tokens", type=int, default=4096,
884
+ help="Max new tokens to generate (default: 4096)")
885
+ parser.add_argument("--num_gpus", type=int, default=8,
886
+ help="Number of GPUs for data parallelism (default: 8)")
887
+ parser.add_argument("--infer_batch_size", type=int, default=1000,
888
+ help="Inference batch size per GPU (default: 1000)")
889
+ parser.add_argument("--read_batch_size", type=int, default=500,
890
+ help="Streaming read batch size from parquet (default: 500)")
891
+ args = parser.parse_args()
892
+
893
+ logger = setup_logger()
894
+
895
+ config = Config(
896
+ input_dir=args.input_dir,
897
+ model_path=args.model_path,
898
+ output_dir=args.output_dir,
899
+ max_chars=args.max_chars,
900
+ overlap_ratio=args.overlap_ratio,
901
+ gpu_memory_utilization=args.gpu_memory_utilization,
902
+ max_model_len=args.max_model_len,
903
+ max_new_tokens=args.max_new_tokens,
904
+ num_gpus=args.num_gpus,
905
+ infer_batch_size=args.infer_batch_size,
906
+ read_batch_size=args.read_batch_size
907
+ )
908
+
909
+ if not Path(config.input_dir).exists():
910
+ logger.error(f"Input directory does not exist: {config.input_dir}")
911
+ return
912
+
913
+ logger.info("Scanning files...")
914
+ files_to_process, skipped = get_files_to_process(config)
915
+
916
+ logger.info(f"Total files: {len(files_to_process) + skipped}")
917
+ if skipped > 0:
918
+ logger.info(f"Skipped (already processed): {skipped}")
919
+ logger.info(f"Files to process: {len(files_to_process)}")
920
+
921
+ if not files_to_process:
922
+ logger.info("All files have been processed")
923
+ return
924
+
925
+ files_per_gpu = [[] for _ in range(config.num_gpus)]
926
+ for i, filename in enumerate(files_to_process):
927
+ gpu_idx = i % config.num_gpus
928
+ files_per_gpu[gpu_idx].append(filename)
929
+
930
+ logger.info("=" * 60)
931
+ logger.info("Data Parallel Configuration")
932
+ logger.info("=" * 60)
933
+ for gpu_id in range(config.num_gpus):
934
+ logger.info(f"GPU {gpu_id}: assigned {len(files_per_gpu[gpu_id])} files")
935
+ logger.info("=" * 60)
936
+
937
+ Path(config.output_dir).mkdir(parents=True, exist_ok=True)
938
+
939
+ logger.info("Starting worker processes...")
940
+
941
+ result_queue = mp.Queue()
942
+ processes = []
943
+
944
+ for gpu_id in range(config.num_gpus):
945
+ p = mp.Process(
946
+ target=worker_process,
947
+ args=(gpu_id, config, files_per_gpu[gpu_id], result_queue)
948
+ )
949
+ p.start()
950
+ processes.append(p)
951
+
952
+ total_stats = {
953
+ 'total': 0,
954
+ 'success': 0,
955
+ 'failed': 0,
956
+ 'split_count': 0,
957
+ 'keep_all_count': 0,
958
+ 'remove_all_count': 0,
959
+ 'modified_count': 0
960
+ }
961
+
962
+ completed = 0
963
+ while completed < config.num_gpus:
964
+ result = result_queue.get()
965
+ if result[0] == 'done':
966
+ _, gpu_id, stats = result
967
+ logger.info(f"GPU {gpu_id} completed")
968
+ for key in total_stats:
969
+ total_stats[key] += stats.get(key, 0)
970
+ completed += 1
971
+
972
+ for p in processes:
973
+ p.join()
974
+
975
+ logger.info("=" * 60)
976
+ logger.info("All processing complete - Summary")
977
+ logger.info("=" * 60)
978
+ logger.info(f"Total rows: {total_stats['total']}")
979
+ logger.info(f"Success: {total_stats['success']}")
980
+ logger.info(f"Failed: {total_stats['failed']}")
981
+ logger.info(f"Split documents: {total_stats['split_count']}")
982
+ logger.info(f"keep_all: {total_stats['keep_all_count']}")
983
+ logger.info(f"remove_all: {total_stats['remove_all_count']}")
984
+ logger.info(f"Modified: {total_stats['modified_count']}")
985
+ logger.info("=" * 60)
986
+
987
+
988
+ if __name__ == "__main__":
989
+ mp.set_start_method('spawn', force=True)
990
+ main()
code/stage2_large_scale_execution/post_processing/post_process_and_execute.py ADDED
@@ -0,0 +1,821 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ UltraX Post-Processing and Execution Script
5
+
6
+ This script reads inference output (original + model_output columns), parses the
7
+ predicted function calls, applies post-processing (ambiguous filtering, same-line
8
+ merging, duplicate pattern detection), and executes the deterministic program to
9
+ produce cleaned text.
10
+
11
+ Features:
12
+ 1. Reads parquet files with 'original' and 'model_output' columns
13
+ 2. Parses and validates function calls from model_output
14
+ 3. Filters ambiguous replace_str operations (multiple occurrences in target line)
15
+ 4. Merges multiple replace_str operations on the same line
16
+ 5. Detects repetitive/looping patterns via similarity clustering
17
+ 6. Executes validated operations deterministically
18
+ 7. Outputs 3 columns: original, cleaned, processed_functions
19
+
20
+ Usage:
21
+ python post_process_and_execute.py --input_dir /path/to/inference_output --output_dir /path/to/cleaned
22
+ """
23
+
24
+ import os
25
+ import re
26
+ import logging
27
+ import difflib
28
+ import time
29
+ import argparse
30
+ import multiprocessing as mp
31
+ from pathlib import Path
32
+ from typing import List, Dict, Optional, Tuple
33
+ from collections import defaultdict
34
+
35
+ import pandas as pd
36
+ import pyarrow.parquet as pq
37
+
38
+
39
+ def normalize_newlines(text: str) -> str:
40
+ """Normalize \\r\\n and \\r to \\n.
41
+
42
+ Must be consistent with the inference script's normalization,
43
+ since line numbers are computed based on \\n-split lines.
44
+ """
45
+ if not isinstance(text, str):
46
+ return text
47
+ return text.replace('\r\n', '\n').replace('\r', '\n')
48
+
49
+
50
+ def setup_logger(worker_id=None):
51
+ """Configure logger for the current process."""
52
+ if worker_id is not None:
53
+ log_format = '%(asctime)s - Worker{} - %(levelname)s - %(message)s'.format(worker_id)
54
+ else:
55
+ log_format = '%(asctime)s - %(levelname)s - %(message)s'
56
+ logging.basicConfig(
57
+ level=logging.INFO,
58
+ format=log_format,
59
+ datefmt='%Y-%m-%d %H:%M:%S',
60
+ force=True
61
+ )
62
+ return logging.getLogger(__name__)
63
+
64
+
65
+ # ==================== Similarity Clustering ====================
66
+
67
+ def _find_similar_groups(strings, ratio_threshold):
68
+ """Greedy clustering of strings by similarity ratio. Returns list of index groups."""
69
+ groups = []
70
+ for idx, s in enumerate(strings):
71
+ merged = False
72
+ for group in groups:
73
+ rep = group[0]
74
+ if difflib.SequenceMatcher(None, rep, s).ratio() >= ratio_threshold:
75
+ group[1].append(idx)
76
+ merged = True
77
+ break
78
+ if not merged:
79
+ groups.append((s, [idx]))
80
+ return [g[1] for g in groups]
81
+
82
+
83
+ # ==================== Repetitive Pattern Detection ====================
84
+
85
+ def detect_repetitive_functions(
86
+ functions,
87
+ add_line_exact_threshold=2,
88
+ add_line_diff_pos_threshold=3,
89
+ replace_str_content_threshold=30,
90
+ remove_lines_threshold=3,
91
+ add_line_similar_threshold=3,
92
+ similarity_ratio=0.85,
93
+ original=None,
94
+ replace_str_legit_ratio=0.8,
95
+ ):
96
+ """
97
+ Detect repetitive/looping patterns in function lists.
98
+
99
+ Detection rules:
100
+ 1. add_line: identical (base_position, content) > exact_threshold
101
+ 2. add_line: same content but different positions > diff_pos_threshold
102
+ 3. replace_str: identical (search, replace) > replace_threshold
103
+ Exemption: if search appears in original >= count * legit_ratio times,
104
+ it's treated as legitimate high-frequency template cleaning.
105
+ 4. remove_lines: identical (start, end) > remove_threshold
106
+ 5. add_line: content similarity >= ratio in cluster > similar_threshold
107
+ """
108
+ min_threshold = min(add_line_exact_threshold, remove_lines_threshold)
109
+ if len(functions) < min_threshold + 1:
110
+ return False
111
+
112
+ add_line_exact_counts = defaultdict(int)
113
+ replace_str_content_counts = defaultdict(int)
114
+ remove_lines_counts = defaultdict(int)
115
+ add_line_by_content = defaultdict(set)
116
+ add_line_contents = []
117
+
118
+ for func in functions:
119
+ op = func.get('operation')
120
+ if op == 'add_line':
121
+ base_pos = func.get('base_position')
122
+ content = func.get('content', '')
123
+ add_line_exact_counts[(base_pos, content)] += 1
124
+ add_line_by_content[content].add(base_pos)
125
+ add_line_contents.append(content)
126
+ elif op == 'replace_str':
127
+ key = (func.get('search_content'), func.get('replace_content'))
128
+ replace_str_content_counts[key] += 1
129
+ elif op == 'remove_lines':
130
+ key = (func.get('start_line'), func.get('end_line'))
131
+ remove_lines_counts[key] += 1
132
+
133
+ for count in add_line_exact_counts.values():
134
+ if count > add_line_exact_threshold:
135
+ return True
136
+
137
+ for positions in add_line_by_content.values():
138
+ if len(positions) > add_line_diff_pos_threshold:
139
+ return True
140
+
141
+ for (search, _replace), count in replace_str_content_counts.items():
142
+ if count > replace_str_content_threshold:
143
+ if original and isinstance(search, str) and search:
144
+ occ = original.count(search)
145
+ if occ >= count * replace_str_legit_ratio:
146
+ continue
147
+ return True
148
+
149
+ for count in remove_lines_counts.values():
150
+ if count > remove_lines_threshold:
151
+ return True
152
+
153
+ if len(add_line_contents) > add_line_similar_threshold:
154
+ groups = _find_similar_groups(add_line_contents, similarity_ratio)
155
+ for group_indices in groups:
156
+ if len(group_indices) > add_line_similar_threshold:
157
+ return True
158
+
159
+ return False
160
+
161
+
162
+ # ==================== Function Parsing ====================
163
+
164
+ def parse_quoted_string(s, quote_char):
165
+ """Parse a quoted string with escape character handling."""
166
+ if not s.startswith(quote_char):
167
+ raise ValueError("Expected quote char")
168
+
169
+ result = []
170
+ i = 1
171
+ while i < len(s):
172
+ if s[i] == '\\' and i + 1 < len(s):
173
+ next_char = s[i + 1]
174
+ if next_char == 'n':
175
+ result.append('\n')
176
+ elif next_char == 't':
177
+ result.append('\t')
178
+ elif next_char == 'r':
179
+ result.append('\r')
180
+ elif next_char == '\\':
181
+ result.append('\\')
182
+ elif next_char == quote_char:
183
+ result.append(quote_char)
184
+ else:
185
+ result.append('\\')
186
+ result.append(next_char)
187
+ i += 2
188
+ elif s[i] == quote_char:
189
+ return ''.join(result), s[i + 1:]
190
+ else:
191
+ result.append(s[i])
192
+ i += 1
193
+
194
+ raise ValueError("String not properly terminated")
195
+
196
+
197
+ def parse_function_call(func_str):
198
+ """Parse a function call string into a structured dict."""
199
+ func_str = func_str.strip()
200
+ if not func_str:
201
+ return None
202
+
203
+ if func_str == 'keep_all()':
204
+ return {'operation': 'keep_all'}
205
+
206
+ if func_str == 'remove_all()':
207
+ return {'operation': 'remove_all'}
208
+
209
+ match = re.match(r'remove_lines\((\d+),\s*(\d+)\)', func_str)
210
+ if match:
211
+ return {
212
+ 'operation': 'remove_lines',
213
+ 'start_line': int(match.group(1)),
214
+ 'end_line': int(match.group(2))
215
+ }
216
+
217
+ if func_str.startswith('replace_str('):
218
+ try:
219
+ inner = func_str[len('replace_str('):-1]
220
+ first_comma = inner.find(',')
221
+ if first_comma == -1:
222
+ return None
223
+
224
+ line_num = int(inner[:first_comma].strip())
225
+ rest = inner[first_comma + 1:].strip()
226
+
227
+ if rest.startswith("'"):
228
+ search_content, rest = parse_quoted_string(rest, "'")
229
+ elif rest.startswith('"'):
230
+ search_content, rest = parse_quoted_string(rest, '"')
231
+ else:
232
+ return None
233
+
234
+ rest = rest.lstrip(',').strip()
235
+
236
+ if rest.startswith("'"):
237
+ replace_content, _ = parse_quoted_string(rest, "'")
238
+ elif rest.startswith('"'):
239
+ replace_content, _ = parse_quoted_string(rest, '"')
240
+ else:
241
+ return None
242
+
243
+ return {
244
+ 'operation': 'replace_str',
245
+ 'line_number': line_num,
246
+ 'search_content': search_content,
247
+ 'replace_content': replace_content
248
+ }
249
+ except Exception:
250
+ return None
251
+
252
+ if func_str.startswith('add_line('):
253
+ try:
254
+ inner = func_str[len('add_line('):-1]
255
+ first_comma = inner.find(',')
256
+ if first_comma == -1:
257
+ return None
258
+
259
+ base_pos = int(inner[:first_comma].strip())
260
+ rest = inner[first_comma + 1:].strip()
261
+
262
+ second_comma = rest.find(',')
263
+ if second_comma == -1:
264
+ return None
265
+
266
+ sub_index = int(rest[:second_comma].strip())
267
+ rest = rest[second_comma + 1:].strip()
268
+
269
+ if rest.startswith("'"):
270
+ content, _ = parse_quoted_string(rest, "'")
271
+ elif rest.startswith('"'):
272
+ content, _ = parse_quoted_string(rest, '"')
273
+ else:
274
+ return None
275
+
276
+ return {
277
+ 'operation': 'add_line',
278
+ 'base_position': base_pos,
279
+ 'sub_index': sub_index,
280
+ 'content': content
281
+ }
282
+ except Exception:
283
+ return None
284
+
285
+ return None
286
+
287
+
288
+ def parse_function_list(content):
289
+ """Parse a newline-separated list of function calls, skipping comments and separators."""
290
+ if not content or not content.strip():
291
+ return []
292
+
293
+ functions = []
294
+ for line in content.strip().split('\n'):
295
+ line = line.strip()
296
+ if line and not line.startswith('#') and line != '---':
297
+ func_info = parse_function_call(line)
298
+ if func_info:
299
+ functions.append(func_info)
300
+ return functions
301
+
302
+
303
+ def extract_prediction(response):
304
+ """Strip <think>...</think> blocks from model output."""
305
+ if not response:
306
+ return ""
307
+ return re.sub(r'<think>.*?</think>\s*', '', response, flags=re.DOTALL).strip()
308
+
309
+
310
+ def functions_to_string(functions):
311
+ """Convert a list of function dicts back to string representation."""
312
+ if not functions:
313
+ return ""
314
+
315
+ lines = []
316
+ for func in functions:
317
+ op = func.get('operation', '')
318
+ if op == 'keep_all':
319
+ lines.append('keep_all()')
320
+ elif op == 'remove_all':
321
+ lines.append('remove_all()')
322
+ elif op == 'remove_lines':
323
+ lines.append("remove_lines({}, {})".format(func['start_line'], func['end_line']))
324
+ elif op == 'replace_str':
325
+ lines.append("replace_str({}, {}, {})".format(
326
+ func['line_number'], repr(func['search_content']), repr(func['replace_content'])))
327
+ elif op == 'add_line':
328
+ lines.append("add_line({}, {}, {})".format(
329
+ func['base_position'], func['sub_index'], repr(func['content'])))
330
+
331
+ return '\n'.join(lines)
332
+
333
+
334
+ # ==================== Function Post-Processing ====================
335
+
336
+ def extract_modifications(search, replace, pos_in_line):
337
+ """Extract actual modifications from search/replace content using diff."""
338
+ matcher = difflib.SequenceMatcher(None, search, replace)
339
+ modifications = []
340
+
341
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():
342
+ if tag == 'equal':
343
+ continue
344
+ abs_start = pos_in_line + i1
345
+ abs_end = pos_in_line + i2
346
+ new_content = replace[j1:j2]
347
+ modifications.append((abs_start, abs_end, new_content))
348
+
349
+ return modifications
350
+
351
+
352
+ def force_merge_all_ops(ops, orig_line, line_num):
353
+ """Force-merge all replace_str operations on a single line into one operation."""
354
+ if not ops:
355
+ return ops
356
+
357
+ all_modifications = []
358
+ processed_mod_ranges = []
359
+
360
+ def trim_modification(start, end, content):
361
+ current_start, current_end = start, end
362
+
363
+ for p_start, p_end in processed_mod_ranges:
364
+ if current_end <= p_start or current_start >= p_end:
365
+ continue
366
+ if p_start <= current_start and current_end <= p_end:
367
+ return None
368
+ if p_start <= current_start < p_end < current_end:
369
+ trim_len = p_end - current_start
370
+ current_start = p_end
371
+ content = content[trim_len:] if trim_len < len(content) else ''
372
+ elif current_start < p_start < current_end <= p_end:
373
+ trim_len = current_end - p_start
374
+ current_end = p_start
375
+ content = content[:-trim_len] if trim_len < len(content) else ''
376
+ elif current_start < p_start and p_end < current_end:
377
+ return None
378
+
379
+ if current_start >= current_end:
380
+ return None
381
+
382
+ return (current_start, current_end, content)
383
+
384
+ sorted_ops = sorted(ops, key=lambda op: len(op['search_content']), reverse=True)
385
+ search_next_start = {}
386
+
387
+ for op in sorted_ops:
388
+ search = op['search_content']
389
+ replace = op['replace_content']
390
+ start_from = search_next_start.get(search, 0)
391
+
392
+ while True:
393
+ pos = orig_line.find(search, start_from)
394
+ if pos == -1:
395
+ break
396
+
397
+ mods = extract_modifications(search, replace, pos)
398
+
399
+ if not mods:
400
+ start_from = pos + 1
401
+ continue
402
+
403
+ trimmed_mods = []
404
+ for mod in mods:
405
+ s, e, c = mod
406
+ trimmed = trim_modification(s, e, c)
407
+ if trimmed:
408
+ trimmed_mods.append(trimmed)
409
+
410
+ if trimmed_mods:
411
+ all_modifications.extend(trimmed_mods)
412
+ for s, e, _ in trimmed_mods:
413
+ processed_mod_ranges.append((s, e))
414
+
415
+ search_next_start[search] = pos + 1
416
+ break
417
+
418
+ if not all_modifications:
419
+ return ops
420
+
421
+ all_modifications.sort(key=lambda x: x[0])
422
+
423
+ merged_modifications = []
424
+ for start, end, content in all_modifications:
425
+ if merged_modifications:
426
+ last_start, last_end, last_content = merged_modifications[-1]
427
+ if start <= last_end:
428
+ new_end = max(last_end, end)
429
+ overlap_in_last = max(0, start - last_start)
430
+ new_content = last_content[:overlap_in_last] + content
431
+ merged_modifications[-1] = (last_start, new_end, new_content)
432
+ continue
433
+ merged_modifications.append((start, end, content))
434
+
435
+ if not merged_modifications:
436
+ return ops
437
+
438
+ result_line = orig_line
439
+ for start, end, new_content in reversed(merged_modifications):
440
+ result_line = result_line[:start] + new_content + result_line[end:]
441
+
442
+ if result_line == orig_line:
443
+ return ops
444
+
445
+ return [{
446
+ 'operation': 'replace_str',
447
+ 'line_number': line_num,
448
+ 'search_content': orig_line,
449
+ 'replace_content': result_line
450
+ }]
451
+
452
+
453
+ def merge_all_same_line_replace_ops(operations, original_lines):
454
+ """Filter ambiguous operations and force-merge same-line replace_str operations."""
455
+ replace_ops = [op for op in operations if op['operation'] == 'replace_str']
456
+ other_ops = [op for op in operations if op['operation'] != 'replace_str']
457
+
458
+ if not replace_ops:
459
+ return operations
460
+
461
+ # Filter: search_content must appear exactly once in the target line
462
+ filtered_ops = []
463
+ for op in replace_ops:
464
+ line_num = op['line_number']
465
+ if isinstance(line_num, int) and 1 <= line_num <= len(original_lines):
466
+ orig_line = original_lines[line_num - 1]
467
+ if orig_line.count(op['search_content']) == 1:
468
+ filtered_ops.append(op)
469
+ else:
470
+ filtered_ops.append(op)
471
+ replace_ops = filtered_ops
472
+
473
+ line_ops = defaultdict(list)
474
+ for op in replace_ops:
475
+ line_ops[op['line_number']].append(op)
476
+
477
+ merged_ops = []
478
+
479
+ for line_num in sorted(line_ops.keys()):
480
+ ops = line_ops[line_num]
481
+
482
+ if len(ops) == 1:
483
+ merged_ops.append(ops[0])
484
+ continue
485
+
486
+ if isinstance(line_num, int) and 1 <= line_num <= len(original_lines):
487
+ orig_line = original_lines[line_num - 1]
488
+ else:
489
+ merged_ops.extend(ops)
490
+ continue
491
+
492
+ merged = force_merge_all_ops(ops, orig_line, line_num)
493
+ merged_ops.extend(merged)
494
+
495
+ return merged_ops + other_ops
496
+
497
+
498
+ # ==================== Clean Function Generation & Execution ====================
499
+
500
+ def generate_clean_function_code(operations):
501
+ """Generate executable clean_data function code from operation list."""
502
+ code_lines = [
503
+ "import re",
504
+ "from typing import Dict",
505
+ "",
506
+ "def remove_lines(line_dict, start_line, end_line):",
507
+ " return {k: v for k, v in line_dict.items() if not (start_line <= k <= end_line)}",
508
+ "",
509
+ "def remove_all():",
510
+ " return ''",
511
+ "",
512
+ "def add_line(line_dict, base_pos, sub_index, content):",
513
+ " result = line_dict.copy()",
514
+ " position = base_pos + sub_index / 10000.0",
515
+ " result[position] = content",
516
+ " return result",
517
+ "",
518
+ "def replace_str(line_dict, line_number, old_content, new_content):",
519
+ " result = line_dict.copy()",
520
+ " if line_number in result:",
521
+ " line = result[line_number]",
522
+ " if old_content in line:",
523
+ " result[line_number] = line.replace(old_content, new_content, 1)",
524
+ " return result",
525
+ "",
526
+ "def keep_all(content):",
527
+ " return content",
528
+ "",
529
+ "def clean_data(content):",
530
+ " lines = content.splitlines(keepends=True)",
531
+ " line_dict = {i: line for i, line in enumerate(lines, start=1)}",
532
+ ""
533
+ ]
534
+
535
+ if not operations:
536
+ code_lines.append(" return keep_all(content)")
537
+ else:
538
+ if len(operations) == 1 and operations[0]['operation'] == 'keep_all':
539
+ code_lines.append(" return keep_all(content)")
540
+ elif len(operations) == 1 and operations[0]['operation'] == 'remove_all':
541
+ code_lines.append(" return remove_all()")
542
+ else:
543
+ for op in operations:
544
+ if op['operation'] == 'remove_lines':
545
+ code_lines.append(" line_dict = remove_lines(line_dict, {}, {})".format(
546
+ op['start_line'], op['end_line']))
547
+ elif op['operation'] == 'add_line':
548
+ code_lines.append(" line_dict = add_line(line_dict, {}, {}, {})".format(
549
+ op['base_position'], op['sub_index'], repr(op['content'])))
550
+ elif op['operation'] == 'replace_str':
551
+ code_lines.append(" line_dict = replace_str(line_dict, {}, {}, {})".format(
552
+ op['line_number'], repr(op['search_content']), repr(op['replace_content'])))
553
+
554
+ code_lines.append("")
555
+ code_lines.append(" sorted_keys = sorted(line_dict.keys())")
556
+ code_lines.append(" sorted_lines = []")
557
+ code_lines.append(" for _i, _k in enumerate(sorted_keys):")
558
+ code_lines.append(" _line = line_dict[_k]")
559
+ code_lines.append(" if isinstance(_k, float):")
560
+ code_lines.append(" if sorted_lines and sorted_lines[-1] and not sorted_lines[-1].endswith('\\n'):")
561
+ code_lines.append(" sorted_lines[-1] = sorted_lines[-1] + '\\n'")
562
+ code_lines.append(" if _i + 1 < len(sorted_keys) and _line and not _line.endswith('\\n'):")
563
+ code_lines.append(" _line = _line + '\\n'")
564
+ code_lines.append(" sorted_lines.append(_line)")
565
+ code_lines.append(" result = ''.join(sorted_lines)")
566
+ code_lines.append(" result = result.replace('\\r\\n', '\\n').replace('\\r', '\\n')")
567
+ code_lines.append(" result = re.sub(r'\\n\\n+', '\\n', result)")
568
+ code_lines.append(" result = result.strip('\\n')")
569
+ code_lines.append(" return result")
570
+
571
+ code_lines.append("")
572
+ return "\n".join(code_lines)
573
+
574
+
575
+ def execute_clean_function(clean_func_code, original_content):
576
+ """Execute the generated clean function in an isolated namespace."""
577
+ try:
578
+ namespace = {}
579
+ exec(clean_func_code, namespace)
580
+ if 'clean_data' in namespace:
581
+ return namespace['clean_data'](original_content)
582
+ except Exception:
583
+ pass
584
+ return None
585
+
586
+
587
+ # ==================== Row Processing ====================
588
+
589
+ def process_row(original, model_output):
590
+ """
591
+ Process a single row: parse model_output -> post-process -> execute cleaning.
592
+
593
+ Returns:
594
+ (original, cleaned, processed_functions)
595
+ """
596
+ if not isinstance(original, str):
597
+ original = ""
598
+
599
+ original = normalize_newlines(original)
600
+
601
+ if not original.strip():
602
+ return (original, original, "keep_all()")
603
+
604
+ mo_str = model_output if (model_output and isinstance(model_output, str)) else ""
605
+ raw_functions = parse_function_list(mo_str)
606
+
607
+ original_lines = original.splitlines(keepends=True)
608
+ functions = list(raw_functions)
609
+ if functions:
610
+ functions = merge_all_same_line_replace_ops(functions, original_lines)
611
+
612
+ if detect_repetitive_functions(raw_functions, original=original):
613
+ processed_str = functions_to_string(functions) + "\n# FILTERED: repetitive pattern detected"
614
+ return (original, original, processed_str)
615
+
616
+ if not functions or (len(functions) == 1 and functions[0]['operation'] == 'keep_all'):
617
+ return (original, original, "keep_all()")
618
+
619
+ if len(functions) == 1 and functions[0]['operation'] == 'remove_all':
620
+ return (original, "", "remove_all()")
621
+
622
+ processed_str = functions_to_string(functions)
623
+
624
+ clean_code = generate_clean_function_code(functions)
625
+ cleaned = execute_clean_function(clean_code, original)
626
+ if cleaned is None:
627
+ cleaned = original
628
+ processed_str += "\n# FAILED: execution error"
629
+
630
+ return (original, cleaned, processed_str)
631
+
632
+
633
+ # ==================== Worker Process ====================
634
+
635
+ def worker_process(worker_id, file_list, input_dir, output_dir, result_queue):
636
+ """Worker process: processes assigned parquet files."""
637
+ logger = setup_logger(worker_id)
638
+ logger.info("Started, assigned {} files".format(len(file_list)))
639
+
640
+ stats = {
641
+ 'total': 0,
642
+ 'keep_all': 0,
643
+ 'remove_all': 0,
644
+ 'modified': 0,
645
+ 'repetitive_filtered': 0,
646
+ 'failed': 0,
647
+ }
648
+
649
+ if not file_list:
650
+ result_queue.put(('done', worker_id, stats))
651
+ return
652
+
653
+ input_path = Path(input_dir)
654
+ output_path = Path(output_dir)
655
+
656
+ for file_idx, filename in enumerate(file_list):
657
+ file_start = time.time()
658
+ logger.info("[{}/{}] Processing: {}".format(file_idx + 1, len(file_list), filename))
659
+
660
+ try:
661
+ df = pd.read_parquet(input_path / filename)
662
+ except Exception as e:
663
+ logger.error("Failed to read file {}: {}".format(filename, e))
664
+ continue
665
+
666
+ if 'original' not in df.columns or 'model_output' not in df.columns:
667
+ logger.warning("File missing required columns, skipping: {}".format(filename))
668
+ continue
669
+
670
+ results = []
671
+ for _, row in df.iterrows():
672
+ orig = row.get('original', '')
673
+ mo = row.get('model_output', '')
674
+ result = process_row(orig, mo)
675
+ results.append(result)
676
+
677
+ stats['total'] += 1
678
+ orig_normalized, cleaned_val, pf_val = result
679
+ if '# FILTERED: repetitive' in pf_val:
680
+ stats['repetitive_filtered'] += 1
681
+ stats['keep_all'] += 1
682
+ elif pf_val == 'keep_all()':
683
+ stats['keep_all'] += 1
684
+ elif pf_val == 'remove_all()':
685
+ stats['remove_all'] += 1
686
+ elif '# FAILED' in pf_val:
687
+ stats['failed'] += 1
688
+ else:
689
+ cleaned_str = cleaned_val if isinstance(cleaned_val, str) else ""
690
+ if cleaned_str == orig_normalized:
691
+ stats['keep_all'] += 1
692
+ elif not cleaned_str.strip():
693
+ stats['remove_all'] += 1
694
+ else:
695
+ stats['modified'] += 1
696
+
697
+ out_df = pd.DataFrame(results, columns=[
698
+ 'original', 'cleaned', 'processed_functions'
699
+ ])
700
+ out_df.to_parquet(output_path / filename, index=False)
701
+
702
+ elapsed = time.time() - file_start
703
+ logger.info(" Done {}: {} rows, {:.1f}s".format(filename, len(results), elapsed))
704
+
705
+ logger.info(
706
+ "Worker {} complete | total={}, modified={}, keep_all={}, "
707
+ "remove_all={}, repetitive={}, failed={}".format(
708
+ worker_id, stats['total'], stats['modified'], stats['keep_all'],
709
+ stats['remove_all'], stats['repetitive_filtered'], stats['failed'])
710
+ )
711
+ result_queue.put(('done', worker_id, stats))
712
+
713
+
714
+ # ==================== Main ====================
715
+
716
+ def get_files_to_process(input_dir, output_dir):
717
+ """Get list of files to process, skipping already-completed ones."""
718
+ input_path = Path(input_dir)
719
+ output_path = Path(output_dir)
720
+ parquet_files = sorted(input_path.glob("*.parquet"))
721
+
722
+ files_to_process = []
723
+ skipped = 0
724
+ for pf in parquet_files:
725
+ if (output_path / pf.name).exists():
726
+ skipped += 1
727
+ continue
728
+ files_to_process.append(pf.name)
729
+ return files_to_process, skipped
730
+
731
+
732
+ def main():
733
+ parser = argparse.ArgumentParser(
734
+ description="UltraX post-processing and execution: parse, validate, and execute cleaning operations."
735
+ )
736
+ parser.add_argument("--input_dir", type=str, required=True,
737
+ help="Input directory containing inference output parquet files (columns: original, model_output)")
738
+ parser.add_argument("--output_dir", type=str, required=True,
739
+ help="Output directory for cleaned parquet files (3 columns: original, cleaned, processed_functions)")
740
+ parser.add_argument("--num_workers", type=int, default=128,
741
+ help="Number of parallel worker processes (default: 128)")
742
+ parser.add_argument("--similarity_ratio", type=float, default=0.85,
743
+ help="Similarity ratio threshold for duplicate detection (default: 0.85)")
744
+ parser.add_argument("--add_line_similar_threshold", type=int, default=3,
745
+ help="Threshold for similar add_line pattern detection (default: 3)")
746
+ args = parser.parse_args()
747
+
748
+ logger = setup_logger()
749
+
750
+ logger.info("Input directory: {}".format(args.input_dir))
751
+ logger.info("Output directory: {}".format(args.output_dir))
752
+ logger.info("Workers: {}".format(args.num_workers))
753
+ logger.info("Similarity ratio: {}".format(args.similarity_ratio))
754
+ logger.info("Add-line similar threshold: {}".format(args.add_line_similar_threshold))
755
+
756
+ if not Path(args.input_dir).exists():
757
+ logger.error("Input directory does not exist: {}".format(args.input_dir))
758
+ return
759
+
760
+ Path(args.output_dir).mkdir(parents=True, exist_ok=True)
761
+
762
+ logger.info("Scanning files...")
763
+ files_to_process, skipped = get_files_to_process(args.input_dir, args.output_dir)
764
+ logger.info("Total files: {}, skipped: {}, to process: {}".format(
765
+ len(files_to_process) + skipped, skipped, len(files_to_process)))
766
+
767
+ if not files_to_process:
768
+ logger.info("All files have been processed")
769
+ return
770
+
771
+ actual_workers = min(args.num_workers, len(files_to_process))
772
+ files_per_worker = [[] for _ in range(actual_workers)]
773
+ for i, filename in enumerate(files_to_process):
774
+ files_per_worker[i % actual_workers].append(filename)
775
+
776
+ logger.info("Using {} worker processes".format(actual_workers))
777
+ for wid in range(actual_workers):
778
+ logger.info(" Worker {}: {} files".format(wid, len(files_per_worker[wid])))
779
+
780
+ start_time = time.time()
781
+ result_queue = mp.Queue()
782
+ processes = []
783
+
784
+ for wid in range(actual_workers):
785
+ p = mp.Process(
786
+ target=worker_process,
787
+ args=(wid, files_per_worker[wid], args.input_dir, args.output_dir, result_queue)
788
+ )
789
+ p.start()
790
+ processes.append(p)
791
+
792
+ total_stats = defaultdict(int)
793
+ completed = 0
794
+ while completed < actual_workers:
795
+ result = result_queue.get()
796
+ if result[0] == 'done':
797
+ _, wid, sts = result
798
+ for key, val in sts.items():
799
+ total_stats[key] += val
800
+ completed += 1
801
+
802
+ for p in processes:
803
+ p.join()
804
+
805
+ elapsed = time.time() - start_time
806
+ logger.info("=" * 60)
807
+ logger.info("All processing complete")
808
+ logger.info("=" * 60)
809
+ logger.info("Total rows: {:,}".format(total_stats['total']))
810
+ logger.info("Modified: {:,}".format(total_stats['modified']))
811
+ logger.info("keep_all: {:,}".format(total_stats['keep_all']))
812
+ logger.info("remove_all: {:,}".format(total_stats['remove_all']))
813
+ logger.info("Repetitive filtered: {:,}".format(total_stats['repetitive_filtered']))
814
+ logger.info("Execution failed: {:,}".format(total_stats['failed']))
815
+ logger.info("Elapsed time: {:.1f}s ({:.1f}min)".format(elapsed, elapsed / 60))
816
+ logger.info("=" * 60)
817
+
818
+
819
+ if __name__ == "__main__":
820
+ mp.set_start_method('spawn', force=True)
821
+ main()
models/UltraX-No-Instruction/added_tokens.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|box_end|>": 151649,
9
+ "<|box_start|>": 151648,
10
+ "<|endoftext|>": 151643,
11
+ "<|file_sep|>": 151664,
12
+ "<|fim_middle|>": 151660,
13
+ "<|fim_pad|>": 151662,
14
+ "<|fim_prefix|>": 151659,
15
+ "<|fim_suffix|>": 151661,
16
+ "<|im_end|>": 151645,
17
+ "<|im_start|>": 151644,
18
+ "<|image_pad|>": 151655,
19
+ "<|object_ref_end|>": 151647,
20
+ "<|object_ref_start|>": 151646,
21
+ "<|quad_end|>": 151651,
22
+ "<|quad_start|>": 151650,
23
+ "<|repo_name|>": 151663,
24
+ "<|video_pad|>": 151656,
25
+ "<|vision_end|>": 151653,
26
+ "<|vision_pad|>": 151654,
27
+ "<|vision_start|>": 151652
28
+ }
models/UltraX-No-Instruction/args.json ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "output_dir": "/user/zhangyixuan/share_user_data/user/zhaoxinlong/2_new_exp/model/qwen3-0.6b-full-20k-2epoch-en_web_sampled/v1-20260415-145140",
3
+ "overwrite_output_dir": false,
4
+ "do_train": false,
5
+ "do_eval": false,
6
+ "do_predict": false,
7
+ "eval_strategy": "no",
8
+ "prediction_loss_only": false,
9
+ "per_device_train_batch_size": 24,
10
+ "per_device_eval_batch_size": 1,
11
+ "per_gpu_train_batch_size": null,
12
+ "per_gpu_eval_batch_size": null,
13
+ "gradient_accumulation_steps": 3,
14
+ "eval_accumulation_steps": null,
15
+ "eval_delay": 0,
16
+ "torch_empty_cache_steps": null,
17
+ "learning_rate": 3e-05,
18
+ "weight_decay": 0.1,
19
+ "adam_beta1": 0.9,
20
+ "adam_beta2": 0.95,
21
+ "adam_epsilon": 1e-08,
22
+ "max_grad_norm": 1.0,
23
+ "num_train_epochs": 3.0,
24
+ "max_steps": 5530,
25
+ "lr_scheduler_type": "cosine_with_min_lr",
26
+ "lr_scheduler_kwargs": "{\"min_lr\": 3e-6}",
27
+ "warmup_ratio": 0.03,
28
+ "warmup_steps": 0,
29
+ "log_level": "passive",
30
+ "log_level_replica": "warning",
31
+ "log_on_each_node": true,
32
+ "logging_dir": "/user/zhangyixuan/share_user_data/user/zhaoxinlong/2_new_exp/model/qwen3-0.6b-full-20k-2epoch-en_web_sampled/v1-20260415-145140/runs",
33
+ "logging_strategy": "steps",
34
+ "logging_first_step": true,
35
+ "logging_steps": 10,
36
+ "logging_nan_inf_filter": true,
37
+ "save_strategy": "steps",
38
+ "save_steps": 2765.0,
39
+ "save_total_limit": 10,
40
+ "save_safetensors": true,
41
+ "save_on_each_node": false,
42
+ "save_only_model": true,
43
+ "restore_callback_states_from_checkpoint": false,
44
+ "no_cuda": false,
45
+ "use_cpu": false,
46
+ "use_mps_device": false,
47
+ "seed": 42,
48
+ "data_seed": 42,
49
+ "jit_mode_eval": false,
50
+ "bf16": true,
51
+ "fp16": false,
52
+ "fp16_opt_level": "O1",
53
+ "half_precision_backend": "auto",
54
+ "bf16_full_eval": false,
55
+ "fp16_full_eval": false,
56
+ "tf32": null,
57
+ "local_rank": 0,
58
+ "ddp_backend": null,
59
+ "tpu_num_cores": null,
60
+ "tpu_metrics_debug": false,
61
+ "debug": null,
62
+ "dataloader_drop_last": false,
63
+ "eval_steps": 2765.0,
64
+ "dataloader_num_workers": 4,
65
+ "dataloader_prefetch_factor": null,
66
+ "past_index": -1,
67
+ "run_name": "/user/zhangyixuan/share_user_data/user/zhaoxinlong/2_new_exp/model/qwen3-0.6b-full-20k-2epoch-en_web_sampled/v1-20260415-145140",
68
+ "disable_tqdm": null,
69
+ "remove_unused_columns": true,
70
+ "label_names": null,
71
+ "load_best_model_at_end": false,
72
+ "metric_for_best_model": "loss",
73
+ "greater_is_better": false,
74
+ "ignore_data_skip": false,
75
+ "fsdp": null,
76
+ "fsdp_min_num_params": 0,
77
+ "fsdp_config": null,
78
+ "fsdp_transformer_layer_cls_to_wrap": null,
79
+ "accelerator_config": {
80
+ "dispatch_batches": false
81
+ },
82
+ "parallelism_config": null,
83
+ "deepspeed": {
84
+ "fp16": {
85
+ "enabled": "auto",
86
+ "loss_scale": 0,
87
+ "loss_scale_window": 1000,
88
+ "initial_scale_power": 16,
89
+ "hysteresis": 2,
90
+ "min_loss_scale": 1
91
+ },
92
+ "bf16": {
93
+ "enabled": "auto"
94
+ },
95
+ "zero_optimization": {
96
+ "stage": 3,
97
+ "offload_optimizer": {
98
+ "device": "none",
99
+ "pin_memory": true
100
+ },
101
+ "offload_param": {
102
+ "device": "none",
103
+ "pin_memory": true
104
+ },
105
+ "overlap_comm": false,
106
+ "contiguous_gradients": true,
107
+ "sub_group_size": 1000000000.0,
108
+ "reduce_bucket_size": "auto",
109
+ "zero_quantized_weights": false,
110
+ "zero_quantized_gradients": false,
111
+ "stage3_prefetch_bucket_size": "auto",
112
+ "stage3_param_persistence_threshold": "auto",
113
+ "stage3_max_live_parameters": 1000000000.0,
114
+ "stage3_max_reuse_distance": 1000000000.0,
115
+ "stage3_gather_16bit_weights_on_model_save": true
116
+ },
117
+ "gradient_accumulation_steps": "auto",
118
+ "gradient_clipping": "auto",
119
+ "steps_per_print": 2000,
120
+ "train_batch_size": "auto",
121
+ "train_micro_batch_size_per_gpu": "auto",
122
+ "wall_clock_breakdown": false
123
+ },
124
+ "label_smoothing_factor": 0.0,
125
+ "optim": "adamw_torch_fused",
126
+ "optim_args": null,
127
+ "adafactor": false,
128
+ "group_by_length": false,
129
+ "length_column_name": "length",
130
+ "report_to": [
131
+ "tensorboard"
132
+ ],
133
+ "project": "huggingface",
134
+ "trackio_space_id": "trackio",
135
+ "ddp_find_unused_parameters": null,
136
+ "ddp_bucket_cap_mb": null,
137
+ "ddp_broadcast_buffers": null,
138
+ "dataloader_pin_memory": true,
139
+ "dataloader_persistent_workers": false,
140
+ "skip_memory_metrics": true,
141
+ "use_legacy_prediction_loop": false,
142
+ "push_to_hub": false,
143
+ "resume_from_checkpoint": null,
144
+ "hub_model_id": null,
145
+ "hub_strategy": "every_save",
146
+ "hub_token": null,
147
+ "hub_private_repo": null,
148
+ "hub_always_push": false,
149
+ "hub_revision": null,
150
+ "gradient_checkpointing": true,
151
+ "gradient_checkpointing_kwargs": null,
152
+ "include_inputs_for_metrics": false,
153
+ "include_for_metrics": [],
154
+ "eval_do_concat_batches": true,
155
+ "fp16_backend": "auto",
156
+ "push_to_hub_model_id": null,
157
+ "push_to_hub_organization": null,
158
+ "push_to_hub_token": null,
159
+ "mp_parameters": "",
160
+ "auto_find_batch_size": false,
161
+ "full_determinism": false,
162
+ "torchdynamo": null,
163
+ "ray_scope": "last",
164
+ "ddp_timeout": 18000000,
165
+ "torch_compile": false,
166
+ "torch_compile_backend": null,
167
+ "torch_compile_mode": null,
168
+ "include_tokens_per_second": false,
169
+ "include_num_input_tokens_seen": false,
170
+ "neftune_noise_alpha": null,
171
+ "optim_target_modules": null,
172
+ "batch_eval_metrics": false,
173
+ "eval_on_start": false,
174
+ "use_liger_kernel": true,
175
+ "liger_kernel_config": null,
176
+ "eval_use_gather_object": false,
177
+ "average_tokens_across_devices": true,
178
+ "sortish_sampler": false,
179
+ "predict_with_generate": false,
180
+ "generation_max_length": null,
181
+ "generation_num_beams": null,
182
+ "generation_config": null,
183
+ "tuner_backend": "peft",
184
+ "vit_gradient_checkpointing": null,
185
+ "router_aux_loss_coef": 0.0,
186
+ "enable_dft_loss": false,
187
+ "enable_channel_loss": false,
188
+ "check_model": true,
189
+ "acc_strategy": "token",
190
+ "train_dataloader_shuffle": true,
191
+ "max_epochs": null,
192
+ "aligner_lr": null,
193
+ "vit_lr": null,
194
+ "use_logits_to_keep": null,
195
+ "ds3_gather_for_generation": true,
196
+ "resume_only_model": false,
197
+ "optimizer": null,
198
+ "loss_type": null,
199
+ "metric": null,
200
+ "eval_use_evalscope": false,
201
+ "eval_dataset": [],
202
+ "eval_dataset_args": null,
203
+ "eval_limit": null,
204
+ "eval_generation_config": null,
205
+ "extra_eval_args": null,
206
+ "use_flash_ckpt": false,
207
+ "use_ray": false,
208
+ "ray_exp_name": null,
209
+ "device_groups": null,
210
+ "model": "Qwen/Qwen3-0.6B",
211
+ "model_type": "qwen3",
212
+ "model_revision": null,
213
+ "task_type": "causal_lm",
214
+ "torch_dtype": "bfloat16",
215
+ "attn_impl": "flash_attn",
216
+ "new_special_tokens": [],
217
+ "num_labels": null,
218
+ "problem_type": null,
219
+ "rope_scaling": null,
220
+ "device_map": null,
221
+ "max_memory": {},
222
+ "max_model_len": null,
223
+ "local_repo_path": null,
224
+ "init_strategy": null,
225
+ "template": "qwen3",
226
+ "system": null,
227
+ "max_length": 20480,
228
+ "truncation_strategy": "delete",
229
+ "max_pixels": null,
230
+ "agent_template": null,
231
+ "norm_bbox": null,
232
+ "use_chat_template": true,
233
+ "padding_side": "right",
234
+ "padding_free": false,
235
+ "loss_scale": "ignore_empty_think",
236
+ "sequence_parallel_size": 1,
237
+ "template_backend": "swift",
238
+ "response_prefix": null,
239
+ "enable_thinking": null,
240
+ "add_non_thinking_prefix": true,
241
+ "dataset": [
242
+ "/user/zhangyixuan/share_user_data/user/zhaoxinlong/2_new_exp/train_data/train_sampled"
243
+ ],
244
+ "val_dataset": [],
245
+ "cached_dataset": [],
246
+ "cached_val_dataset": [],
247
+ "split_dataset_ratio": 0.0,
248
+ "dataset_num_proc": 4,
249
+ "load_from_cache_file": false,
250
+ "dataset_shuffle": true,
251
+ "val_dataset_shuffle": false,
252
+ "streaming": true,
253
+ "interleave_prob": null,
254
+ "stopping_strategy": "first_exhausted",
255
+ "shuffle_buffer_size": 1000,
256
+ "download_mode": "reuse_dataset_if_exists",
257
+ "columns": {},
258
+ "strict": false,
259
+ "model_name": null,
260
+ "model_author": null,
261
+ "custom_dataset_info": [],
262
+ "quant_method": null,
263
+ "quant_bits": null,
264
+ "hqq_axis": null,
265
+ "bnb_4bit_compute_dtype": "bfloat16",
266
+ "bnb_4bit_quant_type": "nf4",
267
+ "bnb_4bit_use_double_quant": true,
268
+ "bnb_4bit_quant_storage": null,
269
+ "max_new_tokens": 64,
270
+ "temperature": 0.0,
271
+ "top_k": null,
272
+ "top_p": null,
273
+ "repetition_penalty": null,
274
+ "num_beams": 1,
275
+ "stream": false,
276
+ "stop_words": [],
277
+ "logprobs": false,
278
+ "top_logprobs": null,
279
+ "ckpt_dir": null,
280
+ "lora_modules": [],
281
+ "train_type": "full",
282
+ "adapters": [],
283
+ "external_plugins": [],
284
+ "model_kwargs": {},
285
+ "load_args": false,
286
+ "load_data_args": false,
287
+ "packing": false,
288
+ "packing_length": null,
289
+ "packing_num_proc": 1,
290
+ "lazy_tokenize": false,
291
+ "custom_register_path": [],
292
+ "use_hf": false,
293
+ "ignore_args_error": false,
294
+ "use_swift_lora": false,
295
+ "freeze_parameters": [],
296
+ "freeze_parameters_regex": null,
297
+ "freeze_parameters_ratio": 0.0,
298
+ "trainable_parameters": [],
299
+ "trainable_parameters_regex": null,
300
+ "freeze_llm": false,
301
+ "freeze_vit": true,
302
+ "freeze_aligner": true,
303
+ "target_modules": [
304
+ "all-linear"
305
+ ],
306
+ "target_regex": null,
307
+ "target_parameters": null,
308
+ "modules_to_save": [],
309
+ "lora_rank": 8,
310
+ "lora_alpha": 32,
311
+ "lora_dropout": 0.05,
312
+ "lora_bias": "none",
313
+ "lora_dtype": null,
314
+ "lorap_lr_ratio": null,
315
+ "use_rslora": false,
316
+ "use_dora": false,
317
+ "lora_ga_batch_size": 2,
318
+ "lora_ga_iters": 2,
319
+ "lora_ga_max_length": 1024,
320
+ "lora_ga_direction": "ArB2r",
321
+ "lora_ga_scale": "stable",
322
+ "lora_ga_stable_gamma": 16,
323
+ "init_weights": true,
324
+ "fourier_n_frequency": 2000,
325
+ "fourier_scaling": 300.0,
326
+ "boft_block_size": 4,
327
+ "boft_block_num": 0,
328
+ "boft_n_butterfly_factor": 1,
329
+ "boft_dropout": 0.0,
330
+ "vera_rank": 256,
331
+ "vera_projection_prng_key": 0,
332
+ "vera_dropout": 0.0,
333
+ "vera_d_initial": 0.1,
334
+ "adapter_act": "gelu",
335
+ "adapter_length": 128,
336
+ "use_galore": false,
337
+ "galore_target_modules": null,
338
+ "galore_rank": 128,
339
+ "galore_update_proj_gap": 50,
340
+ "galore_scale": 1.0,
341
+ "galore_proj_type": "std",
342
+ "galore_optim_per_parameter": false,
343
+ "galore_with_embedding": false,
344
+ "galore_quantization": false,
345
+ "galore_proj_quant": false,
346
+ "galore_proj_bits": 4,
347
+ "galore_proj_group_size": 256,
348
+ "galore_cos_threshold": 0.4,
349
+ "galore_gamma_proj": 2,
350
+ "galore_queue_size": 5,
351
+ "adalora_target_r": 8,
352
+ "adalora_init_r": 12,
353
+ "adalora_tinit": 0,
354
+ "adalora_tfinal": 0,
355
+ "adalora_deltaT": 1,
356
+ "adalora_beta1": 0.85,
357
+ "adalora_beta2": 0.85,
358
+ "adalora_orth_reg_weight": 0.5,
359
+ "llamapro_num_new_blocks": 4,
360
+ "llamapro_num_groups": null,
361
+ "lisa_activated_layers": 0,
362
+ "lisa_step_interval": 20,
363
+ "reft_layer_key": null,
364
+ "reft_layers": null,
365
+ "reft_rank": 4,
366
+ "reft_intervention_type": "LoreftIntervention",
367
+ "reft_args": null,
368
+ "swanlab_token": null,
369
+ "swanlab_project": null,
370
+ "swanlab_workspace": null,
371
+ "swanlab_exp_name": null,
372
+ "swanlab_lark_webhook_url": null,
373
+ "swanlab_lark_secret": null,
374
+ "swanlab_mode": "cloud",
375
+ "add_version": true,
376
+ "create_checkpoint_symlink": false,
377
+ "zero_hpz_partition_size": null,
378
+ "deepspeed_autotp_size": null,
379
+ "early_stop_interval": null,
380
+ "rank": 0,
381
+ "global_world_size": 8,
382
+ "local_world_size": 8,
383
+ "model_suffix": "Qwen3-0.6B",
384
+ "model_info": "ModelInfo(model_type='qwen3', model_dir='/root/.cache/modelscope/hub/models/Qwen/Qwen3-0___6B', torch_dtype=torch.bfloat16, max_model_len=40960, quant_method=None, quant_bits=None, rope_scaling=None, is_moe_model=False, is_multimodal=False, config=None, task_type='causal_lm', num_labels=None)",
385
+ "model_meta": "ModelMeta(model_type='qwen3', model_groups=[ModelGroup(models=[Model(ms_model_id='Qwen/Qwen3-0.6B-Base', hf_model_id='Qwen/Qwen3-0.6B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-1.7B-Base', hf_model_id='Qwen/Qwen3-1.7B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-4B-Base', hf_model_id='Qwen/Qwen3-4B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-8B-Base', hf_model_id='Qwen/Qwen3-8B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-14B-Base', hf_model_id='Qwen/Qwen3-14B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-0.6B', hf_model_id='Qwen/Qwen3-0.6B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-1.7B', hf_model_id='Qwen/Qwen3-1.7B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-4B', hf_model_id='Qwen/Qwen3-4B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-8B', hf_model_id='Qwen/Qwen3-8B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-14B', hf_model_id='Qwen/Qwen3-14B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-32B', hf_model_id='Qwen/Qwen3-32B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-0.6B-FP8', hf_model_id='Qwen/Qwen3-0.6B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-1.7B-FP8', hf_model_id='Qwen/Qwen3-1.7B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-4B-FP8', hf_model_id='Qwen/Qwen3-4B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-8B-FP8', hf_model_id='Qwen/Qwen3-8B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-14B-FP8', hf_model_id='Qwen/Qwen3-14B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-32B-FP8', hf_model_id='Qwen/Qwen3-32B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-4B-AWQ', hf_model_id='Qwen/Qwen3-4B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-8B-AWQ', hf_model_id='Qwen/Qwen3-8B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-14B-AWQ', hf_model_id='Qwen/Qwen3-14B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-32B-AWQ', hf_model_id='Qwen/Qwen3-32B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='swift/Qwen3-32B-AWQ', hf_model_id=None, model_path=None, ms_revision=None, hf_revision=None)], ignore_patterns=None, requires=None, tags=[])], template='qwen3', get_function=<function get_model_tokenizer_with_flash_attn at 0x7f447e028670>, model_arch=ModelKeys(arch_name='llama', embedding='model.embed_tokens', module_list='model.layers', lm_head='lm_head', q_proj='model.layers.{}.self_attn.q_proj', k_proj='model.layers.{}.self_attn.k_proj', v_proj='model.layers.{}.self_attn.v_proj', o_proj='model.layers.{}.self_attn.o_proj', attention='model.layers.{}.self_attn', mlp='model.layers.{}.mlp', down_proj='model.layers.{}.mlp.down_proj', qkv_proj=None, qk_proj=None, qa_proj=None, qb_proj=None, kv_proj=None, kva_proj=None, kvb_proj=None), architectures=['Qwen3ForCausalLM'], additional_saved_files=[], torch_dtype=None, is_multimodal=False, is_reward=False, is_reranker=False, task_type=None, ignore_patterns=None, requires=['transformers>=4.51'], tags=[])",
386
+ "model_dir": "/root/.cache/modelscope/hub/models/Qwen/Qwen3-0___6B",
387
+ "_val_dataset_exists": [],
388
+ "hub": "<class 'swift.hub.hub.MSHub'>",
389
+ "evaluation_strategy": "steps",
390
+ "training_args": "Seq2SeqTrainingArguments(output_dir='/user/zhangyixuan/share_user_data/user/zhaoxinlong/2_new_exp/model/qwen3-0.6b-full-20k-2epoch-en_web_sampled/v1-20260415-145140', overwrite_output_dir=False, do_train=False, do_eval=False, do_predict=False, eval_strategy=<IntervalStrategy.NO: 'no'>, prediction_loss_only=False, per_device_train_batch_size=24, per_device_eval_batch_size=1, per_gpu_train_batch_size=None, per_gpu_eval_batch_size=None, gradient_accumulation_steps=3, eval_accumulation_steps=None, eval_delay=0, torch_empty_cache_steps=None, learning_rate=3e-05, weight_decay=0.1, adam_beta1=0.9, adam_beta2=0.95, adam_epsilon=1e-08, max_grad_norm=1.0, num_train_epochs=3.0, max_steps=5530, lr_scheduler_type=<SchedulerType.COSINE_WITH_MIN_LR: 'cosine_with_min_lr'>, lr_scheduler_kwargs={'min_lr': 3e-06}, warmup_ratio=0.03, warmup_steps=0, log_level='passive', log_level_replica='warning', log_on_each_node=True, logging_dir='/user/zhangyixuan/share_user_data/user/zhaoxinlong/2_new_exp/model/qwen3-0.6b-full-20k-2epoch-en_web_sampled/v1-20260415-145140/runs', logging_strategy=<IntervalStrategy.STEPS: 'steps'>, logging_first_step=True, logging_steps=10, logging_nan_inf_filter=True, save_strategy=<SaveStrategy.STEPS: 'steps'>, save_steps=2765, save_total_limit=10, save_safetensors=True, save_on_each_node=False, save_only_model=True, restore_callback_states_from_checkpoint=False, no_cuda=False, use_cpu=False, use_mps_device=False, seed=42, data_seed=42, jit_mode_eval=False, bf16=True, fp16=False, fp16_opt_level='O1', half_precision_backend='auto', bf16_full_eval=False, fp16_full_eval=False, tf32=None, local_rank=0, ddp_backend=None, tpu_num_cores=None, tpu_metrics_debug=False, debug=[], dataloader_drop_last=False, eval_steps=2765.0, dataloader_num_workers=4, dataloader_prefetch_factor=10, past_index=-1, run_name='/user/zhangyixuan/share_user_data/user/zhaoxinlong/2_new_exp/model/qwen3-0.6b-full-20k-2epoch-en_web_sampled/v1-20260415-145140', disable_tqdm=False, remove_unused_columns=False, label_names=None, load_best_model_at_end=False, metric_for_best_model='loss', greater_is_better=False, ignore_data_skip=False, fsdp=[], fsdp_min_num_params=0, fsdp_config={'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}, fsdp_transformer_layer_cls_to_wrap=None, accelerator_config=AcceleratorConfig(split_batches=False, dispatch_batches=False, even_batches=True, use_seedable_sampler=True, non_blocking=False, gradient_accumulation_kwargs=None, use_configured_state=False), parallelism_config=None, deepspeed={'fp16': {'enabled': 'auto', 'loss_scale': 0, 'loss_scale_window': 1000, 'initial_scale_power': 16, 'hysteresis': 2, 'min_loss_scale': 1}, 'bf16': {'enabled': 'auto'}, 'zero_optimization': {'stage': 3, 'offload_optimizer': {'device': 'none', 'pin_memory': True}, 'offload_param': {'device': 'none', 'pin_memory': True}, 'overlap_comm': False, 'contiguous_gradients': True, 'sub_group_size': 1000000000.0, 'reduce_bucket_size': 'auto', 'zero_quantized_weights': False, 'zero_quantized_gradients': False, 'stage3_prefetch_bucket_size': 'auto', 'stage3_param_persistence_threshold': 'auto', 'stage3_max_live_parameters': 1000000000.0, 'stage3_max_reuse_distance': 1000000000.0, 'stage3_gather_16bit_weights_on_model_save': True}, 'gradient_accumulation_steps': 'auto', 'gradient_clipping': 'auto', 'steps_per_print': 2000, 'train_batch_size': 'auto', 'train_micro_batch_size_per_gpu': 'auto', 'wall_clock_breakdown': False}, label_smoothing_factor=0.0, optim=<OptimizerNames.ADAMW_TORCH_FUSED: 'adamw_torch_fused'>, optim_args=None, adafactor=False, group_by_length=False, length_column_name='length', report_to=['tensorboard'], project='huggingface', trackio_space_id='trackio', ddp_find_unused_parameters=None, ddp_bucket_cap_mb=None, ddp_broadcast_buffers=None, dataloader_pin_memory=True, dataloader_persistent_workers=False, skip_memory_metrics=True, use_legacy_prediction_loop=False, push_to_hub=False, resume_from_checkpoint=None, hub_model_id=None, hub_strategy=<HubStrategy.EVERY_SAVE: 'every_save'>, hub_token=None, hub_private_repo=None, hub_always_push=False, hub_revision=None, gradient_checkpointing=True, gradient_checkpointing_kwargs=None, include_inputs_for_metrics=False, include_for_metrics=[], eval_do_concat_batches=True, fp16_backend='auto', push_to_hub_model_id=None, push_to_hub_organization=None, push_to_hub_token=None, mp_parameters='', auto_find_batch_size=False, full_determinism=False, torchdynamo=None, ray_scope='last', ddp_timeout=18000000, torch_compile=False, torch_compile_backend=None, torch_compile_mode=None, include_tokens_per_second=None, include_num_input_tokens_seen=None, neftune_noise_alpha=None, optim_target_modules=None, batch_eval_metrics=False, eval_on_start=False, use_liger_kernel=True, liger_kernel_config=None, eval_use_gather_object=False, average_tokens_across_devices=None, sortish_sampler=False, predict_with_generate=False, generation_max_length=None, generation_num_beams=None, generation_config=None, tuner_backend='peft', vit_gradient_checkpointing=True, router_aux_loss_coef=0.0, enable_dft_loss=False, enable_channel_loss=False, check_model=True, acc_strategy='token', train_dataloader_shuffle=True, max_epochs=None, aligner_lr=None, vit_lr=None, use_logits_to_keep=None, ds3_gather_for_generation=True, resume_only_model=False, optimizer=None, loss_type=None, metric=None, eval_use_evalscope=False, eval_dataset=[], eval_dataset_args=None, eval_limit=None, eval_generation_config=None, extra_eval_args=None, use_flash_ckpt=False, sft_alpha=0, chord_sft_dataset=[], chord_sft_per_device_train_batch_size=None, chord_enable_phi_function=False, chord_mu_warmup_steps=None, chord_mu_decay_steps=None, chord_mu_peak=None, chord_mu_valley=None, train_type='full', local_repo_path=None, galore_config=None, task_type='causal_lm', problem_type=None)"
391
+ }
models/UltraX-No-Instruction/chat_template.jinja ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# 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>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\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" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if message.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {%- set reasoning_content = '' %}
35
+ {%- if message.reasoning_content is string %}
36
+ {%- set reasoning_content = message.reasoning_content %}
37
+ {%- else %}
38
+ {%- if '</think>' in content %}
39
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
40
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
41
+ {%- endif %}
42
+ {%- endif %}
43
+ {%- if loop.index0 > ns.last_query_index %}
44
+ {%- if loop.last or (not loop.last and reasoning_content) %}
45
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
46
+ {%- else %}
47
+ {{- '<|im_start|>' + message.role + '\n' + content }}
48
+ {%- endif %}
49
+ {%- else %}
50
+ {{- '<|im_start|>' + message.role + '\n' + content }}
51
+ {%- endif %}
52
+ {%- if message.tool_calls %}
53
+ {%- for tool_call in message.tool_calls %}
54
+ {%- if (loop.first and content) or (not loop.first) %}
55
+ {{- '\n' }}
56
+ {%- endif %}
57
+ {%- if tool_call.function %}
58
+ {%- set tool_call = tool_call.function %}
59
+ {%- endif %}
60
+ {{- '<tool_call>\n{"name": "' }}
61
+ {{- tool_call.name }}
62
+ {{- '", "arguments": ' }}
63
+ {%- if tool_call.arguments is string %}
64
+ {{- tool_call.arguments }}
65
+ {%- else %}
66
+ {{- tool_call.arguments | tojson }}
67
+ {%- endif %}
68
+ {{- '}\n</tool_call>' }}
69
+ {%- endfor %}
70
+ {%- endif %}
71
+ {{- '<|im_end|>\n' }}
72
+ {%- elif message.role == "tool" %}
73
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
74
+ {{- '<|im_start|>user' }}
75
+ {%- endif %}
76
+ {{- '\n<tool_response>\n' }}
77
+ {{- content }}
78
+ {{- '\n</tool_response>' }}
79
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
80
+ {{- '<|im_end|>\n' }}
81
+ {%- endif %}
82
+ {%- endif %}
83
+ {%- endfor %}
84
+ {%- if add_generation_prompt %}
85
+ {{- '<|im_start|>assistant\n' }}
86
+ {%- if enable_thinking is defined and enable_thinking is false %}
87
+ {{- '<think>\n\n</think>\n\n' }}
88
+ {%- endif %}
89
+ {%- endif %}
models/UltraX-No-Instruction/config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "dtype": "bfloat16",
8
+ "eos_token_id": 151645,
9
+ "head_dim": 128,
10
+ "hidden_act": "silu",
11
+ "hidden_size": 1024,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 3072,
14
+ "layer_types": [
15
+ "full_attention",
16
+ "full_attention",
17
+ "full_attention",
18
+ "full_attention",
19
+ "full_attention",
20
+ "full_attention",
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "full_attention",
27
+ "full_attention",
28
+ "full_attention",
29
+ "full_attention",
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention",
33
+ "full_attention",
34
+ "full_attention",
35
+ "full_attention",
36
+ "full_attention",
37
+ "full_attention",
38
+ "full_attention",
39
+ "full_attention",
40
+ "full_attention",
41
+ "full_attention",
42
+ "full_attention"
43
+ ],
44
+ "max_position_embeddings": 40960,
45
+ "max_window_layers": 28,
46
+ "model_type": "qwen3",
47
+ "num_attention_heads": 16,
48
+ "num_hidden_layers": 28,
49
+ "num_key_value_heads": 8,
50
+ "pad_token_id": 151643,
51
+ "rms_norm_eps": 1e-06,
52
+ "rope_scaling": null,
53
+ "rope_theta": 1000000,
54
+ "sliding_window": null,
55
+ "tie_word_embeddings": true,
56
+ "transformers_version": "4.57.3",
57
+ "use_cache": false,
58
+ "use_sliding_window": false,
59
+ "vocab_size": 151936
60
+ }
models/UltraX-No-Instruction/generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "temperature": 0.6,
10
+ "top_k": 20,
11
+ "top_p": 0.95,
12
+ "transformers_version": "4.57.3"
13
+ }
models/UltraX-No-Instruction/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
models/UltraX-No-Instruction/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6659476674fe57befdc739da02e87eebaeeb8b7771c32955e1df897632186363
3
+ size 1192135096
models/UltraX-No-Instruction/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": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
models/UltraX-No-Instruction/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4
3
+ size 11422654
models/UltraX-No-Instruction/tokenizer_config.json ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ }
213
+ },
214
+ "additional_special_tokens": [
215
+ "<|im_start|>",
216
+ "<|im_end|>",
217
+ "<|object_ref_start|>",
218
+ "<|object_ref_end|>",
219
+ "<|box_start|>",
220
+ "<|box_end|>",
221
+ "<|quad_start|>",
222
+ "<|quad_end|>",
223
+ "<|vision_start|>",
224
+ "<|vision_end|>",
225
+ "<|vision_pad|>",
226
+ "<|image_pad|>",
227
+ "<|video_pad|>"
228
+ ],
229
+ "bos_token": null,
230
+ "clean_up_tokenization_spaces": false,
231
+ "eos_token": "<|im_end|>",
232
+ "errors": "replace",
233
+ "extra_special_tokens": {},
234
+ "model_max_length": 131072,
235
+ "pad_token": "<|endoftext|>",
236
+ "split_special_tokens": false,
237
+ "tokenizer_class": "Qwen2Tokenizer",
238
+ "unk_token": null
239
+ }
models/UltraX-No-Instruction/trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
models/UltraX-No-Instruction/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04cf2f27c2741e1e06fbd443035f69e6f550e1ba1d35ac83af7c8bd1df836777
3
+ size 9617
models/UltraX-No-Instruction/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
models/UltraX-Preservation-Weighted/added_tokens.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|box_end|>": 151649,
9
+ "<|box_start|>": 151648,
10
+ "<|endoftext|>": 151643,
11
+ "<|file_sep|>": 151664,
12
+ "<|fim_middle|>": 151660,
13
+ "<|fim_pad|>": 151662,
14
+ "<|fim_prefix|>": 151659,
15
+ "<|fim_suffix|>": 151661,
16
+ "<|im_end|>": 151645,
17
+ "<|im_start|>": 151644,
18
+ "<|image_pad|>": 151655,
19
+ "<|object_ref_end|>": 151647,
20
+ "<|object_ref_start|>": 151646,
21
+ "<|quad_end|>": 151651,
22
+ "<|quad_start|>": 151650,
23
+ "<|repo_name|>": 151663,
24
+ "<|video_pad|>": 151656,
25
+ "<|vision_end|>": 151653,
26
+ "<|vision_pad|>": 151654,
27
+ "<|vision_start|>": 151652
28
+ }
models/UltraX-Preservation-Weighted/args.json ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "output_dir": "/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/model/qwen3-0.6b-full-20k-2epoch-en_web_with_instruction_high/v1-20260429-105742",
3
+ "overwrite_output_dir": false,
4
+ "do_train": false,
5
+ "do_eval": false,
6
+ "do_predict": false,
7
+ "eval_strategy": "no",
8
+ "prediction_loss_only": false,
9
+ "per_device_train_batch_size": 28,
10
+ "per_device_eval_batch_size": 1,
11
+ "per_gpu_train_batch_size": null,
12
+ "per_gpu_eval_batch_size": null,
13
+ "gradient_accumulation_steps": 3,
14
+ "eval_accumulation_steps": null,
15
+ "eval_delay": 0,
16
+ "torch_empty_cache_steps": null,
17
+ "learning_rate": 3e-05,
18
+ "weight_decay": 0.1,
19
+ "adam_beta1": 0.9,
20
+ "adam_beta2": 0.95,
21
+ "adam_epsilon": 1e-08,
22
+ "max_grad_norm": 1.0,
23
+ "num_train_epochs": 3.0,
24
+ "max_steps": 8960,
25
+ "lr_scheduler_type": "cosine_with_min_lr",
26
+ "lr_scheduler_kwargs": "{\"min_lr\": 3e-6}",
27
+ "warmup_ratio": 0.03,
28
+ "warmup_steps": 0,
29
+ "log_level": "passive",
30
+ "log_level_replica": "warning",
31
+ "log_on_each_node": true,
32
+ "logging_dir": "/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/model/qwen3-0.6b-full-20k-2epoch-en_web_with_instruction_high/v1-20260429-105742/runs",
33
+ "logging_strategy": "steps",
34
+ "logging_first_step": true,
35
+ "logging_steps": 10,
36
+ "logging_nan_inf_filter": true,
37
+ "save_strategy": "steps",
38
+ "save_steps": 4480.0,
39
+ "save_total_limit": 3,
40
+ "save_safetensors": true,
41
+ "save_on_each_node": false,
42
+ "save_only_model": true,
43
+ "restore_callback_states_from_checkpoint": false,
44
+ "no_cuda": false,
45
+ "use_cpu": false,
46
+ "use_mps_device": false,
47
+ "seed": 42,
48
+ "data_seed": 42,
49
+ "jit_mode_eval": false,
50
+ "bf16": true,
51
+ "fp16": false,
52
+ "fp16_opt_level": "O1",
53
+ "half_precision_backend": "auto",
54
+ "bf16_full_eval": false,
55
+ "fp16_full_eval": false,
56
+ "tf32": null,
57
+ "local_rank": 0,
58
+ "ddp_backend": null,
59
+ "tpu_num_cores": null,
60
+ "tpu_metrics_debug": false,
61
+ "debug": null,
62
+ "dataloader_drop_last": false,
63
+ "eval_steps": 4480.0,
64
+ "dataloader_num_workers": 8,
65
+ "dataloader_prefetch_factor": null,
66
+ "past_index": -1,
67
+ "run_name": "/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/model/qwen3-0.6b-full-20k-2epoch-en_web_with_instruction_high/v1-20260429-105742",
68
+ "disable_tqdm": null,
69
+ "remove_unused_columns": true,
70
+ "label_names": null,
71
+ "load_best_model_at_end": false,
72
+ "metric_for_best_model": "loss",
73
+ "greater_is_better": false,
74
+ "ignore_data_skip": false,
75
+ "fsdp": null,
76
+ "fsdp_min_num_params": 0,
77
+ "fsdp_config": null,
78
+ "fsdp_transformer_layer_cls_to_wrap": null,
79
+ "accelerator_config": {
80
+ "dispatch_batches": false
81
+ },
82
+ "parallelism_config": null,
83
+ "deepspeed": {
84
+ "fp16": {
85
+ "enabled": "auto",
86
+ "loss_scale": 0,
87
+ "loss_scale_window": 1000,
88
+ "initial_scale_power": 16,
89
+ "hysteresis": 2,
90
+ "min_loss_scale": 1
91
+ },
92
+ "bf16": {
93
+ "enabled": "auto"
94
+ },
95
+ "zero_optimization": {
96
+ "stage": 3,
97
+ "offload_optimizer": {
98
+ "device": "none",
99
+ "pin_memory": true
100
+ },
101
+ "offload_param": {
102
+ "device": "none",
103
+ "pin_memory": true
104
+ },
105
+ "overlap_comm": false,
106
+ "contiguous_gradients": true,
107
+ "sub_group_size": 1000000000.0,
108
+ "reduce_bucket_size": "auto",
109
+ "zero_quantized_weights": false,
110
+ "zero_quantized_gradients": false,
111
+ "stage3_prefetch_bucket_size": "auto",
112
+ "stage3_param_persistence_threshold": "auto",
113
+ "stage3_max_live_parameters": 1000000000.0,
114
+ "stage3_max_reuse_distance": 1000000000.0,
115
+ "stage3_gather_16bit_weights_on_model_save": true
116
+ },
117
+ "gradient_accumulation_steps": "auto",
118
+ "gradient_clipping": "auto",
119
+ "steps_per_print": 2000,
120
+ "train_batch_size": "auto",
121
+ "train_micro_batch_size_per_gpu": "auto",
122
+ "wall_clock_breakdown": false
123
+ },
124
+ "label_smoothing_factor": 0.0,
125
+ "optim": "adamw_torch_fused",
126
+ "optim_args": null,
127
+ "adafactor": false,
128
+ "group_by_length": false,
129
+ "length_column_name": "length",
130
+ "report_to": [
131
+ "tensorboard"
132
+ ],
133
+ "project": "huggingface",
134
+ "trackio_space_id": "trackio",
135
+ "ddp_find_unused_parameters": null,
136
+ "ddp_bucket_cap_mb": null,
137
+ "ddp_broadcast_buffers": null,
138
+ "dataloader_pin_memory": true,
139
+ "dataloader_persistent_workers": false,
140
+ "skip_memory_metrics": true,
141
+ "use_legacy_prediction_loop": false,
142
+ "push_to_hub": false,
143
+ "resume_from_checkpoint": null,
144
+ "hub_model_id": null,
145
+ "hub_strategy": "every_save",
146
+ "hub_token": null,
147
+ "hub_private_repo": null,
148
+ "hub_always_push": false,
149
+ "hub_revision": null,
150
+ "gradient_checkpointing": true,
151
+ "gradient_checkpointing_kwargs": null,
152
+ "include_inputs_for_metrics": false,
153
+ "include_for_metrics": [],
154
+ "eval_do_concat_batches": true,
155
+ "fp16_backend": "auto",
156
+ "push_to_hub_model_id": null,
157
+ "push_to_hub_organization": null,
158
+ "push_to_hub_token": null,
159
+ "mp_parameters": "",
160
+ "auto_find_batch_size": false,
161
+ "full_determinism": false,
162
+ "torchdynamo": null,
163
+ "ray_scope": "last",
164
+ "ddp_timeout": 18000000,
165
+ "torch_compile": false,
166
+ "torch_compile_backend": null,
167
+ "torch_compile_mode": null,
168
+ "include_tokens_per_second": false,
169
+ "include_num_input_tokens_seen": false,
170
+ "neftune_noise_alpha": null,
171
+ "optim_target_modules": null,
172
+ "batch_eval_metrics": false,
173
+ "eval_on_start": false,
174
+ "use_liger_kernel": true,
175
+ "liger_kernel_config": null,
176
+ "eval_use_gather_object": false,
177
+ "average_tokens_across_devices": true,
178
+ "sortish_sampler": false,
179
+ "predict_with_generate": false,
180
+ "generation_max_length": null,
181
+ "generation_num_beams": null,
182
+ "generation_config": null,
183
+ "tuner_backend": "peft",
184
+ "vit_gradient_checkpointing": null,
185
+ "router_aux_loss_coef": 0.0,
186
+ "enable_dft_loss": false,
187
+ "enable_channel_loss": false,
188
+ "check_model": true,
189
+ "acc_strategy": "token",
190
+ "train_dataloader_shuffle": true,
191
+ "max_epochs": null,
192
+ "aligner_lr": null,
193
+ "vit_lr": null,
194
+ "use_logits_to_keep": null,
195
+ "ds3_gather_for_generation": true,
196
+ "resume_only_model": false,
197
+ "optimizer": null,
198
+ "loss_type": null,
199
+ "metric": null,
200
+ "eval_use_evalscope": false,
201
+ "eval_dataset": [],
202
+ "eval_dataset_args": null,
203
+ "eval_limit": null,
204
+ "eval_generation_config": null,
205
+ "extra_eval_args": null,
206
+ "use_flash_ckpt": false,
207
+ "use_ray": false,
208
+ "ray_exp_name": null,
209
+ "device_groups": null,
210
+ "model": "Qwen/Qwen3-0.6B",
211
+ "model_type": "qwen3",
212
+ "model_revision": null,
213
+ "task_type": "causal_lm",
214
+ "torch_dtype": "bfloat16",
215
+ "attn_impl": "flash_attn",
216
+ "new_special_tokens": [],
217
+ "num_labels": null,
218
+ "problem_type": null,
219
+ "rope_scaling": null,
220
+ "device_map": null,
221
+ "max_memory": {},
222
+ "max_model_len": null,
223
+ "local_repo_path": null,
224
+ "init_strategy": null,
225
+ "template": "qwen3",
226
+ "system": null,
227
+ "max_length": 20480,
228
+ "truncation_strategy": "delete",
229
+ "max_pixels": null,
230
+ "agent_template": null,
231
+ "norm_bbox": null,
232
+ "use_chat_template": true,
233
+ "padding_side": "right",
234
+ "padding_free": false,
235
+ "loss_scale": "ignore_empty_think",
236
+ "sequence_parallel_size": 1,
237
+ "template_backend": "swift",
238
+ "response_prefix": null,
239
+ "enable_thinking": null,
240
+ "add_non_thinking_prefix": true,
241
+ "dataset": [
242
+ "/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/data/train_sampled_with_instruction_high"
243
+ ],
244
+ "val_dataset": [],
245
+ "cached_dataset": [],
246
+ "cached_val_dataset": [],
247
+ "split_dataset_ratio": 0.0,
248
+ "dataset_num_proc": 8,
249
+ "load_from_cache_file": false,
250
+ "dataset_shuffle": true,
251
+ "val_dataset_shuffle": false,
252
+ "streaming": true,
253
+ "interleave_prob": null,
254
+ "stopping_strategy": "first_exhausted",
255
+ "shuffle_buffer_size": 1000,
256
+ "download_mode": "reuse_dataset_if_exists",
257
+ "columns": {},
258
+ "strict": false,
259
+ "model_name": null,
260
+ "model_author": null,
261
+ "custom_dataset_info": [],
262
+ "quant_method": null,
263
+ "quant_bits": null,
264
+ "hqq_axis": null,
265
+ "bnb_4bit_compute_dtype": "bfloat16",
266
+ "bnb_4bit_quant_type": "nf4",
267
+ "bnb_4bit_use_double_quant": true,
268
+ "bnb_4bit_quant_storage": null,
269
+ "max_new_tokens": 64,
270
+ "temperature": 0.0,
271
+ "top_k": null,
272
+ "top_p": null,
273
+ "repetition_penalty": null,
274
+ "num_beams": 1,
275
+ "stream": false,
276
+ "stop_words": [],
277
+ "logprobs": false,
278
+ "top_logprobs": null,
279
+ "ckpt_dir": null,
280
+ "lora_modules": [],
281
+ "train_type": "full",
282
+ "adapters": [],
283
+ "external_plugins": [],
284
+ "model_kwargs": {},
285
+ "load_args": false,
286
+ "load_data_args": false,
287
+ "packing": false,
288
+ "packing_length": null,
289
+ "packing_num_proc": 1,
290
+ "lazy_tokenize": false,
291
+ "custom_register_path": [],
292
+ "use_hf": false,
293
+ "ignore_args_error": false,
294
+ "use_swift_lora": false,
295
+ "freeze_parameters": [],
296
+ "freeze_parameters_regex": null,
297
+ "freeze_parameters_ratio": 0.0,
298
+ "trainable_parameters": [],
299
+ "trainable_parameters_regex": null,
300
+ "freeze_llm": false,
301
+ "freeze_vit": true,
302
+ "freeze_aligner": true,
303
+ "target_modules": [
304
+ "all-linear"
305
+ ],
306
+ "target_regex": null,
307
+ "target_parameters": null,
308
+ "modules_to_save": [],
309
+ "lora_rank": 8,
310
+ "lora_alpha": 32,
311
+ "lora_dropout": 0.05,
312
+ "lora_bias": "none",
313
+ "lora_dtype": null,
314
+ "lorap_lr_ratio": null,
315
+ "use_rslora": false,
316
+ "use_dora": false,
317
+ "lora_ga_batch_size": 2,
318
+ "lora_ga_iters": 2,
319
+ "lora_ga_max_length": 1024,
320
+ "lora_ga_direction": "ArB2r",
321
+ "lora_ga_scale": "stable",
322
+ "lora_ga_stable_gamma": 16,
323
+ "init_weights": true,
324
+ "fourier_n_frequency": 2000,
325
+ "fourier_scaling": 300.0,
326
+ "boft_block_size": 4,
327
+ "boft_block_num": 0,
328
+ "boft_n_butterfly_factor": 1,
329
+ "boft_dropout": 0.0,
330
+ "vera_rank": 256,
331
+ "vera_projection_prng_key": 0,
332
+ "vera_dropout": 0.0,
333
+ "vera_d_initial": 0.1,
334
+ "adapter_act": "gelu",
335
+ "adapter_length": 128,
336
+ "use_galore": false,
337
+ "galore_target_modules": null,
338
+ "galore_rank": 128,
339
+ "galore_update_proj_gap": 50,
340
+ "galore_scale": 1.0,
341
+ "galore_proj_type": "std",
342
+ "galore_optim_per_parameter": false,
343
+ "galore_with_embedding": false,
344
+ "galore_quantization": false,
345
+ "galore_proj_quant": false,
346
+ "galore_proj_bits": 4,
347
+ "galore_proj_group_size": 256,
348
+ "galore_cos_threshold": 0.4,
349
+ "galore_gamma_proj": 2,
350
+ "galore_queue_size": 5,
351
+ "adalora_target_r": 8,
352
+ "adalora_init_r": 12,
353
+ "adalora_tinit": 0,
354
+ "adalora_tfinal": 0,
355
+ "adalora_deltaT": 1,
356
+ "adalora_beta1": 0.85,
357
+ "adalora_beta2": 0.85,
358
+ "adalora_orth_reg_weight": 0.5,
359
+ "llamapro_num_new_blocks": 4,
360
+ "llamapro_num_groups": null,
361
+ "lisa_activated_layers": 0,
362
+ "lisa_step_interval": 20,
363
+ "reft_layer_key": null,
364
+ "reft_layers": null,
365
+ "reft_rank": 4,
366
+ "reft_intervention_type": "LoreftIntervention",
367
+ "reft_args": null,
368
+ "swanlab_token": null,
369
+ "swanlab_project": null,
370
+ "swanlab_workspace": null,
371
+ "swanlab_exp_name": null,
372
+ "swanlab_lark_webhook_url": null,
373
+ "swanlab_lark_secret": null,
374
+ "swanlab_mode": "cloud",
375
+ "add_version": true,
376
+ "create_checkpoint_symlink": false,
377
+ "zero_hpz_partition_size": null,
378
+ "deepspeed_autotp_size": null,
379
+ "early_stop_interval": null,
380
+ "rank": 0,
381
+ "global_world_size": 8,
382
+ "local_world_size": 8,
383
+ "model_suffix": "Qwen3-0.6B",
384
+ "model_info": "ModelInfo(model_type='qwen3', model_dir='/root/.cache/modelscope/hub/models/Qwen/Qwen3-0___6B', torch_dtype=torch.bfloat16, max_model_len=40960, quant_method=None, quant_bits=None, rope_scaling=None, is_moe_model=False, is_multimodal=False, config=None, task_type='causal_lm', num_labels=None)",
385
+ "model_meta": "ModelMeta(model_type='qwen3', model_groups=[ModelGroup(models=[Model(ms_model_id='Qwen/Qwen3-0.6B-Base', hf_model_id='Qwen/Qwen3-0.6B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-1.7B-Base', hf_model_id='Qwen/Qwen3-1.7B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-4B-Base', hf_model_id='Qwen/Qwen3-4B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-8B-Base', hf_model_id='Qwen/Qwen3-8B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-14B-Base', hf_model_id='Qwen/Qwen3-14B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-0.6B', hf_model_id='Qwen/Qwen3-0.6B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-1.7B', hf_model_id='Qwen/Qwen3-1.7B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-4B', hf_model_id='Qwen/Qwen3-4B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-8B', hf_model_id='Qwen/Qwen3-8B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-14B', hf_model_id='Qwen/Qwen3-14B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-32B', hf_model_id='Qwen/Qwen3-32B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-0.6B-FP8', hf_model_id='Qwen/Qwen3-0.6B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-1.7B-FP8', hf_model_id='Qwen/Qwen3-1.7B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-4B-FP8', hf_model_id='Qwen/Qwen3-4B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-8B-FP8', hf_model_id='Qwen/Qwen3-8B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-14B-FP8', hf_model_id='Qwen/Qwen3-14B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-32B-FP8', hf_model_id='Qwen/Qwen3-32B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-4B-AWQ', hf_model_id='Qwen/Qwen3-4B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-8B-AWQ', hf_model_id='Qwen/Qwen3-8B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-14B-AWQ', hf_model_id='Qwen/Qwen3-14B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-32B-AWQ', hf_model_id='Qwen/Qwen3-32B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='swift/Qwen3-32B-AWQ', hf_model_id=None, model_path=None, ms_revision=None, hf_revision=None)], ignore_patterns=None, requires=None, tags=[])], template='qwen3', get_function=<function get_model_tokenizer_with_flash_attn at 0x7fc894488550>, model_arch=ModelKeys(arch_name='llama', embedding='model.embed_tokens', module_list='model.layers', lm_head='lm_head', q_proj='model.layers.{}.self_attn.q_proj', k_proj='model.layers.{}.self_attn.k_proj', v_proj='model.layers.{}.self_attn.v_proj', o_proj='model.layers.{}.self_attn.o_proj', attention='model.layers.{}.self_attn', mlp='model.layers.{}.mlp', down_proj='model.layers.{}.mlp.down_proj', qkv_proj=None, qk_proj=None, qa_proj=None, qb_proj=None, kv_proj=None, kva_proj=None, kvb_proj=None), architectures=['Qwen3ForCausalLM'], additional_saved_files=[], torch_dtype=None, is_multimodal=False, is_reward=False, is_reranker=False, task_type=None, ignore_patterns=None, requires=['transformers>=4.51'], tags=[])",
386
+ "model_dir": "/root/.cache/modelscope/hub/models/Qwen/Qwen3-0___6B",
387
+ "_val_dataset_exists": [],
388
+ "hub": "<class 'swift.hub.hub.MSHub'>",
389
+ "evaluation_strategy": "steps",
390
+ "training_args": "Seq2SeqTrainingArguments(output_dir='/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/model/qwen3-0.6b-full-20k-2epoch-en_web_with_instruction_high/v1-20260429-105742', overwrite_output_dir=False, do_train=False, do_eval=False, do_predict=False, eval_strategy=<IntervalStrategy.NO: 'no'>, prediction_loss_only=False, per_device_train_batch_size=28, per_device_eval_batch_size=1, per_gpu_train_batch_size=None, per_gpu_eval_batch_size=None, gradient_accumulation_steps=3, eval_accumulation_steps=None, eval_delay=0, torch_empty_cache_steps=None, learning_rate=3e-05, weight_decay=0.1, adam_beta1=0.9, adam_beta2=0.95, adam_epsilon=1e-08, max_grad_norm=1.0, num_train_epochs=3.0, max_steps=8960, lr_scheduler_type=<SchedulerType.COSINE_WITH_MIN_LR: 'cosine_with_min_lr'>, lr_scheduler_kwargs={'min_lr': 3e-06}, warmup_ratio=0.03, warmup_steps=0, log_level='passive', log_level_replica='warning', log_on_each_node=True, logging_dir='/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/model/qwen3-0.6b-full-20k-2epoch-en_web_with_instruction_high/v1-20260429-105742/runs', logging_strategy=<IntervalStrategy.STEPS: 'steps'>, logging_first_step=True, logging_steps=10, logging_nan_inf_filter=True, save_strategy=<SaveStrategy.STEPS: 'steps'>, save_steps=4480, save_total_limit=3, save_safetensors=True, save_on_each_node=False, save_only_model=True, restore_callback_states_from_checkpoint=False, no_cuda=False, use_cpu=False, use_mps_device=False, seed=42, data_seed=42, jit_mode_eval=False, bf16=True, fp16=False, fp16_opt_level='O1', half_precision_backend='auto', bf16_full_eval=False, fp16_full_eval=False, tf32=None, local_rank=0, ddp_backend=None, tpu_num_cores=None, tpu_metrics_debug=False, debug=[], dataloader_drop_last=False, eval_steps=4480.0, dataloader_num_workers=8, dataloader_prefetch_factor=10, past_index=-1, run_name='/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/model/qwen3-0.6b-full-20k-2epoch-en_web_with_instruction_high/v1-20260429-105742', disable_tqdm=False, remove_unused_columns=False, label_names=None, load_best_model_at_end=False, metric_for_best_model='loss', greater_is_better=False, ignore_data_skip=False, fsdp=[], fsdp_min_num_params=0, fsdp_config={'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}, fsdp_transformer_layer_cls_to_wrap=None, accelerator_config=AcceleratorConfig(split_batches=False, dispatch_batches=False, even_batches=True, use_seedable_sampler=True, non_blocking=False, gradient_accumulation_kwargs=None, use_configured_state=False), parallelism_config=None, deepspeed={'fp16': {'enabled': 'auto', 'loss_scale': 0, 'loss_scale_window': 1000, 'initial_scale_power': 16, 'hysteresis': 2, 'min_loss_scale': 1}, 'bf16': {'enabled': 'auto'}, 'zero_optimization': {'stage': 3, 'offload_optimizer': {'device': 'none', 'pin_memory': True}, 'offload_param': {'device': 'none', 'pin_memory': True}, 'overlap_comm': False, 'contiguous_gradients': True, 'sub_group_size': 1000000000.0, 'reduce_bucket_size': 'auto', 'zero_quantized_weights': False, 'zero_quantized_gradients': False, 'stage3_prefetch_bucket_size': 'auto', 'stage3_param_persistence_threshold': 'auto', 'stage3_max_live_parameters': 1000000000.0, 'stage3_max_reuse_distance': 1000000000.0, 'stage3_gather_16bit_weights_on_model_save': True}, 'gradient_accumulation_steps': 'auto', 'gradient_clipping': 'auto', 'steps_per_print': 2000, 'train_batch_size': 'auto', 'train_micro_batch_size_per_gpu': 'auto', 'wall_clock_breakdown': False}, label_smoothing_factor=0.0, optim=<OptimizerNames.ADAMW_TORCH_FUSED: 'adamw_torch_fused'>, optim_args=None, adafactor=False, group_by_length=False, length_column_name='length', report_to=['tensorboard'], project='huggingface', trackio_space_id='trackio', ddp_find_unused_parameters=None, ddp_bucket_cap_mb=None, ddp_broadcast_buffers=None, dataloader_pin_memory=True, dataloader_persistent_workers=False, skip_memory_metrics=True, use_legacy_prediction_loop=False, push_to_hub=False, resume_from_checkpoint=None, hub_model_id=None, hub_strategy=<HubStrategy.EVERY_SAVE: 'every_save'>, hub_token=None, hub_private_repo=None, hub_always_push=False, hub_revision=None, gradient_checkpointing=True, gradient_checkpointing_kwargs=None, include_inputs_for_metrics=False, include_for_metrics=[], eval_do_concat_batches=True, fp16_backend='auto', push_to_hub_model_id=None, push_to_hub_organization=None, push_to_hub_token=None, mp_parameters='', auto_find_batch_size=False, full_determinism=False, torchdynamo=None, ray_scope='last', ddp_timeout=18000000, torch_compile=False, torch_compile_backend=None, torch_compile_mode=None, include_tokens_per_second=None, include_num_input_tokens_seen=None, neftune_noise_alpha=None, optim_target_modules=None, batch_eval_metrics=False, eval_on_start=False, use_liger_kernel=True, liger_kernel_config=None, eval_use_gather_object=False, average_tokens_across_devices=None, sortish_sampler=False, predict_with_generate=False, generation_max_length=None, generation_num_beams=None, generation_config=None, tuner_backend='peft', vit_gradient_checkpointing=True, router_aux_loss_coef=0.0, enable_dft_loss=False, enable_channel_loss=False, check_model=True, acc_strategy='token', train_dataloader_shuffle=True, max_epochs=None, aligner_lr=None, vit_lr=None, use_logits_to_keep=None, ds3_gather_for_generation=True, resume_only_model=False, optimizer=None, loss_type=None, metric=None, eval_use_evalscope=False, eval_dataset=[], eval_dataset_args=None, eval_limit=None, eval_generation_config=None, extra_eval_args=None, use_flash_ckpt=False, sft_alpha=0, chord_sft_dataset=[], chord_sft_per_device_train_batch_size=None, chord_enable_phi_function=False, chord_mu_warmup_steps=None, chord_mu_decay_steps=None, chord_mu_peak=None, chord_mu_valley=None, train_type='full', local_repo_path=None, galore_config=None, task_type='causal_lm', problem_type=None)"
391
+ }
models/UltraX-Preservation-Weighted/chat_template.jinja ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# 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>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\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" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if message.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {%- set reasoning_content = '' %}
35
+ {%- if message.reasoning_content is string %}
36
+ {%- set reasoning_content = message.reasoning_content %}
37
+ {%- else %}
38
+ {%- if '</think>' in content %}
39
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
40
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
41
+ {%- endif %}
42
+ {%- endif %}
43
+ {%- if loop.index0 > ns.last_query_index %}
44
+ {%- if loop.last or (not loop.last and reasoning_content) %}
45
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
46
+ {%- else %}
47
+ {{- '<|im_start|>' + message.role + '\n' + content }}
48
+ {%- endif %}
49
+ {%- else %}
50
+ {{- '<|im_start|>' + message.role + '\n' + content }}
51
+ {%- endif %}
52
+ {%- if message.tool_calls %}
53
+ {%- for tool_call in message.tool_calls %}
54
+ {%- if (loop.first and content) or (not loop.first) %}
55
+ {{- '\n' }}
56
+ {%- endif %}
57
+ {%- if tool_call.function %}
58
+ {%- set tool_call = tool_call.function %}
59
+ {%- endif %}
60
+ {{- '<tool_call>\n{"name": "' }}
61
+ {{- tool_call.name }}
62
+ {{- '", "arguments": ' }}
63
+ {%- if tool_call.arguments is string %}
64
+ {{- tool_call.arguments }}
65
+ {%- else %}
66
+ {{- tool_call.arguments | tojson }}
67
+ {%- endif %}
68
+ {{- '}\n</tool_call>' }}
69
+ {%- endfor %}
70
+ {%- endif %}
71
+ {{- '<|im_end|>\n' }}
72
+ {%- elif message.role == "tool" %}
73
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
74
+ {{- '<|im_start|>user' }}
75
+ {%- endif %}
76
+ {{- '\n<tool_response>\n' }}
77
+ {{- content }}
78
+ {{- '\n</tool_response>' }}
79
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
80
+ {{- '<|im_end|>\n' }}
81
+ {%- endif %}
82
+ {%- endif %}
83
+ {%- endfor %}
84
+ {%- if add_generation_prompt %}
85
+ {{- '<|im_start|>assistant\n' }}
86
+ {%- if enable_thinking is defined and enable_thinking is false %}
87
+ {{- '<think>\n\n</think>\n\n' }}
88
+ {%- endif %}
89
+ {%- endif %}
models/UltraX-Preservation-Weighted/config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "dtype": "bfloat16",
8
+ "eos_token_id": 151645,
9
+ "head_dim": 128,
10
+ "hidden_act": "silu",
11
+ "hidden_size": 1024,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 3072,
14
+ "layer_types": [
15
+ "full_attention",
16
+ "full_attention",
17
+ "full_attention",
18
+ "full_attention",
19
+ "full_attention",
20
+ "full_attention",
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "full_attention",
27
+ "full_attention",
28
+ "full_attention",
29
+ "full_attention",
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention",
33
+ "full_attention",
34
+ "full_attention",
35
+ "full_attention",
36
+ "full_attention",
37
+ "full_attention",
38
+ "full_attention",
39
+ "full_attention",
40
+ "full_attention",
41
+ "full_attention",
42
+ "full_attention"
43
+ ],
44
+ "max_position_embeddings": 40960,
45
+ "max_window_layers": 28,
46
+ "model_type": "qwen3",
47
+ "num_attention_heads": 16,
48
+ "num_hidden_layers": 28,
49
+ "num_key_value_heads": 8,
50
+ "pad_token_id": 151643,
51
+ "rms_norm_eps": 1e-06,
52
+ "rope_scaling": null,
53
+ "rope_theta": 1000000,
54
+ "sliding_window": null,
55
+ "tie_word_embeddings": true,
56
+ "transformers_version": "4.57.3",
57
+ "use_cache": false,
58
+ "use_sliding_window": false,
59
+ "vocab_size": 151936
60
+ }
models/UltraX-Preservation-Weighted/generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "temperature": 0.6,
10
+ "top_k": 20,
11
+ "top_p": 0.95,
12
+ "transformers_version": "4.57.3"
13
+ }
models/UltraX-Preservation-Weighted/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
models/UltraX-Preservation-Weighted/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d2cb01af211ed9f0087761a904705d40a9ad80128bb499e1b4a3b30614e36ac
3
+ size 1192135096
models/UltraX-Preservation-Weighted/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": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
models/UltraX-Preservation-Weighted/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4
3
+ size 11422654
models/UltraX-Preservation-Weighted/tokenizer_config.json ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ }
213
+ },
214
+ "additional_special_tokens": [
215
+ "<|im_start|>",
216
+ "<|im_end|>",
217
+ "<|object_ref_start|>",
218
+ "<|object_ref_end|>",
219
+ "<|box_start|>",
220
+ "<|box_end|>",
221
+ "<|quad_start|>",
222
+ "<|quad_end|>",
223
+ "<|vision_start|>",
224
+ "<|vision_end|>",
225
+ "<|vision_pad|>",
226
+ "<|image_pad|>",
227
+ "<|video_pad|>"
228
+ ],
229
+ "bos_token": null,
230
+ "clean_up_tokenization_spaces": false,
231
+ "eos_token": "<|im_end|>",
232
+ "errors": "replace",
233
+ "extra_special_tokens": {},
234
+ "model_max_length": 131072,
235
+ "pad_token": "<|endoftext|>",
236
+ "split_special_tokens": false,
237
+ "tokenizer_class": "Qwen2Tokenizer",
238
+ "unk_token": null
239
+ }
models/UltraX-Preservation-Weighted/trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
models/UltraX-Preservation-Weighted/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3832c89bc01925f5362c6391db5e2275a8ffd105134fd1975fde3d32f410712e
3
+ size 9681
models/UltraX-Preservation-Weighted/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
models/UltraX/added_tokens.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|box_end|>": 151649,
9
+ "<|box_start|>": 151648,
10
+ "<|endoftext|>": 151643,
11
+ "<|file_sep|>": 151664,
12
+ "<|fim_middle|>": 151660,
13
+ "<|fim_pad|>": 151662,
14
+ "<|fim_prefix|>": 151659,
15
+ "<|fim_suffix|>": 151661,
16
+ "<|im_end|>": 151645,
17
+ "<|im_start|>": 151644,
18
+ "<|image_pad|>": 151655,
19
+ "<|object_ref_end|>": 151647,
20
+ "<|object_ref_start|>": 151646,
21
+ "<|quad_end|>": 151651,
22
+ "<|quad_start|>": 151650,
23
+ "<|repo_name|>": 151663,
24
+ "<|video_pad|>": 151656,
25
+ "<|vision_end|>": 151653,
26
+ "<|vision_pad|>": 151654,
27
+ "<|vision_start|>": 151652
28
+ }
models/UltraX/args.json ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "output_dir": "/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/model/qwen3-0.6b-full-20k-2epoch-en_web_with_instruction/v0-20260427-152720",
3
+ "overwrite_output_dir": false,
4
+ "do_train": false,
5
+ "do_eval": false,
6
+ "do_predict": false,
7
+ "eval_strategy": "no",
8
+ "prediction_loss_only": false,
9
+ "per_device_train_batch_size": 24,
10
+ "per_device_eval_batch_size": 1,
11
+ "per_gpu_train_batch_size": null,
12
+ "per_gpu_eval_batch_size": null,
13
+ "gradient_accumulation_steps": 3,
14
+ "eval_accumulation_steps": null,
15
+ "eval_delay": 0,
16
+ "torch_empty_cache_steps": null,
17
+ "learning_rate": 3e-05,
18
+ "weight_decay": 0.1,
19
+ "adam_beta1": 0.9,
20
+ "adam_beta2": 0.95,
21
+ "adam_epsilon": 1e-08,
22
+ "max_grad_norm": 1.0,
23
+ "num_train_epochs": 3.0,
24
+ "max_steps": 5530,
25
+ "lr_scheduler_type": "cosine_with_min_lr",
26
+ "lr_scheduler_kwargs": "{\"min_lr\": 3e-6}",
27
+ "warmup_ratio": 0.03,
28
+ "warmup_steps": 0,
29
+ "log_level": "passive",
30
+ "log_level_replica": "warning",
31
+ "log_on_each_node": true,
32
+ "logging_dir": "/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/model/qwen3-0.6b-full-20k-2epoch-en_web_with_instruction/v0-20260427-152720/runs",
33
+ "logging_strategy": "steps",
34
+ "logging_first_step": true,
35
+ "logging_steps": 10,
36
+ "logging_nan_inf_filter": true,
37
+ "save_strategy": "steps",
38
+ "save_steps": 2765.0,
39
+ "save_total_limit": 3,
40
+ "save_safetensors": true,
41
+ "save_on_each_node": false,
42
+ "save_only_model": true,
43
+ "restore_callback_states_from_checkpoint": false,
44
+ "no_cuda": false,
45
+ "use_cpu": false,
46
+ "use_mps_device": false,
47
+ "seed": 42,
48
+ "data_seed": 42,
49
+ "jit_mode_eval": false,
50
+ "bf16": true,
51
+ "fp16": false,
52
+ "fp16_opt_level": "O1",
53
+ "half_precision_backend": "auto",
54
+ "bf16_full_eval": false,
55
+ "fp16_full_eval": false,
56
+ "tf32": null,
57
+ "local_rank": 0,
58
+ "ddp_backend": null,
59
+ "tpu_num_cores": null,
60
+ "tpu_metrics_debug": false,
61
+ "debug": null,
62
+ "dataloader_drop_last": false,
63
+ "eval_steps": 2765.0,
64
+ "dataloader_num_workers": 8,
65
+ "dataloader_prefetch_factor": null,
66
+ "past_index": -1,
67
+ "run_name": "/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/model/qwen3-0.6b-full-20k-2epoch-en_web_with_instruction/v0-20260427-152720",
68
+ "disable_tqdm": null,
69
+ "remove_unused_columns": true,
70
+ "label_names": null,
71
+ "load_best_model_at_end": false,
72
+ "metric_for_best_model": "loss",
73
+ "greater_is_better": false,
74
+ "ignore_data_skip": false,
75
+ "fsdp": null,
76
+ "fsdp_min_num_params": 0,
77
+ "fsdp_config": null,
78
+ "fsdp_transformer_layer_cls_to_wrap": null,
79
+ "accelerator_config": {
80
+ "dispatch_batches": false
81
+ },
82
+ "parallelism_config": null,
83
+ "deepspeed": {
84
+ "fp16": {
85
+ "enabled": "auto",
86
+ "loss_scale": 0,
87
+ "loss_scale_window": 1000,
88
+ "initial_scale_power": 16,
89
+ "hysteresis": 2,
90
+ "min_loss_scale": 1
91
+ },
92
+ "bf16": {
93
+ "enabled": "auto"
94
+ },
95
+ "zero_optimization": {
96
+ "stage": 3,
97
+ "offload_optimizer": {
98
+ "device": "none",
99
+ "pin_memory": true
100
+ },
101
+ "offload_param": {
102
+ "device": "none",
103
+ "pin_memory": true
104
+ },
105
+ "overlap_comm": false,
106
+ "contiguous_gradients": true,
107
+ "sub_group_size": 1000000000.0,
108
+ "reduce_bucket_size": "auto",
109
+ "zero_quantized_weights": false,
110
+ "zero_quantized_gradients": false,
111
+ "stage3_prefetch_bucket_size": "auto",
112
+ "stage3_param_persistence_threshold": "auto",
113
+ "stage3_max_live_parameters": 1000000000.0,
114
+ "stage3_max_reuse_distance": 1000000000.0,
115
+ "stage3_gather_16bit_weights_on_model_save": true
116
+ },
117
+ "gradient_accumulation_steps": "auto",
118
+ "gradient_clipping": "auto",
119
+ "steps_per_print": 2000,
120
+ "train_batch_size": "auto",
121
+ "train_micro_batch_size_per_gpu": "auto",
122
+ "wall_clock_breakdown": false
123
+ },
124
+ "label_smoothing_factor": 0.0,
125
+ "optim": "adamw_torch_fused",
126
+ "optim_args": null,
127
+ "adafactor": false,
128
+ "group_by_length": false,
129
+ "length_column_name": "length",
130
+ "report_to": [
131
+ "tensorboard"
132
+ ],
133
+ "project": "huggingface",
134
+ "trackio_space_id": "trackio",
135
+ "ddp_find_unused_parameters": null,
136
+ "ddp_bucket_cap_mb": null,
137
+ "ddp_broadcast_buffers": null,
138
+ "dataloader_pin_memory": true,
139
+ "dataloader_persistent_workers": false,
140
+ "skip_memory_metrics": true,
141
+ "use_legacy_prediction_loop": false,
142
+ "push_to_hub": false,
143
+ "resume_from_checkpoint": null,
144
+ "hub_model_id": null,
145
+ "hub_strategy": "every_save",
146
+ "hub_token": null,
147
+ "hub_private_repo": null,
148
+ "hub_always_push": false,
149
+ "hub_revision": null,
150
+ "gradient_checkpointing": true,
151
+ "gradient_checkpointing_kwargs": null,
152
+ "include_inputs_for_metrics": false,
153
+ "include_for_metrics": [],
154
+ "eval_do_concat_batches": true,
155
+ "fp16_backend": "auto",
156
+ "push_to_hub_model_id": null,
157
+ "push_to_hub_organization": null,
158
+ "push_to_hub_token": null,
159
+ "mp_parameters": "",
160
+ "auto_find_batch_size": false,
161
+ "full_determinism": false,
162
+ "torchdynamo": null,
163
+ "ray_scope": "last",
164
+ "ddp_timeout": 18000000,
165
+ "torch_compile": false,
166
+ "torch_compile_backend": null,
167
+ "torch_compile_mode": null,
168
+ "include_tokens_per_second": false,
169
+ "include_num_input_tokens_seen": false,
170
+ "neftune_noise_alpha": null,
171
+ "optim_target_modules": null,
172
+ "batch_eval_metrics": false,
173
+ "eval_on_start": false,
174
+ "use_liger_kernel": true,
175
+ "liger_kernel_config": null,
176
+ "eval_use_gather_object": false,
177
+ "average_tokens_across_devices": true,
178
+ "sortish_sampler": false,
179
+ "predict_with_generate": false,
180
+ "generation_max_length": null,
181
+ "generation_num_beams": null,
182
+ "generation_config": null,
183
+ "tuner_backend": "peft",
184
+ "vit_gradient_checkpointing": null,
185
+ "router_aux_loss_coef": 0.0,
186
+ "enable_dft_loss": false,
187
+ "enable_channel_loss": false,
188
+ "check_model": true,
189
+ "acc_strategy": "token",
190
+ "train_dataloader_shuffle": true,
191
+ "max_epochs": null,
192
+ "aligner_lr": null,
193
+ "vit_lr": null,
194
+ "use_logits_to_keep": null,
195
+ "ds3_gather_for_generation": true,
196
+ "resume_only_model": false,
197
+ "optimizer": null,
198
+ "loss_type": null,
199
+ "metric": null,
200
+ "eval_use_evalscope": false,
201
+ "eval_dataset": [],
202
+ "eval_dataset_args": null,
203
+ "eval_limit": null,
204
+ "eval_generation_config": null,
205
+ "extra_eval_args": null,
206
+ "use_flash_ckpt": false,
207
+ "use_ray": false,
208
+ "ray_exp_name": null,
209
+ "device_groups": null,
210
+ "model": "Qwen/Qwen3-0.6B",
211
+ "model_type": "qwen3",
212
+ "model_revision": null,
213
+ "task_type": "causal_lm",
214
+ "torch_dtype": "bfloat16",
215
+ "attn_impl": "flash_attn",
216
+ "new_special_tokens": [],
217
+ "num_labels": null,
218
+ "problem_type": null,
219
+ "rope_scaling": null,
220
+ "device_map": null,
221
+ "max_memory": {},
222
+ "max_model_len": null,
223
+ "local_repo_path": null,
224
+ "init_strategy": null,
225
+ "template": "qwen3",
226
+ "system": null,
227
+ "max_length": 20480,
228
+ "truncation_strategy": "delete",
229
+ "max_pixels": null,
230
+ "agent_template": null,
231
+ "norm_bbox": null,
232
+ "use_chat_template": true,
233
+ "padding_side": "right",
234
+ "padding_free": false,
235
+ "loss_scale": "ignore_empty_think",
236
+ "sequence_parallel_size": 1,
237
+ "template_backend": "swift",
238
+ "response_prefix": null,
239
+ "enable_thinking": null,
240
+ "add_non_thinking_prefix": true,
241
+ "dataset": [
242
+ "/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/data/train_sampled_with_instruction"
243
+ ],
244
+ "val_dataset": [],
245
+ "cached_dataset": [],
246
+ "cached_val_dataset": [],
247
+ "split_dataset_ratio": 0.0,
248
+ "dataset_num_proc": 8,
249
+ "load_from_cache_file": false,
250
+ "dataset_shuffle": true,
251
+ "val_dataset_shuffle": false,
252
+ "streaming": true,
253
+ "interleave_prob": null,
254
+ "stopping_strategy": "first_exhausted",
255
+ "shuffle_buffer_size": 1000,
256
+ "download_mode": "reuse_dataset_if_exists",
257
+ "columns": {},
258
+ "strict": false,
259
+ "model_name": null,
260
+ "model_author": null,
261
+ "custom_dataset_info": [],
262
+ "quant_method": null,
263
+ "quant_bits": null,
264
+ "hqq_axis": null,
265
+ "bnb_4bit_compute_dtype": "bfloat16",
266
+ "bnb_4bit_quant_type": "nf4",
267
+ "bnb_4bit_use_double_quant": true,
268
+ "bnb_4bit_quant_storage": null,
269
+ "max_new_tokens": 64,
270
+ "temperature": 0.0,
271
+ "top_k": null,
272
+ "top_p": null,
273
+ "repetition_penalty": null,
274
+ "num_beams": 1,
275
+ "stream": false,
276
+ "stop_words": [],
277
+ "logprobs": false,
278
+ "top_logprobs": null,
279
+ "ckpt_dir": null,
280
+ "lora_modules": [],
281
+ "train_type": "full",
282
+ "adapters": [],
283
+ "external_plugins": [],
284
+ "model_kwargs": {},
285
+ "load_args": false,
286
+ "load_data_args": false,
287
+ "packing": false,
288
+ "packing_length": null,
289
+ "packing_num_proc": 1,
290
+ "lazy_tokenize": false,
291
+ "custom_register_path": [],
292
+ "use_hf": false,
293
+ "ignore_args_error": false,
294
+ "use_swift_lora": false,
295
+ "freeze_parameters": [],
296
+ "freeze_parameters_regex": null,
297
+ "freeze_parameters_ratio": 0.0,
298
+ "trainable_parameters": [],
299
+ "trainable_parameters_regex": null,
300
+ "freeze_llm": false,
301
+ "freeze_vit": true,
302
+ "freeze_aligner": true,
303
+ "target_modules": [
304
+ "all-linear"
305
+ ],
306
+ "target_regex": null,
307
+ "target_parameters": null,
308
+ "modules_to_save": [],
309
+ "lora_rank": 8,
310
+ "lora_alpha": 32,
311
+ "lora_dropout": 0.05,
312
+ "lora_bias": "none",
313
+ "lora_dtype": null,
314
+ "lorap_lr_ratio": null,
315
+ "use_rslora": false,
316
+ "use_dora": false,
317
+ "lora_ga_batch_size": 2,
318
+ "lora_ga_iters": 2,
319
+ "lora_ga_max_length": 1024,
320
+ "lora_ga_direction": "ArB2r",
321
+ "lora_ga_scale": "stable",
322
+ "lora_ga_stable_gamma": 16,
323
+ "init_weights": true,
324
+ "fourier_n_frequency": 2000,
325
+ "fourier_scaling": 300.0,
326
+ "boft_block_size": 4,
327
+ "boft_block_num": 0,
328
+ "boft_n_butterfly_factor": 1,
329
+ "boft_dropout": 0.0,
330
+ "vera_rank": 256,
331
+ "vera_projection_prng_key": 0,
332
+ "vera_dropout": 0.0,
333
+ "vera_d_initial": 0.1,
334
+ "adapter_act": "gelu",
335
+ "adapter_length": 128,
336
+ "use_galore": false,
337
+ "galore_target_modules": null,
338
+ "galore_rank": 128,
339
+ "galore_update_proj_gap": 50,
340
+ "galore_scale": 1.0,
341
+ "galore_proj_type": "std",
342
+ "galore_optim_per_parameter": false,
343
+ "galore_with_embedding": false,
344
+ "galore_quantization": false,
345
+ "galore_proj_quant": false,
346
+ "galore_proj_bits": 4,
347
+ "galore_proj_group_size": 256,
348
+ "galore_cos_threshold": 0.4,
349
+ "galore_gamma_proj": 2,
350
+ "galore_queue_size": 5,
351
+ "adalora_target_r": 8,
352
+ "adalora_init_r": 12,
353
+ "adalora_tinit": 0,
354
+ "adalora_tfinal": 0,
355
+ "adalora_deltaT": 1,
356
+ "adalora_beta1": 0.85,
357
+ "adalora_beta2": 0.85,
358
+ "adalora_orth_reg_weight": 0.5,
359
+ "llamapro_num_new_blocks": 4,
360
+ "llamapro_num_groups": null,
361
+ "lisa_activated_layers": 0,
362
+ "lisa_step_interval": 20,
363
+ "reft_layer_key": null,
364
+ "reft_layers": null,
365
+ "reft_rank": 4,
366
+ "reft_intervention_type": "LoreftIntervention",
367
+ "reft_args": null,
368
+ "swanlab_token": null,
369
+ "swanlab_project": null,
370
+ "swanlab_workspace": null,
371
+ "swanlab_exp_name": null,
372
+ "swanlab_lark_webhook_url": null,
373
+ "swanlab_lark_secret": null,
374
+ "swanlab_mode": "cloud",
375
+ "add_version": true,
376
+ "create_checkpoint_symlink": false,
377
+ "zero_hpz_partition_size": null,
378
+ "deepspeed_autotp_size": null,
379
+ "early_stop_interval": null,
380
+ "rank": 0,
381
+ "global_world_size": 8,
382
+ "local_world_size": 8,
383
+ "model_suffix": "Qwen3-0.6B",
384
+ "model_info": "ModelInfo(model_type='qwen3', model_dir='/root/.cache/modelscope/hub/models/Qwen/Qwen3-0___6B', torch_dtype=torch.bfloat16, max_model_len=40960, quant_method=None, quant_bits=None, rope_scaling=None, is_moe_model=False, is_multimodal=False, config=None, task_type='causal_lm', num_labels=None)",
385
+ "model_meta": "ModelMeta(model_type='qwen3', model_groups=[ModelGroup(models=[Model(ms_model_id='Qwen/Qwen3-0.6B-Base', hf_model_id='Qwen/Qwen3-0.6B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-1.7B-Base', hf_model_id='Qwen/Qwen3-1.7B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-4B-Base', hf_model_id='Qwen/Qwen3-4B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-8B-Base', hf_model_id='Qwen/Qwen3-8B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-14B-Base', hf_model_id='Qwen/Qwen3-14B-Base', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-0.6B', hf_model_id='Qwen/Qwen3-0.6B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-1.7B', hf_model_id='Qwen/Qwen3-1.7B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-4B', hf_model_id='Qwen/Qwen3-4B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-8B', hf_model_id='Qwen/Qwen3-8B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-14B', hf_model_id='Qwen/Qwen3-14B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-32B', hf_model_id='Qwen/Qwen3-32B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-0.6B-FP8', hf_model_id='Qwen/Qwen3-0.6B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-1.7B-FP8', hf_model_id='Qwen/Qwen3-1.7B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-4B-FP8', hf_model_id='Qwen/Qwen3-4B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-8B-FP8', hf_model_id='Qwen/Qwen3-8B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-14B-FP8', hf_model_id='Qwen/Qwen3-14B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-32B-FP8', hf_model_id='Qwen/Qwen3-32B-FP8', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-4B-AWQ', hf_model_id='Qwen/Qwen3-4B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-8B-AWQ', hf_model_id='Qwen/Qwen3-8B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-14B-AWQ', hf_model_id='Qwen/Qwen3-14B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='Qwen/Qwen3-32B-AWQ', hf_model_id='Qwen/Qwen3-32B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='swift/Qwen3-32B-AWQ', hf_model_id=None, model_path=None, ms_revision=None, hf_revision=None)], ignore_patterns=None, requires=None, tags=[])], template='qwen3', get_function=<function get_model_tokenizer_with_flash_attn at 0x7f93756a2f80>, model_arch=ModelKeys(arch_name='llama', embedding='model.embed_tokens', module_list='model.layers', lm_head='lm_head', q_proj='model.layers.{}.self_attn.q_proj', k_proj='model.layers.{}.self_attn.k_proj', v_proj='model.layers.{}.self_attn.v_proj', o_proj='model.layers.{}.self_attn.o_proj', attention='model.layers.{}.self_attn', mlp='model.layers.{}.mlp', down_proj='model.layers.{}.mlp.down_proj', qkv_proj=None, qk_proj=None, qa_proj=None, qb_proj=None, kv_proj=None, kva_proj=None, kvb_proj=None), architectures=['Qwen3ForCausalLM'], additional_saved_files=[], torch_dtype=None, is_multimodal=False, is_reward=False, is_reranker=False, task_type=None, ignore_patterns=None, requires=['transformers>=4.51'], tags=[])",
386
+ "model_dir": "/root/.cache/modelscope/hub/models/Qwen/Qwen3-0___6B",
387
+ "_val_dataset_exists": [],
388
+ "hub": "<class 'swift.hub.hub.MSHub'>",
389
+ "evaluation_strategy": "steps",
390
+ "training_args": "Seq2SeqTrainingArguments(output_dir='/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/model/qwen3-0.6b-full-20k-2epoch-en_web_with_instruction/v0-20260427-152720', overwrite_output_dir=False, do_train=False, do_eval=False, do_predict=False, eval_strategy=<IntervalStrategy.NO: 'no'>, prediction_loss_only=False, per_device_train_batch_size=24, per_device_eval_batch_size=1, per_gpu_train_batch_size=None, per_gpu_eval_batch_size=None, gradient_accumulation_steps=3, eval_accumulation_steps=None, eval_delay=0, torch_empty_cache_steps=None, learning_rate=3e-05, weight_decay=0.1, adam_beta1=0.9, adam_beta2=0.95, adam_epsilon=1e-08, max_grad_norm=1.0, num_train_epochs=3.0, max_steps=5530, lr_scheduler_type=<SchedulerType.COSINE_WITH_MIN_LR: 'cosine_with_min_lr'>, lr_scheduler_kwargs={'min_lr': 3e-06}, warmup_ratio=0.03, warmup_steps=0, log_level='passive', log_level_replica='warning', log_on_each_node=True, logging_dir='/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/model/qwen3-0.6b-full-20k-2epoch-en_web_with_instruction/v0-20260427-152720/runs', logging_strategy=<IntervalStrategy.STEPS: 'steps'>, logging_first_step=True, logging_steps=10, logging_nan_inf_filter=True, save_strategy=<SaveStrategy.STEPS: 'steps'>, save_steps=2765, save_total_limit=3, save_safetensors=True, save_on_each_node=False, save_only_model=True, restore_callback_states_from_checkpoint=False, no_cuda=False, use_cpu=False, use_mps_device=False, seed=42, data_seed=42, jit_mode_eval=False, bf16=True, fp16=False, fp16_opt_level='O1', half_precision_backend='auto', bf16_full_eval=False, fp16_full_eval=False, tf32=None, local_rank=0, ddp_backend=None, tpu_num_cores=None, tpu_metrics_debug=False, debug=[], dataloader_drop_last=False, eval_steps=2765.0, dataloader_num_workers=8, dataloader_prefetch_factor=10, past_index=-1, run_name='/user/zhangyixuan/share_user_data/user/zhaoxinlong/4_new_exp_final/model/qwen3-0.6b-full-20k-2epoch-en_web_with_instruction/v0-20260427-152720', disable_tqdm=False, remove_unused_columns=False, label_names=None, load_best_model_at_end=False, metric_for_best_model='loss', greater_is_better=False, ignore_data_skip=False, fsdp=[], fsdp_min_num_params=0, fsdp_config={'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}, fsdp_transformer_layer_cls_to_wrap=None, accelerator_config=AcceleratorConfig(split_batches=False, dispatch_batches=False, even_batches=True, use_seedable_sampler=True, non_blocking=False, gradient_accumulation_kwargs=None, use_configured_state=False), parallelism_config=None, deepspeed={'fp16': {'enabled': 'auto', 'loss_scale': 0, 'loss_scale_window': 1000, 'initial_scale_power': 16, 'hysteresis': 2, 'min_loss_scale': 1}, 'bf16': {'enabled': 'auto'}, 'zero_optimization': {'stage': 3, 'offload_optimizer': {'device': 'none', 'pin_memory': True}, 'offload_param': {'device': 'none', 'pin_memory': True}, 'overlap_comm': False, 'contiguous_gradients': True, 'sub_group_size': 1000000000.0, 'reduce_bucket_size': 'auto', 'zero_quantized_weights': False, 'zero_quantized_gradients': False, 'stage3_prefetch_bucket_size': 'auto', 'stage3_param_persistence_threshold': 'auto', 'stage3_max_live_parameters': 1000000000.0, 'stage3_max_reuse_distance': 1000000000.0, 'stage3_gather_16bit_weights_on_model_save': True}, 'gradient_accumulation_steps': 'auto', 'gradient_clipping': 'auto', 'steps_per_print': 2000, 'train_batch_size': 'auto', 'train_micro_batch_size_per_gpu': 'auto', 'wall_clock_breakdown': False}, label_smoothing_factor=0.0, optim=<OptimizerNames.ADAMW_TORCH_FUSED: 'adamw_torch_fused'>, optim_args=None, adafactor=False, group_by_length=False, length_column_name='length', report_to=['tensorboard'], project='huggingface', trackio_space_id='trackio', ddp_find_unused_parameters=None, ddp_bucket_cap_mb=None, ddp_broadcast_buffers=None, dataloader_pin_memory=True, dataloader_persistent_workers=False, skip_memory_metrics=True, use_legacy_prediction_loop=False, push_to_hub=False, resume_from_checkpoint=None, hub_model_id=None, hub_strategy=<HubStrategy.EVERY_SAVE: 'every_save'>, hub_token=None, hub_private_repo=None, hub_always_push=False, hub_revision=None, gradient_checkpointing=True, gradient_checkpointing_kwargs=None, include_inputs_for_metrics=False, include_for_metrics=[], eval_do_concat_batches=True, fp16_backend='auto', push_to_hub_model_id=None, push_to_hub_organization=None, push_to_hub_token=None, mp_parameters='', auto_find_batch_size=False, full_determinism=False, torchdynamo=None, ray_scope='last', ddp_timeout=18000000, torch_compile=False, torch_compile_backend=None, torch_compile_mode=None, include_tokens_per_second=None, include_num_input_tokens_seen=None, neftune_noise_alpha=None, optim_target_modules=None, batch_eval_metrics=False, eval_on_start=False, use_liger_kernel=True, liger_kernel_config=None, eval_use_gather_object=False, average_tokens_across_devices=None, sortish_sampler=False, predict_with_generate=False, generation_max_length=None, generation_num_beams=None, generation_config=None, tuner_backend='peft', vit_gradient_checkpointing=True, router_aux_loss_coef=0.0, enable_dft_loss=False, enable_channel_loss=False, check_model=True, acc_strategy='token', train_dataloader_shuffle=True, max_epochs=None, aligner_lr=None, vit_lr=None, use_logits_to_keep=None, ds3_gather_for_generation=True, resume_only_model=False, optimizer=None, loss_type=None, metric=None, eval_use_evalscope=False, eval_dataset=[], eval_dataset_args=None, eval_limit=None, eval_generation_config=None, extra_eval_args=None, use_flash_ckpt=False, sft_alpha=0, chord_sft_dataset=[], chord_sft_per_device_train_batch_size=None, chord_enable_phi_function=False, chord_mu_warmup_steps=None, chord_mu_decay_steps=None, chord_mu_peak=None, chord_mu_valley=None, train_type='full', local_repo_path=None, galore_config=None, task_type='causal_lm', problem_type=None)"
391
+ }
models/UltraX/chat_template.jinja ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# 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>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\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" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if message.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {%- set reasoning_content = '' %}
35
+ {%- if message.reasoning_content is string %}
36
+ {%- set reasoning_content = message.reasoning_content %}
37
+ {%- else %}
38
+ {%- if '</think>' in content %}
39
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
40
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
41
+ {%- endif %}
42
+ {%- endif %}
43
+ {%- if loop.index0 > ns.last_query_index %}
44
+ {%- if loop.last or (not loop.last and reasoning_content) %}
45
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
46
+ {%- else %}
47
+ {{- '<|im_start|>' + message.role + '\n' + content }}
48
+ {%- endif %}
49
+ {%- else %}
50
+ {{- '<|im_start|>' + message.role + '\n' + content }}
51
+ {%- endif %}
52
+ {%- if message.tool_calls %}
53
+ {%- for tool_call in message.tool_calls %}
54
+ {%- if (loop.first and content) or (not loop.first) %}
55
+ {{- '\n' }}
56
+ {%- endif %}
57
+ {%- if tool_call.function %}
58
+ {%- set tool_call = tool_call.function %}
59
+ {%- endif %}
60
+ {{- '<tool_call>\n{"name": "' }}
61
+ {{- tool_call.name }}
62
+ {{- '", "arguments": ' }}
63
+ {%- if tool_call.arguments is string %}
64
+ {{- tool_call.arguments }}
65
+ {%- else %}
66
+ {{- tool_call.arguments | tojson }}
67
+ {%- endif %}
68
+ {{- '}\n</tool_call>' }}
69
+ {%- endfor %}
70
+ {%- endif %}
71
+ {{- '<|im_end|>\n' }}
72
+ {%- elif message.role == "tool" %}
73
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
74
+ {{- '<|im_start|>user' }}
75
+ {%- endif %}
76
+ {{- '\n<tool_response>\n' }}
77
+ {{- content }}
78
+ {{- '\n</tool_response>' }}
79
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
80
+ {{- '<|im_end|>\n' }}
81
+ {%- endif %}
82
+ {%- endif %}
83
+ {%- endfor %}
84
+ {%- if add_generation_prompt %}
85
+ {{- '<|im_start|>assistant\n' }}
86
+ {%- if enable_thinking is defined and enable_thinking is false %}
87
+ {{- '<think>\n\n</think>\n\n' }}
88
+ {%- endif %}
89
+ {%- endif %}