nielsr HF Staff commited on
Commit
fb89c59
ยท
verified ยท
1 Parent(s): 729b39e

Add pipeline tag and usage instructions

Browse files

This PR adds the `pipeline_tag` to ensure the model can be found at https://huggingface.co/models?pipeline_tag=text-ranking. It also adds usage instructions, installation instructions, training details and evaluation details from the GitHub README.

Files changed (1) hide show
  1. README.md +281 -3
README.md CHANGED
@@ -1,10 +1,288 @@
1
  ---
2
- library_name: transformers
3
- license: apache-2.0
4
  language:
5
  - en
 
 
 
6
  ---
7
 
8
  The base of this model is [Llama-3.2-3B-Instruct](https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct), using TopiOCQA as the training data, and the training method is ConvSearch-R1.
9
 
10
- The code is available [here](https://github.com/BeastyZ/ConvSearch-R1). Please refer to the paper [here](https://arxiv.org/abs/2505.15776).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
 
 
2
  language:
3
  - en
4
+ library_name: transformers
5
+ license: apache-2.0
6
+ pipeline_tag: text-ranking
7
  ---
8
 
9
  The base of this model is [Llama-3.2-3B-Instruct](https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct), using TopiOCQA as the training data, and the training method is ConvSearch-R1.
10
 
11
+ The code is available [here](https://github.com/BeastyZ/ConvSearch-R1). Please refer to the paper [here](https://arxiv.org/abs/2505.15776).
12
+
13
+ # ๐Ÿ’ป Usage
14
+ ```python
15
+ from vllm import LLM, SamplingParams
16
+
17
+ example = """Given a query and its context, you must first think about the reasoning process in the mind to decontextualize the query by resolving \
18
+ coreference and omission issues. Then, provide the user with a rewrite that retains its original meaning and is as informative as possible to help \
19
+ search engines retrieve relevant documents effectively. The reasoning process and rewrite should be enclosed within <think> </think> and <rewrite> </rewrite> tags, respectively, i.e., \
20
+ <think> reasoning process here </think>
21
+ <rewrite> rewrite here </rewrite>.
22
+
23
+ ### Context Begin ###
24
+ Q1: what can you tell me about Gaelic Ireland Dress?
25
+ A1: The common clothing amongst the Gaelic Irish consisted of a woollen semi circular cloak worn over a loose-fitting, long-sleeved tunic made of linen.
26
+ Q2: did they wear any other clothing distinction?
27
+ A2: For men the lรฉine reached to their ankles but was hitched up by means of a woven belt. The lรฉine was hitched up to knee level.
28
+ Q3: Did they have any other distinction in their clothing?
29
+ A3: The cloak was simply thrown over both shoulders or sometimes over only one.
30
+ Q4: Any other distinction for the women?
31
+ A4: Women wore the lรฉine at full length, rather than knee length for men.
32
+ Q5: did they wear their hair up or down?
33
+ A5: Women invariably grew their hair long and, as in other European cultures, this custom was also common among the men.
34
+ Q6: What other things did they wear?
35
+ A6: A short, tight-fitting jacket became popular later on and the Irish commonly wore hoods at that time
36
+ ### Context End ###
37
+
38
+ Query: What is a leine?
39
+ Rewrite:"""
40
+
41
+ model_name_or_path = 'BeastyZ/Qwen2.5-3B-ConvSearch-R1-TopiOCQA'
42
+
43
+ sampling_params = SamplingParams(
44
+ temperature=0.7,
45
+ max_tokens=4096
46
+ )
47
+ llm = LLM(
48
+ model=model_name_or_path,
49
+ tensor_parallel_size=1,
50
+ enforce_eager=False,
51
+ gpu_memory_utilization=0.8,
52
+ dtype='bfloat16',
53
+ )
54
+ conv = [
55
+ {
56
+ 'role': 'user',
57
+ 'content': example,
58
+ }
59
+ ]
60
+ outputs = llm.chat(conv, sampling_params, add_generation_prompt=True)
61
+ for output in outputs:
62
+ generated_text = output.outputs[0].text
63
+ print(generated_text)
64
+
65
+ """ Reference Answer:
66
+ <think> The user is asking for a definition or explanation of the term "lรฉine," which is mentioned in the previous context. \
67
+ The term "lรฉine" refers to a specific type of garment worn by the Gaelic Irish. Based on the previous context, \
68
+ the lรฉine was described as a linen tunic worn by both men and women. The query seeks a definition or explanation of this term. </think>
69
+ <rewrite> What is a lรฉine? The lรฉine is a traditional Irish garment, a loose-fitting, long-sleeved tunic made of linen. \
70
+ It was a common piece of clothing among the Gaelic Irish. The term "lรฉine" is derived from the Old Irish word "lรญn," meaning "garment." \
71
+ It typically reached to the ankles for men and at full length for women. The lรฉine was a significant part of the Gaelic Irish's clothing, \
72
+ often worn with a cloak and other accessories. </rewrite>
73
+ """
74
+
75
+ ```
76
+
77
+ # ๐Ÿ› ๏ธ Installation
78
+ Since training process involves retrieval and RL, to avoid interference between environments, retrieval and RL use their own separate environments.
79
+
80
+ Setup for retrieval
81
+ ```bash
82
+ git clone https://github.com/BeastyZ/ConvSearch-R1.git
83
+ cd ConvSearch-R1
84
+
85
+ conda create -n retriever python=3.10
86
+ conda activate retriever
87
+
88
+ pip3 install -r requirements_retriever.txt
89
+ ```
90
+
91
+ Setup for RL using verl
92
+ ```bash
93
+ conda create -n verl python=3.9
94
+ conda create verl
95
+
96
+ pip3 install torch==2.4.0 --index-url https://download.pytorch.org/whl/cu124
97
+ pip3 install flash-attn --no-build-isolation
98
+
99
+ cd verl
100
+ pip3 install -e .
101
+ ```
102
+
103
+ # ๐Ÿ›œ Server
104
+ Before training, please deploy the retriever first, and then paste the access address of the retriever into the training script. For deployment methods, please refer to [serve.sh](./src/retrieval/serve.sh). Then test its connectivity with the following code.
105
+ ```python
106
+ import requests
107
+
108
+ # URL for your local FastAPI server
109
+ url = "http://127.0.0.1:YOUR_PORT/retrieve"
110
+
111
+ test_rewrite = """Did Harry Hopkins work with other people to publicize and defend New Deal relief programs? Hopkins began important roles in New Deal programs such as Federal Emergency Relief Administration (FERA) in 1933. This period saw Hopkins as federal relief administrator. As part of his work, Hopkins supervised programs like FERA and Civil Works Administration (CWA). In his position, Hopkins was involved from 1933 to 1935 with these efforts. After joining Roosevelt's administration, Hopkins was extensively involved in relief projects. By the late 1930s, as he was fighting stomach cancer, FDR began to train Hopkins as a possible successor. Hopkins also supervised the Works Progress Administration (WPA). Throughout Hopkins' career, was he involved with publicizing and defending New Deal programs? In an effort to publicize and defend these programs, did Hopkins work with any particular groups or individuals? Some reports suggest Hopkins himself was a key public figure in promoting New Deal programs and sometimes worked with respected experts. Historically, there is evidence that Hopkins worked with and supported other government and public figures in advocating for FDR's New Deal programs. Additionally, came Hopkins' work with publicizing these programs include working with others in his capacity as federal relief administrator or in running various programs like FERA, FDR training him as potential successor, and his involvement with relief programs during the Great Depression. Did Hopkins collaborate with others to promote and protect New Deal programs, and when did these efforts start? Did Hopkins work with individuals like Edwin Campell, who helped to develop the New Deal and attempted to publicize government programs to the public as part of this role? How else did Hopkins work with these programs to ensure public support?"""
112
+ test_qid = "QReCC-Train_938_7"
113
+ # Example payload
114
+ payload = {
115
+ # for topiocqa
116
+ # "queries": ["what was australia's contribution to the battle of normandy?", "was the battle fought in australia?"],
117
+ # "query_ids": ['topiocqa-train_1_1', 'topiocqa-train_1_2'], # gold id: 5498209, 5498207
118
+
119
+ # for qrecc
120
+ "queries": [test_rewrite, "How did Van Halen reunite with Roth?", "Where was he born?", 'Who is the new chairman of National Scheduled Tribes Commision', 'For how long was the country devided before it became united'],
121
+ "query_ids": [test_qid, 'QReCC-Train_2_1', 'QReCC-Train_5_1', 'QReCC-Train_10822_1', 'QReCC-Train_10810_3'], # gold id: 54537936, 54572406, 54302883
122
+
123
+ "topk": 100,
124
+ "return_scores": False
125
+ }
126
+
127
+ # Send POST request
128
+ response = requests.post(url, json=payload)
129
+
130
+ # Raise an exception if the request failed
131
+ response.raise_for_status()
132
+
133
+ # Get the JSON response
134
+ retrieved_data = response.json()
135
+
136
+ print("Response from server:")
137
+ print(retrieved_data)
138
+ ```
139
+
140
+ # ๐Ÿ”ฅ Training
141
+ Verl only supports data in **Parquet** format, and both the data for SFT and GRPO must follow this format.
142
+
143
+ For the code to preprocess the SFT and GRPO data, please refer to directory [data_preprocess](./verl/examples/data_preprocess).
144
+
145
+ ## SFT
146
+ For more examples about SFT, see [SFT](./verl/examples/sft).
147
+ ```bash
148
+ conda activate verl
149
+
150
+ set -x
151
+
152
+ nproc_per_node=8
153
+ save_path=ckpt/sft/qrecc/llama3.2-3b-it_self
154
+ export WANDB_API_KEY="your_wandb_key"
155
+ HOME=path/to/your/work/home
156
+
157
+ torchrun --standalone --nnodes=1 --nproc_per_node=$nproc_per_node \
158
+ -m verl.trainer.fsdp_sft_trainer \
159
+ data.train_files=$HOME/data/qrecc/sft/train_llama3.2-3b-it_self.parquet \
160
+ data.val_files=$HOME/data/qrecc/sft/test_llama3.2-3b-it_self.parquet \
161
+ data.prompt_key=extra_info \
162
+ data.response_key=extra_info \
163
+ +data.prompt_dict_keys=['prompt'] \
164
+ +data.response_dict_keys=['answer'] \
165
+ data.train_batch_size=64 \
166
+ data.micro_batch_size_per_gpu=8 \
167
+ data.max_length=3072 \
168
+ data.truncation=right \
169
+ model.partial_pretrain=path/to/your/model \
170
+ model.enable_gradient_checkpointing=True \
171
+ trainer.default_local_dir=$save_path \
172
+ trainer.project_name=llama3.2-3b-it_qrecc-sft \
173
+ trainer.experiment_name=llama3.2-3b-it_self_epoch2 \
174
+ trainer.total_epochs=2 \
175
+ trainer.logger=['wandb'] \
176
+ trainer.default_hdfs_dir=null
177
+ ```
178
+ ## GRPO
179
+ For more examples about GRPO, see [GRPO](./verl/examples/grpo_trainer).
180
+ ```bash
181
+ conda activate verl
182
+
183
+ #!/bin/bash
184
+ set -x
185
+
186
+ export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
187
+ export VLLM_ATTENTION_BACKEND=XFORMERS
188
+ export WANDB_API_KEY="your_wandb_key"
189
+ DATE=$(date "+%y%m%d%H%M")
190
+ HOME=path/to/your/work/home
191
+
192
+ PROJECT_NAME=verl_grpo_rewrite_qrecc
193
+ EXPERIMENT_NAME=llama3.2_3b_it_self_bs128_maxlen1024_lr1e-6_warmup100_n8_temp0.7_epoch9_r9_v3
194
+ export RETRIEVER_URL="your_retrieval_server_url"
195
+
196
+
197
+ python3 -m verl.trainer.main_ppo \
198
+ algorithm.adv_estimator=grpo \
199
+ data.train_files=$HOME/data/qrecc/train_v3.parquet \
200
+ data.val_files=$HOME/data/qrecc/test_v3.parquet \
201
+ data.train_batch_size=128 \
202
+ data.max_prompt_length=1536 \
203
+ data.max_response_length=1024 \
204
+ data.filter_overlong_prompts=True \
205
+ data.truncation='error' \
206
+ actor_rollout_ref.model.path=path/to/your/sft/model \
207
+ actor_rollout_ref.actor.optim.lr=1e-6 \
208
+ actor_rollout_ref.actor.optim.lr_warmup_steps=100 \
209
+ actor_rollout_ref.model.use_remove_padding=True \
210
+ actor_rollout_ref.actor.ppo_mini_batch_size=128 \
211
+ actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=8 \
212
+ actor_rollout_ref.actor.use_kl_loss=True \
213
+ actor_rollout_ref.actor.kl_loss_coef=0.001 \
214
+ actor_rollout_ref.actor.kl_loss_type=low_var_kl \
215
+ actor_rollout_ref.model.enable_gradient_checkpointing=True \
216
+ actor_rollout_ref.actor.fsdp_config.param_offload=False \
217
+ actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
218
+ actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=32 \
219
+ actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
220
+ actor_rollout_ref.rollout.name=vllm \
221
+ actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
222
+ actor_rollout_ref.rollout.n=8 \
223
+ actor_rollout_ref.rollout.temperature=0.7 \
224
+ actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=32 \
225
+ actor_rollout_ref.ref.fsdp_config.param_offload=True \
226
+ algorithm.kl_ctrl.kl_coef=0.001 \
227
+ trainer.critic_warmup=0 \
228
+ trainer.logger=['wandb'] \
229
+ trainer.project_name=$PROJECT_NAME \
230
+ trainer.experiment_name=$EXPERIMENT_NAME \
231
+ trainer.n_gpus_per_node=8 \
232
+ trainer.nnodes=1 \
233
+ trainer.save_freq=100 \
234
+ trainer.test_freq=-1 \
235
+ trainer.default_local_dir=ckpt/qrecc/dense/$EXPERIMENT_NAME \
236
+ trainer.total_epochs=9 \
237
+ reward_model.reward_manager=rewrite_r1 \
238
+ custom_reward_function.path=verl/verl/utils/reward_score/rewrite_r1.py \
239
+ retriever.topk=100 $@ 2>&1 | tee logs/${DATE}_${EXPERIMENT_NAME}.log
240
+ ```
241
+
242
+ # ๐Ÿค– Inference
243
+ We need to collect data for evaluation. For more examples about inference, see [infer](./src/infer).
244
+ ```bash
245
+ conda activate verl
246
+
247
+ python3 src/infer/infer.py \
248
+ --model_name_or_path path/to/your/model \
249
+ --model_name ConvSearch-R1 \
250
+ --dp_size 8 \
251
+ --gpus_per_dp_rank 1 \
252
+ --temperature 0.7 \
253
+ --input_path data/topiocqa/dev.json \
254
+ --output_path path/to/your/output
255
+ ```
256
+
257
+ # ๐Ÿ‘จโ€โš–๏ธ Evaluation
258
+ For more details about evaluation, see [eval](./src/eval).
259
+ ```bash
260
+ conda activate retriever
261
+
262
+ python3 src/eval/get_metrics_using_ance.py \
263
+ --pretrained_encoder_path path/to/your/dense/retriever \
264
+ --test_file_path path/to/rewrite/file/gennerated/by/rewriter \
265
+ --passage_embeddings_dir_path "embedding/ance_topiocqa" \
266
+ --qrel_output_dir data/topiocqa/qrel/dense \
267
+ --output_trec_file filename/to/save/trec/file \
268
+ --trec_gold_qrel_file_path data/topiocqa/dev.trec \
269
+ --n_gpu 2 \
270
+ --test_type rewrite
271
+ ```
272
+
273
+ # ๐Ÿ™ Acknowledgement
274
+ We use verl for SFT and GRPO: https://github.com/volcengine/verl
275
+
276
+
277
+ # ๐Ÿ‘‹ Citation
278
+ ```
279
+ @misc{zhu2025convsearchr1enhancingqueryreformulation,
280
+ title={ConvSearch-R1: Enhancing Query Reformulation for Conversational Search with Reasoning via Reinforcement Learning},
281
+ author={Changtai Zhu and Siyin Wang and Ruijun Feng and Kai Song and Xipeng Qiu},
282
+ year={2025},
283
+ eprint={2505.15776},
284
+ archivePrefix={arXiv},
285
+ primaryClass={cs.CL},
286
+ url={https://arxiv.org/abs/2505.15776},
287
+ }
288
+ ```