Views
No views yet
git clone git@github.com:hiyouga/LLaMA-Factory.git1/home/user/anaconda3/envs/llama-fac/lib/python3.11/site-packages/transformers/loss/loss_utils.py
2
3↕️
4
5to_replace/transformers/loss/loss_utils.pyNote: The version of the transformers library corresponding to this code is 4.46.1.
1export special_token_loss=F # Set to F to disable loss calculation for special tokens (weight = 0)
2export special_token_loss=T # Set to T to enable loss calculation for special tokens (default weight = 1)
3export special_token_loss=Tn # Set the loss weight for special tokens, where n is a float representing the specified weight value
4# For example: export special_token_loss=T10, which sets the loss weight for special tokens to 10./easyr1 directory. For environment configuration, please refer to the EasyR1 documentation../evaluation directory. For environment configuration, please refer to the Qwen2.5-Math documentation../easyr1 and ./evaluation directories. We need to modify the source code of vllm to support the insertion of special tokens during inference:worker/model_runner.py file in the vllm library and replace it:1/home/user/anaconda3/envs/easyr1/lib/python3.11/site-packages/vllm/worker/model_runner.py
2&
3/home/user/anaconda3/envs/QMath/lib/python3.11/site-packages/vllm/worker/model_runner.py
4
5↕️
6
7to_replace/vllm/worker/model_runner.pyNote: The version of the vllm library corresponding to this code is 0.7.3.
...vllm/worker/model_runner.py file. The original version is as follows:1
2 @torch.inference_mode()
3 def execute_model(
4 self,
5 model_input: ModelInputForGPUWithSamplingMetadata,
6 kv_caches: List[torch.Tensor],
7 intermediate_tensors: Optional[IntermediateTensors] = None,
8 num_steps: int = 1,
9 ) -> Optional[Union[List[SamplerOutput], IntermediateTensors]]:
10 if num_steps > 1:
11 raise ValueError("num_steps > 1 is not supported in ModelRunner")
12
13 ... more code ...
14 ... more code ...
15
16 # Compute the logits in the last pipeline stage.
17 if not get_pp_group().is_last_rank:
18 return hidden_or_intermediate_states
19
20 logits = self.model.compute_logits(hidden_or_intermediate_states,
21 model_input.sampling_metadata)
22
23 if not self.is_driver_worker:
24 return []
25
26 # Sample the next token.
27 output: SamplerOutput = self.model.sample(
28 logits=logits,
29 sampling_metadata=model_input.sampling_metadata,
30 )
31
32
33
34
35 if self.return_hidden_states:
36 # we only need to pass hidden states of most recent token
37 assert model_input.sampling_metadata is not None
38 indices = model_input.sampling_metadata.selected_token_indices
39 if model_input.is_prompt:
40 hidden_states = hidden_or_intermediate_states.index_select(
41 0, indices)
42 elif decode_meta.use_cuda_graph:
43 hidden_states = hidden_or_intermediate_states[:len(indices)]
44 else:
45 hidden_states = hidden_or_intermediate_states
46
47 output.hidden_states = hidden_states
48
49 return [output]1
2 @torch.inference_mode()
3 def execute_model(
4 self,
5 model_input: ModelInputForGPUWithSamplingMetadata,
6 kv_caches: List[torch.Tensor],
7 intermediate_tensors: Optional[IntermediateTensors] = None,
8 num_steps: int = 1,
9 ) -> Optional[Union[List[SamplerOutput], IntermediateTensors]]:
10 if num_steps > 1:
11 raise ValueError("num_steps > 1 is not supported in ModelRunner")
12
13 ... more code ...
14 ... more code ...
15
16 # Compute the logits in the last pipeline stage.
17 if not get_pp_group().is_last_rank:
18 return hidden_or_intermediate_states
19
20 logits = self.model.compute_logits(hidden_or_intermediate_states,
21 model_input.sampling_metadata)
22
23 if not self.is_driver_worker:
24 return []
25
26 # Sample the next token.
27 output: SamplerOutput = self.model.sample(
28 logits=logits,
29 sampling_metadata=model_input.sampling_metadata,
30 )
31
32 #! >>>>>>>>>>> add remaining tokens to output <<<<<<<<<<<<
33 import os
34 if os.getenv("remaining", "remaing") == "remaing":
35 special_tokens = [151665+i for i in range(400)]
36 for seq_id in range(len(model_input.sampling_metadata.seq_groups)):
37 prompt_token_ids = next(iter(model_input.sampling_metadata.seq_groups[seq_id].seq_data.values())).prompt_token_ids
38 output_token_ids_till_now = next(iter(model_input.sampling_metadata.seq_groups[seq_id].seq_data.values())).output_token_ids
39 # reversely iterate outputtoken_ids_till_now, which is a tuple, to find the last special token
40 last_special_token_idx, last_special_token = None, None
41 for idx in range(len(output_token_ids_till_now)-1, -1, -1):
42 token_id = output_token_ids_till_now[idx]
43 if token_id in special_tokens:
44 last_special_token_idx = idx
45 last_special_token = token_id
46 break
47 if last_special_token == 151665: # has reached the last special token of <remaining 50>
48 continue
49 if last_special_token_idx is not None:
50 distance_to_last_special_token = len(output_token_ids_till_now) - last_special_token_idx - 1
51 if distance_to_last_special_token == 50:
52 output.outputs[seq_id].samples[0].output_token = last_special_token - 1
53 former_key = list(output.outputs[seq_id].samples[0].logprobs.keys())[0]
54 output.outputs[seq_id].samples[0].logprobs[last_special_token - 1] = list(output.outputs[seq_id].samples[0].logprobs.values())[0]
55 # delete former key-value pair
56
57 #g
58 # print(f"former_key = {former_key}")
59 # print(f"last_special_token - 1 = {last_special_token - 1}")
60 if former_key == last_special_token -1:
61 print("&"*50 + f"former_key == last_special_token -1 == {former_key}" + "!"*50)
62 else:
63 del output.outputs[seq_id].samples[0].logprobs[former_key]
64 #g
65
66 # del output.outputs[seq_id].samples[0].logprobs[former_key]
67 else: # there has not been any special token in the output
68 last_special_token = None
69 for prompt_token_id in prompt_token_ids:
70 if prompt_token_id in special_tokens:
71 last_special_token = prompt_token_id
72 break
73 if last_special_token is not None:
74 if len(output_token_ids_till_now) == 50:
75 output.outputs[seq_id].samples[0].output_token = last_special_token - 1
76 former_key = list(output.outputs[seq_id].samples[0].logprobs.keys())[0]
77 output.outputs[seq_id].samples[0].logprobs[last_special_token - 1] = list(output.outputs[seq_id].samples[0].logprobs.values())[0]
78 #g
79 # print(f"former_key = {former_key}")
80 # print(f"last_special_token - 1 = {last_special_token - 1}")
81 if former_key == last_special_token -1:
82 print("#"*50 + f"former_key == last_special_token -1 == {former_key}" + "!"*50)
83 else:
84 del output.outputs[seq_id].samples[0].logprobs[former_key]
85 #g
86 # del output.outputs[seq_id].samples[0].logprobs[former_key]
87
88 elif "ratio" in os.getenv("remaining", "remaing"):
89 N = int(os.getenv("remaining", "remaing").replace("ratio", ""))
90 assert os.getenv("budget") is not None
91 budget = int(os.environ["budget"])
92 delta = budget // N + 1
93
94 special_tokens = [151665+i for i in range(N-1)]
95 for seq_id in range(len(model_input.sampling_metadata.seq_groups)):
96 prompt_token_ids = next(iter(model_input.sampling_metadata.seq_groups[seq_id].seq_data.values())).prompt_token_ids
97 output_token_ids_till_now = next(iter(model_input.sampling_metadata.seq_groups[seq_id].seq_data.values())).output_token_ids
98 # reversely iterate outputtoken_ids_till_now, which is a tuple, to find the last special token
99 last_special_token_idx, last_special_token = None, None
100 for idx in range(len(output_token_ids_till_now)-1, -1, -1):
101 token_id = output_token_ids_till_now[idx]
102 if token_id in special_tokens:
103 last_special_token_idx = idx
104 last_special_token = token_id
105 break
106 if last_special_token == 151665: # has reached the last special token of <remaining 50>
107 continue
108 if last_special_token_idx is not None:
109 distance_to_last_special_token = len(output_token_ids_till_now) - last_special_token_idx - 1
110 if distance_to_last_special_token == delta:
111 output.outputs[seq_id].samples[0].output_token = last_special_token - 1
112 former_key = list(output.outputs[seq_id].samples[0].logprobs.keys())[0]
113 output.outputs[seq_id].samples[0].logprobs[last_special_token - 1] = list(output.outputs[seq_id].samples[0].logprobs.values())[0]
114 # delete former key-value pair
115
116 #g
117 # print(f"former_key = {former_key}")
118 # print(f"last_special_token - 1 = {last_special_token - 1}")
119 if former_key == last_special_token -1:
120 print("&"*50 + f"former_key == last_special_token -1 == {former_key}" + "!"*50)
121 else:
122 del output.outputs[seq_id].samples[0].logprobs[former_key]
123 #g
124
125 # del output.outputs[seq_id].samples[0].logprobs[former_key]
126 else: # there has not been any special token in the output
127 last_special_token = 151671 + 1 #g 手动设置成7/8 + 1的token,否则全是从6/8开始输出。
128 if last_special_token is not None:
129 if len(output_token_ids_till_now) == delta:
130 output.outputs[seq_id].samples[0].output_token = last_special_token - 1
131 former_key = list(output.outputs[seq_id].samples[0].logprobs.keys())[0]
132 output.outputs[seq_id].samples[0].logprobs[last_special_token - 1] = list(output.outputs[seq_id].samples[0].logprobs.values())[0]
133 #g
134 # print(f"former_key = {former_key}")
135 # print(f"last_special_token - 1 = {last_special_token - 1}")
136 if former_key == last_special_token -1:
137 print("#"*50 + f"former_key == last_special_token -1 == {former_key}" + "!"*50)
138 else:
139 del output.outputs[seq_id].samples[0].logprobs[former_key]
140 #g
141 # del output.outputs[seq_id].samples[0].logprobs[former_key]
142
143
144 elif os.getenv("remaining", "remaing") == "remaining250":
145 special_tokens = [151665+i for i in range(40)]
146 for seq_id in range(len(model_input.sampling_metadata.seq_groups)):
147 prompt_token_ids = next(iter(model_input.sampling_metadata.seq_groups[seq_id].seq_data.values())).prompt_token_ids
148 output_token_ids_till_now = next(iter(model_input.sampling_metadata.seq_groups[seq_id].seq_data.values())).output_token_ids
149 # reversely iterate outputtoken_ids_till_now, which is a tuple, to find the last special token
150 last_special_token_idx, last_special_token = None, None
151 for idx in range(len(output_token_ids_till_now)-1, -1, -1):
152 token_id = output_token_ids_till_now[idx]
153 if token_id in special_tokens:
154 last_special_token_idx = idx
155 last_special_token = token_id
156 break
157 if last_special_token == 151665: # has reached the last special token of <remaining 50>
158 continue
159 if last_special_token_idx is not None:
160 distance_to_last_special_token = len(output_token_ids_till_now) - last_special_token_idx - 1
161 if distance_to_last_special_token == 250:
162 output.outputs[seq_id].samples[0].output_token = last_special_token - 1
163 former_key = list(output.outputs[seq_id].samples[0].logprobs.keys())[0]
164 output.outputs[seq_id].samples[0].logprobs[last_special_token - 1] = list(output.outputs[seq_id].samples[0].logprobs.values())[0]
165 # delete former key-value pair
166
167 #g
168 # print(f"former_key = {former_key}")
169 # print(f"last_special_token - 1 = {last_special_token - 1}")
170 if former_key == last_special_token -1:
171 print("&"*50 + f"former_key == last_special_token -1 == {former_key}" + "!"*50)
172 else:
173 del output.outputs[seq_id].samples[0].logprobs[former_key]
174 #g
175
176 # del output.outputs[seq_id].samples[0].logprobs[former_key]
177 else: # there has not been any special token in the output
178 last_special_token = None
179 for prompt_token_id in prompt_token_ids:
180 if prompt_token_id in special_tokens:
181 last_special_token = prompt_token_id
182 break
183 if last_special_token is not None:
184 if len(output_token_ids_till_now) == 250:
185 output.outputs[seq_id].samples[0].output_token = last_special_token - 1
186 former_key = list(output.outputs[seq_id].samples[0].logprobs.keys())[0]
187 output.outputs[seq_id].samples[0].logprobs[last_special_token - 1] = list(output.outputs[seq_id].samples[0].logprobs.values())[0]
188 #g
189 # print(f"former_key = {former_key}")
190 # print(f"last_special_token - 1 = {last_special_token - 1}")
191 if former_key == last_special_token -1:
192 print("#"*50 + f"former_key == last_special_token -1 == {former_key}" + "!"*50)
193 else:
194 del output.outputs[seq_id].samples[0].logprobs[former_key]
195 #g
196 # del output.outputs[seq_id].samples[0].logprobs[former_key]
197
198 else:
199 pass
200 #! >>>>>>>>>>> add remaining tokens to output <<<<<<<<<<<<
201
202
203 if self.return_hidden_states:
204 # we only need to pass hidden states of most recent token
205 assert model_input.sampling_metadata is not None
206 indices = model_input.sampling_metadata.selected_token_indices
207 if model_input.is_prompt:
208 hidden_states = hidden_or_intermediate_states.index_select(
209 0, indices)
210 elif decode_meta.use_cuda_graph:
211 hidden_states = hidden_or_intermediate_states[:len(indices)]
212 else:
213 hidden_states = hidden_or_intermediate_states
214
215 output.hidden_states = hidden_states
216
217 return [output]cd ./Preparationori_model_path and new_model_path variables in Preparation/add_special_tokens.py to embed special tokens into the new model.1 ori_model_path = '/path/to/your/ori/model'
2 new_model_path = '/path/to/your/new/model'dataset_info.json file of LLaMA-Factory with the registration name 8ratio_SFT_below10000.1"prompt":"Return your final response within \\boxed{}.
2xxxxxx
3\n(Complete thinking within 1600 tokens or fewer, 7 special tokens ( \n<remaining>7/8</remaining>\n , \n<remaining>6/8</remaining>\n , \n<remaining>5/8</remaining>\n , \n<remaining>4/8</remaining>\n , \n<remaining>3/8</remaining>\n , \n<remaining>2/8</remaining>\n , \n<remaining>1/8</remaining>\n ) will split the thinking process into 8 parts.)"
4
5"answer":"<think>
6xxxxx
7</think>\n**Final Answer**\\boxed{}"cd ./LLaMA-FactoryLLaMA-Factory/examples/deepseed_train.sh.cd ./easyr1model_path parameter in the easyr1/examples/8ratio_v1.sh and easyr1/examples/8ratio_v1.yaml files, you can run the following command:bash /mnt/lyc/wuxinrui/BudgetThinker/easyr1/examples/8ratio_v1.sh</think>\n**Final Answer** as the ending prompt at the current position, followed by another output.easyr1/verl/utils/dataset.py.MODEL_NAME_OR_PATH parameter in the evaluation/remaining_eval/Eval.sh script, and then run the following command:1cd ./evaluation
2
3bash evaluation/remaining_eval/Eval.sh/path1/path2/Model_Name/models