Skip to content

Commit 070907d

Browse files
committed
polish
1 parent f736d74 commit 070907d

File tree

6 files changed

+74
-26
lines changed

6 files changed

+74
-26
lines changed

applications/ColossalChat/coati/dataset/loader.py

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,14 @@ def apply_chat_template_and_mask(
356356
truncation: bool = True,
357357
ignore_idx: int = -100,
358358
) -> Dict[str, torch.Tensor]:
359+
360+
system_prompt = "You are a helpful assistant. The assistant first thinks about the reasoning process in the mind and then provides the user with the answer. The reasoning process and answer are enclosed within <think> </think> and<answer> </answer> tags, respectively, i.e., <think> reasoning process here </think><answer> answer here </answer>. Now the user asks you to solve a math problem that involves reasoning. After thinking, when you finally reach a conclusion, clearly output the final answer without explanation within the <answer> </answer> tags, your final answer should be a integer without unit, currency mark, thousands separator or other text. i.e., <answer> 123 </answer>.\n"
361+
362+
system_element = {
363+
"role": "system",
364+
"content": system_prompt,
365+
}
366+
359367
# Format for RL.
360368
gt_answer = None
361369
if "messages" in chat and "gt_answer" in chat:
@@ -365,7 +373,7 @@ def apply_chat_template_and_mask(
365373
tokens = []
366374
assistant_mask = []
367375
for i, msg in enumerate(chat):
368-
msg_tokens = tokenizer.apply_chat_template([msg], tokenize=True)
376+
msg_tokens = tokenizer.apply_chat_template([system_element, msg], tokenize=True, add_generation_prompt=True)
369377
# remove unexpected bos token
370378
if i > 0 and msg_tokens[0] == tokenizer.bos_token_id:
371379
msg_tokens = msg_tokens[1:]
@@ -378,14 +386,15 @@ def apply_chat_template_and_mask(
378386
if max_length is not None:
379387
if padding and len(tokens) < max_length:
380388
to_pad = max_length - len(tokens)
381-
if tokenizer.padding_side == "right":
382-
tokens.extend([tokenizer.pad_token_id] * to_pad)
383-
assistant_mask.extend([False] * to_pad)
384-
attention_mask.extend([0] * to_pad)
385-
else:
386-
tokens = [tokenizer.pad_token_id] * to_pad + tokens
387-
assistant_mask = [False] * to_pad + assistant_mask
388-
attention_mask = [0] * to_pad + attention_mask
389+
# Left padding for generation.
390+
# if tokenizer.padding_side == "right":
391+
# tokens.extend([tokenizer.pad_token_id] * to_pad)
392+
# assistant_mask.extend([False] * to_pad)
393+
# attention_mask.extend([0] * to_pad)
394+
# else:
395+
tokens = [tokenizer.pad_token_id] * to_pad + tokens
396+
assistant_mask = [False] * to_pad + assistant_mask
397+
attention_mask = [0] * to_pad + attention_mask
389398
if truncation and len(tokens) > max_length:
390399
tokens = tokens[:max_length]
391400
assistant_mask = assistant_mask[:max_length]

applications/ColossalChat/coati/distributed/grpo_consumer.py

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from coati.distributed.reward.reward_fn import math_reward_fn
1010
from coati.distributed.reward.verifiable_reward import VerifiableReward
1111
from coati.distributed.utils import calc_action_log_probs
12-
from coati.trainer.utils import all_reduce_mean, is_rank_0
12+
from coati.trainer.utils import all_reduce_mean
1313
from transformers import AutoModelForCausalLM, AutoTokenizer
1414

1515
from colossalai.nn.optimizer import HybridAdam
@@ -77,8 +77,15 @@ def __init__(
7777
)
7878

7979
self.policy_loss_fn = PolicyLoss()
80-
if is_rank_0():
81-
self.run = wandb.init(project="Colossal-GRPO-Test4")
80+
self.global_step = 0
81+
if self.rank == 0:
82+
self.wandb_run = wandb.init(project="Colossal-GRPO-Test6", sync_tensorboard=True)
83+
# import os
84+
# import time
85+
86+
# log_dir = self.wandb_run.dir
87+
# # log_dir = os.path.join(log_dir, time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime()))
88+
# # self.writer = SummaryWriter(log_dir=log_dir)
8289

8390
def setup(self):
8491
super().setup()
@@ -115,18 +122,21 @@ def step(self, step_idx: int, **kwargs) -> Optional[float]:
115122
)["logits"]
116123
action_log_probs = calc_action_log_probs(policy_model_logits, data["input_ids"], num_action)
117124

118-
reference_model_logits = self.reference_model(
119-
input_ids=data["input_ids"],
120-
attention_mask=data["attention_mask"],
121-
)["logits"]
125+
with torch.no_grad():
126+
reference_model_logits = self.reference_model(
127+
input_ids=data["input_ids"],
128+
attention_mask=data["attention_mask"],
129+
)["logits"]
122130
reference_action_log_probs = calc_action_log_probs(reference_model_logits, data["input_ids"], num_action)
123131

124132
# GRPO advantage calculation
125133
kl = torch.sum(-0.1 * (action_log_probs - reference_action_log_probs) * action_mask, dim=-1) / torch.sum(
126134
action_mask, dim=-1
127135
)
128136

129-
reward = self.reward_model(data["input_ids"], gt_answer=data["gt_answer"])
137+
reward = self.reward_model(
138+
data["input_ids"], gt_answer=data["gt_answer"], response_idx=data["response_idx"]
139+
)
130140
reward = kl + reward
131141
# [batch_size, num_generations]
132142
group_reward = reward.view(-1, self.num_generations)
@@ -163,11 +173,19 @@ def step(self, step_idx: int, **kwargs) -> Optional[float]:
163173
self.optimizer.step()
164174
self.optimizer.zero_grad()
165175
loss_scalar = self.accum_loss.item()
166-
if is_rank_0():
176+
if self.rank == 0:
167177
print("Loss:", self.accum_loss.item(), "Reward:", self.accum_reward.item(), "KL:", self.accum_kl.item())
168-
self.run.log(
169-
{"loss": self.accum_loss.item(), "reward": self.accum_reward.item(), "kl": self.accum_kl.item()}
178+
self.wandb_run.log(
179+
{
180+
"train/loss": self.accum_loss.item(),
181+
"train/reward": self.accum_reward.item(),
182+
"train/kl": self.accum_kl.item(),
183+
}
170184
)
185+
# self.writer.add_scalar("train/loss", self.accum_loss.item(), self.global_step)
186+
# self.writer.add_scalar("train/reward", self.accum_reward.item(), self.global_step)
187+
# self.writer.add_scalar("train/kl", self.accum_kl.item(), self.global_step)
188+
# self.global_step += 1
171189
self.accum_loss.zero_()
172190
self.accum_reward.zero_()
173191
self.accum_kl.zero_()

applications/ColossalChat/coati/distributed/inference_backend.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ class VLLMInferenceBackend(BaseInferenceBackend):
154154
)
155155
FORCE_GENERATE_CONFIG = dict(
156156
logprobs=0,
157+
n=4,
157158
)
158159

159160
def __init__(self, model_config: Dict[str, Any], generate_config: Dict[str, Any], tokenizer: PreTrainedTokenizer):
@@ -166,19 +167,24 @@ def __init__(self, model_config: Dict[str, Any], generate_config: Dict[str, Any]
166167
generate_config.update(self.FORCE_GENERATE_CONFIG)
167168
self.generate_config = SamplingParams(**generate_config)
168169
self.tokenizer = tokenizer
170+
self.num_generations = self.FORCE_GENERATE_CONFIG["n"]
169171

170172
@torch.no_grad()
171173
def generate(self, input_ids: torch.Tensor, attention_mask: torch.Tensor, **kwargs) -> Dict[str, torch.Tensor]:
174+
micro_batch_size = input_ids.size(0)
175+
response_start_idx = input_ids.size(1)
172176
outputs = self.llm.generate(
173177
prompt_token_ids=input_ids.tolist(), sampling_params=self.generate_config, use_tqdm=False
174178
)
175179
out_tokens = []
176180
out_len = []
177181
log_probs = []
182+
response_idx = []
178183
for out in outputs:
179184
for output_i in out.outputs:
180185
out_len.append(len(output_i.token_ids))
181186
out_tokens.append(list(output_i.token_ids))
187+
response_idx.append((response_start_idx, response_start_idx + len(output_i.token_ids) - 1))
182188
assert len(output_i.logprobs) == len(output_i.token_ids)
183189
p = [m[t].logprob for m, t in zip(output_i.logprobs, output_i.token_ids)]
184190
log_probs.append(p)
@@ -195,6 +201,8 @@ def generate(self, input_ids: torch.Tensor, attention_mask: torch.Tensor, **kwar
195201

196202
out_tokens = torch.tensor(out_tokens)
197203
log_probs = torch.tensor(log_probs)
204+
response_idx = torch.tensor(response_idx)
205+
198206
if attention_mask.size(0) != action_mask.size(0):
199207
assert action_mask.size(0) % attention_mask.size(0) == 0
200208
num_returns = action_mask.size(0) // attention_mask.size(0)
@@ -209,9 +217,14 @@ def generate(self, input_ids: torch.Tensor, attention_mask: torch.Tensor, **kwar
209217
"attention_mask": attention_mask,
210218
"action_log_probs": log_probs,
211219
"action_mask": action_mask,
220+
"response_idx": response_idx,
212221
}
222+
223+
data = {k: v.view(micro_batch_size, self.num_generations, v.size(-1)) for k, v in data.items()}
224+
213225
if "gt_answer" in kwargs:
214-
data["gt_answer"] = kwargs["gt_answer"]
226+
# repeat gt_answer for each prompt.
227+
data["gt_answer"] = kwargs["gt_answer"].repeat_interleave(self.num_generations, dim=1)
215228
data = {k: v.to(get_current_device()) for k, v in data.items()}
216229
return data
217230

applications/ColossalChat/coati/distributed/reward/reward_fn.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@
33
from .reward_utils import extract_solution, validate_response_structure
44

55

6-
def math_reward_fn(input_ids, gt_answer, **kwargs):
6+
def math_reward_fn(input_ids, gt_answer, response_idx, **kwargs):
77
tokenizer = kwargs["tokenizer"]
88
reward = torch.tensor(0.0).to(input_ids.device)
9+
s, e = response_idx[0], response_idx[1]
910
if gt_answer is None:
1011
return reward
11-
decoded_final_answer = tokenizer.decode(input_ids, skip_special_tokens=True)
12+
13+
decoded_final_answer = tokenizer.decode(input_ids[s : e + 1], skip_special_tokens=True)
1214
gt_answer = tokenizer.decode(gt_answer.squeeze(0))
1315
final_answer, processed_str = extract_solution(decoded_final_answer)
1416

@@ -29,7 +31,7 @@ def gsm8k_reward_fn(input_ids, **kwargs):
2931
reward = torch.tensor(0.0).to(input_ids.device)
3032
if gt_answer is None:
3133
return reward
32-
decoded_final_answer = tokenizer.decode(input_ids[s:e], skip_special_tokens=True)
34+
decoded_final_answer = tokenizer.decode(input_ids[s : e + 1], skip_special_tokens=True)
3335
final_answer, processed_str = extract_solution(decoded_final_answer)
3436
is_valid = True
3537
try:

applications/ColossalChat/coati/distributed/reward/verifiable_reward.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ def __call__(
1616
self,
1717
input_ids: torch.LongTensor,
1818
gt_answer: List[torch.Tensor] = None,
19+
response_idx: List[torch.Tensor] = None,
1920
) -> torch.Tensor:
2021
# Get batch size
2122
bs = input_ids.size(0)
@@ -30,6 +31,7 @@ def __call__(
3031
reward_fn(
3132
input_ids[i],
3233
gt_answer=gt_answer[i],
34+
response_idx=response_idx[i],
3335
**self.kwargs,
3436
)
3537
for i in range(bs)

applications/ColossalChat/rl_example.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,17 @@
5151
elif args.backend == "vllm":
5252
inference_model_config.update(
5353
dict(
54-
gpu_memory_utilization=0.6,
54+
gpu_memory_utilization=0.7,
5555
)
5656
)
5757
generate_config.update(
5858
dict(
59-
max_tokens=256,
59+
max_tokens=2048,
6060
ignore_eos=True,
61+
include_stop_str_in_output=True,
62+
stop=["</answer>"],
63+
temperature=0.2,
64+
top_p=0.95,
6165
)
6266
)
6367
else:

0 commit comments

Comments
 (0)