Mungert commited on
Commit
0cbc266
·
verified ·
1 Parent(s): 2e78e07

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +353 -0
README.md ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ datasets:
4
+ - Tongyi-Zhiwen/DocQA-RL-1.6K
5
+ base_model:
6
+ - deepseek-ai/DeepSeek-R1-Distill-Qwen-32B
7
+ tags:
8
+ - long-context
9
+ - large-reasoning-model
10
+ pipeline_tag: text-generation
11
+ library_name: transformers
12
+ ---
13
+
14
+ # QwenLong-L1: Towards Long-Context Large Reasoning Models with Reinforcement Learning
15
+ <p align="center" width="100%">
16
+ </p>
17
+
18
+ <div id="top" align="center">
19
+
20
+ -----------------------------
21
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
22
+ [![arXiv](https://img.shields.io/badge/arXiv-2505.17667-b31b1b.svg)](https://arxiv.org/abs/2505.17667)
23
+ [![GitHub](https://img.shields.io/badge/GitHub-QwenLongL1-4b32c3?logo=github)](https://github.com/Tongyi-Zhiwen/QwenLong-L1)
24
+ [![ModelScope](https://img.shields.io/badge/🤖%20ModelScope-purple)](https://modelscope.cn/models/iic/QwenLong-L1-32B)
25
+ [![HuggingFace](https://img.shields.io/badge/🤗%20HuggingFace-yellow)](https://huggingface.co/Tongyi-Zhiwen/QwenLong-L1-32B)
26
+
27
+ <!-- **Authors:** -->
28
+
29
+ _**Fanqi Wan, Weizhou Shen, Shengyi Liao, Yingcheng Shi, Chenliang Li,**_
30
+
31
+ _**Ziyi Yang, Ji Zhang, Fei Huang, Jingren Zhou, Ming Yan**_
32
+
33
+
34
+ <!-- **Affiliations:** -->
35
+
36
+
37
+ _Tongyi Lab, Alibaba Group_
38
+
39
+ <p align="center">
40
+ <img src="./assets/fig1.png" width="100%"> <br>
41
+ </p>
42
+
43
+
44
+ </div>
45
+
46
+ ## 🎉 News
47
+
48
+ - **May 28, 2025:** 🔥 We release [🤗 QwenLong-L1-32B-AWQ](https://huggingface.co/Tongyi-Zhiwen/QwenLong-L1-32B-AWQ), which has undergone AWQ int4 quantization using the ms-swift framework.
49
+
50
+ - **May 26, 2025:** 🔥 We release [🤗 QwenLong-L1-32B](https://huggingface.co/Tongyi-Zhiwen/QwenLong-L1-32B), which is the first long-context LRM trained with reinforcement learning for long-context reasoning. Experiments on seven long-context DocQA benchmarks demonstrate that **QwenLong-L1-32B outperforms flagship LRMs like OpenAI-o3-mini and Qwen3-235B-A22B, achieving performance on par with Claude-3.7-Sonnet-Thinking**, demonstrating leading performance among state-of-the-art LRMs.
51
+
52
+ - **May 26, 2025:** 🔥 We release [🤗 DocQA-RL-1.6K](https://huggingface.co/datasets/Tongyi-Zhiwen/DocQA-RL-1.6K), which is a specialized RL training dataset comprising 1.6K document question answering (DocQA) problems spanning mathematical, logical, and multi-hop reasoning domains.
53
+
54
+
55
+ ## 📚 Introduction
56
+
57
+ In this work, we propose QwenLong-L1, a novel reinforcement learning (RL) framework designed to facilitate the transition of LRMs from short-context proficiency to robust long-context generalization. In our preliminary experiments, we illustrate the differences between the training dynamics of short-context and long-context reasoning RL.
58
+
59
+ <p align="center">
60
+ <img src="./assets/fig2.png" width="100%"> <br>
61
+ </p>
62
+
63
+ Our framework enhances short-context LRMs through progressive context scaling during RL training. The framework comprises three core components: a warm-up supervised fine-tuning (SFT) phase to initialize a robust policy, a curriculum-guided RL phase that facilitates stable adaptation from short to long contexts, and a difficulty-aware retrospective sampling mechanism that adjusts training complexity across stages to incentivize policy exploration. Leveraging recent RL algorithms, including GRPO and DAPO, our framework integrates hybrid reward functions combining rule-based and model-based binary outcome rewards to balance precision and recall. Through strategic utilization of group relative advantages during policy optimization, it guides LRMs to learn effective reasoning patterns essential for robust long-context grounding and superior reasoning capabilities.
64
+
65
+ <p align="center">
66
+ <img src="./assets/fig3.png" width="100%"> <br>
67
+ </p>
68
+
69
+
70
+ ## 🎯 Model Release
71
+
72
+ We release [🤗 QwenLong-L1-32B](https://huggingface.co/Tongyi-Zhiwen/QwenLong-L1-32B), which is the first long-context LRM trained with reinforcement learniing for long-context reasoning. Experiments on seven long-context DocQA benchmarks demonstrate that **QwenLong-L1-32B outperforms flagship LRMs like OpenAI-o3-mini and Qwen3-235B-A22B, achieving performance on par with Claude-3.7-Sonnet-Thinking**, demonstrating leading performance among state-of-the-art LRMs.
73
+
74
+ Here are the evaluation results.
75
+
76
+ <p align="center">
77
+ <img src="./assets/tab4.png" width="100%"> <br>
78
+ </p>
79
+
80
+ ## 🛠️ Requirements
81
+
82
+ ```bash
83
+ # Create the conda environment
84
+ conda create -n qwenlongl1 python==3.10
85
+ conda activate qwenlongl1
86
+
87
+ # Install requirements
88
+ pip3 install -r requirements.txt
89
+
90
+ # Install verl
91
+ cd verl
92
+ pip3 install -e .
93
+
94
+ # Install vLLM
95
+ pip3 install vllm==0.7.3
96
+
97
+ # Install flash-attn
98
+ pip3 install flash-attn --no-build-isolation
99
+ ```
100
+
101
+ ## 🚀 Quick Start
102
+
103
+ Here's how you can run the model using the 🤗 Transformers:
104
+
105
+ ```python
106
+ from transformers import AutoModelForCausalLM, AutoTokenizer
107
+
108
+ model_name = "Tongyi-Zhiwen/QwenLong-L1-32B"
109
+
110
+ # load the tokenizer and the model
111
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
112
+ model = AutoModelForCausalLM.from_pretrained(
113
+ model_name,
114
+ torch_dtype="auto",
115
+ device_map="auto"
116
+ )
117
+
118
+ # prepare the model input
119
+ template = """Please read the following text and answer the question below.
120
+
121
+ <text>
122
+ $DOC$
123
+ </text>
124
+
125
+ $Q$
126
+
127
+ Format your response as follows: "Therefore, the answer is (insert answer here)"."""
128
+ context = "<YOUR_CONTEXT_HERE>"
129
+ question = "<YOUR_QUESTION_HERE>"
130
+ prompt = template.replace('$DOC$', context.strip()).replace('$Q$', question.strip())
131
+ messages = [
132
+ # {"role": "system", "content": "You are QwenLong-L1, created by Alibaba Tongyi Lab. You are a helpful assistant."}, # Use system prompt to define identity when needed.
133
+ {"role": "user", "content": prompt}
134
+ ]
135
+ text = tokenizer.apply_chat_template(
136
+ messages,
137
+ tokenize=False,
138
+ add_generation_prompt=True
139
+ )
140
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
141
+
142
+ # conduct text completion
143
+ generated_ids = model.generate(
144
+ **model_inputs,
145
+ max_new_tokens=10000,
146
+ temperature=0.7,
147
+ top_p=0.95
148
+ )
149
+ output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
150
+
151
+ # parsing thinking content
152
+ try:
153
+ # rindex finding 151649 (</think>)
154
+ index = len(output_ids) - output_ids[::-1].index(151649)
155
+ except ValueError:
156
+ index = 0
157
+
158
+ thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
159
+ content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
160
+
161
+ print("thinking content:", thinking_content)
162
+ print("content:", content)
163
+ ```
164
+
165
+ ## ♾️ Processing Long Documents
166
+
167
+ For input where the total length (including both input and output) significantly exceeds 32,768 tokens, we recommend using RoPE scaling techniques to handle long texts effectively. We have validated the model's performance on context lengths of up to 131,072 tokens using the [YaRN](https://arxiv.org/abs/2309.00071) method.
168
+
169
+ YaRN is currently supported by several inference frameworks, e.g., `transformers` and `llama.cpp` for local use, `vllm` and `sglang` for deployment. In general, there are two approaches to enabling YaRN for supported frameworks:
170
+
171
+ - Modifying the model files:
172
+ In the `config.json` file, add the `rope_scaling` fields:
173
+ ```json
174
+ {
175
+ ...,
176
+ "rope_scaling": {
177
+ "rope_type": "yarn",
178
+ "factor": 4.0,
179
+ "original_max_position_embeddings": 32768
180
+ }
181
+ }
182
+ ```
183
+ For `llama.cpp`, you need to regenerate the GGUF file after the modification.
184
+ - Passing command line arguments:
185
+
186
+ For `vllm`, you can use
187
+ ```shell
188
+ vllm serve ... --rope-scaling '{"rope_type":"yarn","factor":4.0,"original_max_position_embeddings":32768}' --max-model-len 131072
189
+ ```
190
+ For `sglang`, you can use
191
+ ```shell
192
+ python -m sglang.launch_server ... --json-model-override-args '{"rope_scaling":{"rope_type":"yarn","factor":4.0,"original_max_position_embeddings":32768}}'
193
+ ```
194
+ For `llama-server` from `llama.cpp`, you can use
195
+ ```shell
196
+ llama-server ... --rope-scaling yarn --rope-scale 4 --yarn-orig-ctx 32768
197
+ ```
198
+ > [!IMPORTANT]
199
+ > If you encounter the following warning
200
+ > ```
201
+ > Unrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}
202
+ > ```
203
+ > please upgrade `transformers>=4.51.0`.
204
+
205
+ > [!NOTE]
206
+ > All the notable open-source frameworks implement static YaRN, which means the scaling factor remains constant regardless of input length, **potentially impacting performance on shorter texts.**
207
+ > We advise adding the `rope_scaling` configuration only when processing long contexts is required.
208
+ > It is also recommended to modify the `factor` as needed. For example, if the typical context length for your application is 65,536 tokens, it would be better to set `factor` as 2.0.
209
+
210
+ > [!NOTE]
211
+ If the average context length does not exceed 32,768 tokens, we do not recommend enabling YaRN in this scenario, as it may potentially degrade model performance.
212
+
213
+ ## 🗂️ Dataset
214
+
215
+ To construct a challenging RL dataset for verifiable long-context reasoning, we develop [🤗 DocQA-RL-1.6K](https://huggingface.co/datasets/Tongyi-Zhiwen/DocQA-RL-1.6K), which comprises 1.6K DocQA problems across three reasoning domains:
216
+
217
+ (1) Mathematical Reasoning: We use 600 problems from the DocMath dataset, requiring numerical reasoning across long and specialized documents such as financial reports. For DocMath, we sample 75% items from each subset from its valid split for training and 25% for evaluation;
218
+
219
+ (2) Logical Reasoning: We employ DeepSeek-R1 to synthesize 600 multi-choice questions requiring logic analysis of real-world documents spanning legal, financial, insurance, and production domains from our curated collection;
220
+
221
+ (3) Multi-Hop Reasoning: We sample 200 examples from MultiHopRAG and 200 examples from Musique, emphasizing cross-document reasoning.
222
+
223
+ Please download and put the following datasets in `./datasets/` for training and evaluation.
224
+
225
+ RL training data: [🤗 DocQA-RL-1.6K](https://huggingface.co/datasets/Tongyi-Zhiwen/DocQA-RL-1.6K).
226
+
227
+ Evaluation data: [🤗 docmath](https://huggingface.co/datasets/Tongyi-Zhiwen/docmath), [🤗 frames](https://huggingface.co/datasets/Tongyi-Zhiwen/frames), [🤗 longbench](https://huggingface.co/datasets/Tongyi-Zhiwen/longbench).
228
+
229
+ ## 💻 Training
230
+
231
+ We provide the basic demo training code for single stage RL traininig with DAPO.
232
+
233
+ First, we should start a local verifier.
234
+ ```bash
235
+ export CUDA_VISIBLE_DEVICES=0
236
+
237
+ vllm serve "Qwen/Qwen2.5-1.5B-Instruct" \
238
+ --host 0.0.0.0 \
239
+ --port 23547
240
+ ```
241
+
242
+ Then, we start RL training with 4 nodes.
243
+ ```bash
244
+ export PROJ_DIR="<YOUR_PROJ_DIR_HERE>"
245
+ export MASTER_IP="<YOUR_MASTER_IP_HERE>" # ray master ip
246
+ export NNODES=4 # total GPU nodes
247
+ export NODE_RANK=${RANK} # rank of current node
248
+ export PORT=6382
249
+ export WANDB_API_KEY="<YOUR_WANDB_API_KEY_HERE>"
250
+ export WANDB_PROJECT="QwenLong-L1"
251
+ export LLM_JUDGE=Y # 'Y': LLM JUDGE, 'N': RULE BASED
252
+ export VLLM_ATTENTION_BACKEND=FLASH_ATTN
253
+ # verifier
254
+ export VERIFIER_PATH="Qwen/Qwen2.5-1.5B-Instruct"
255
+ export VERIFIER_HOST="<YOUR_VERIFIER_HOST_HERE>"
256
+ export VERIFIER_PORT="23547"
257
+
258
+ ray_start_retry() {
259
+ while true; do
260
+ ray start --address="${MASTER_IP}:${PORT}"
261
+ if [ $? -eq 0 ]; then
262
+ break
263
+ fi
264
+ echo "Failed to connect to master, retrying in 5 seconds..."
265
+ sleep 5
266
+ done
267
+ }
268
+
269
+ check_ray_status() {
270
+ until ray status >/dev/null 2>&1; do
271
+ echo "Waiting for Ray cluster to be ready..."
272
+ sleep 5
273
+ done
274
+ }
275
+
276
+ if [ "$RANK" == "0" ]; then
277
+ echo "Starting HEAD node..."
278
+ ray start --head --port=${PORT}
279
+
280
+ check_ray_status
281
+ echo "Ray head node started successfully"
282
+
283
+ else
284
+ echo "Starting WORKER node..."
285
+ ray_start_retry
286
+
287
+ check_ray_status
288
+ echo "Successfully joined Ray cluster"
289
+ fi
290
+
291
+ if [ "$RANK" == "0" ]; then
292
+ bash ${PROJ_DIR}/scripts/rl_4nodes_dapo.sh 2>&1 | tee ${PROJ_DIR}/logs/rl_log_$(date +%Y%m%d_%H%M%S).txt &
293
+ else
294
+ sleep 30d
295
+ fi
296
+
297
+ wait
298
+ ```
299
+
300
+ ## 📊 Evaluation
301
+
302
+ We conduct evaluation on seven long-context DocQA benchmarks, including multi-hop reasoning benchmarks such as 2WikiMultihopQA, HotpotQA, Musique, NarrativeQA, Qasper, and Frames as well as mathematical reasoning benchmarks like DocMath. We report the maximum of exact match and LLM-judged accuracy as the final score, aligned with the reward function in our RL training process. We use DeepSeek-V3 as the judge model with a temperature of 0.0 to provide a reliable evaluation.
303
+
304
+ ```bash
305
+ # Step 1. Serve the model for evaluation
306
+ export CUDA_VISIBLE_DEVICES="0,1,2,3,4,5,6,7"
307
+ MODEL_NAME="QwenLong-L1-32B"
308
+ MODEL_PATH="Tongyi-Zhiwen/QwenLong-L1-32B"
309
+
310
+ vllm serve ${MODEL_PATH} \
311
+ --port 23547 \
312
+ --api-key "token-abc123" \
313
+ --tensor-parallel-size 8 \
314
+ --gpu-memory-utilization 0.95 \
315
+ --max_model_len 131072 \
316
+ --trust-remote-code
317
+
318
+ # Step 2. Generate model responses for each dataset
319
+ export SERVE_HOST="<YOUR_SERVE_HOST_HERE>" # e.g., 127.0.0.1
320
+ export SERVE_PORT="23547"
321
+ PROJ_DIR="<YOUR_PROJ_DIR_HERE>"
322
+ DATA="<YOUR_DATA_HERE>" # e.g., docmath, frames, 2wikimqa, hotpotqa, musique, narrativeqa, pasper
323
+ python ${PROJ_DIR}/eval/${DATA}.py \
324
+ --save_dir "${PROJ_DIR}/eval/results/${DATA}" \
325
+ --save_file "${MODEL_NAME}" \
326
+ --model "${MODEL_PATH}" \
327
+ --tokenizer "${MODEL_PATH}" \
328
+ --n_proc 16 \
329
+ --api "openai"
330
+
331
+ # Step 3. Verify model responses for each dataset
332
+ export VERIFIER_API="<YOUR_API_KEY_HERE>"
333
+ export VERIFIER_URL="https://api.deepseek.com/v1"
334
+ PROJ_DIR="<YOUR_PROJ_DIR_HERE>"
335
+ DATA="<YOUR_DATA_HERE>" # e.g., docmath, frames, 2wikimqa, hotpotqa, musique, narrativeqa, pasper
336
+ python ${PROJ_DIR}/eval/${DATA}_verify.py \
337
+ --save_dir "${PROJ_DIR}/results/${DATA}" \
338
+ --save_file "${MODEL_NAME}" \
339
+ --judge_model "deepseek-chat" \
340
+ --batch_size 20
341
+ ```
342
+
343
+ ## 📝 Citation
344
+
345
+ If you find this work is relevant with your research or applications, please feel free to cite our work!
346
+ ```
347
+ @article{wan2025qwenlongl1,
348
+ title={QwenLong-L1: : Towards Long-Context Large Reasoning Models with Reinforcement Learning},
349
+ author={Fanqi Wan, Weizhou Shen, Shengyi Liao, Yingcheng Shi, Chenliang Li, Ziyi Yang, Ji Zhang, Fei Huang, Jingren Zhou, Ming Yan},
350
+ journal={arXiv preprint arXiv:2505.17667},
351
+ year={2025}
352
+ }
353
+ ```