Compare commits
16 Commits
fc5ca6c35b
...
52100993c8
| Author | SHA1 | Date |
|---|---|---|
|
|
52100993c8 | |
|
|
1e6e909f88 | |
|
|
b00be3e5ca | |
|
|
7f5ba40a4e | |
|
|
949488fdb4 | |
|
|
e41bf7cacf | |
|
|
b330a4d5c0 | |
|
|
b956bad49f | |
|
|
d698c06fc5 | |
|
|
984a2c3611 | |
|
|
d4b67f1783 | |
|
|
ba10c4d17b | |
|
|
cb08b9300b | |
|
|
56d4cddfd8 | |
|
|
0c91dea4a2 | |
|
|
182bff1bd8 |
|
|
@ -28,9 +28,12 @@ def pre_processing_chat(conversations, add_system_ratio=0.2):
|
||||||
return [{'role': 'system', 'content': random.choice(SYSTEM_PROMPTS)}] + conversations
|
return [{'role': 'system', 'content': random.choice(SYSTEM_PROMPTS)}] + conversations
|
||||||
return conversations
|
return conversations
|
||||||
|
|
||||||
def post_processing_chat(prompt_content, empty_think_ratio=0.2):
|
def post_processing_chat(prompt_content, empty_think_ratio=0.2, remove_empty_think=None):
|
||||||
# 以80%概率移除空思考标签
|
# 以80%概率移除空思考标签
|
||||||
if '<think>\n\n</think>\n\n' in prompt_content and random.random() > empty_think_ratio:
|
if '<think>\n\n</think>\n\n' in prompt_content:
|
||||||
|
if remove_empty_think is None:
|
||||||
|
remove_empty_think = random.random() > empty_think_ratio
|
||||||
|
if remove_empty_think:
|
||||||
prompt_content = prompt_content.replace('<think>\n\n</think>\n\n', '')
|
prompt_content = prompt_content.replace('<think>\n\n</think>\n\n', '')
|
||||||
return prompt_content
|
return prompt_content
|
||||||
|
|
||||||
|
|
@ -139,12 +142,13 @@ class DPODataset(Dataset):
|
||||||
chosen_prompt = self.tokenizer.apply_chat_template(
|
chosen_prompt = self.tokenizer.apply_chat_template(
|
||||||
chosen, tokenize=False, add_generation_prompt=False
|
chosen, tokenize=False, add_generation_prompt=False
|
||||||
)
|
)
|
||||||
chosen_prompt = post_processing_chat(chosen_prompt)
|
|
||||||
|
|
||||||
rejected_prompt = self.tokenizer.apply_chat_template(
|
rejected_prompt = self.tokenizer.apply_chat_template(
|
||||||
rejected, tokenize=False, add_generation_prompt=False
|
rejected, tokenize=False, add_generation_prompt=False
|
||||||
)
|
)
|
||||||
rejected_prompt = post_processing_chat(rejected_prompt)
|
remove_empty_think = random.random() > 0.2
|
||||||
|
chosen_prompt = post_processing_chat(chosen_prompt, remove_empty_think=remove_empty_think)
|
||||||
|
rejected_prompt = post_processing_chat(rejected_prompt, remove_empty_think=remove_empty_think)
|
||||||
chosen_encoding = self.tokenizer(
|
chosen_encoding = self.tokenizer(
|
||||||
chosen_prompt, truncation=True, max_length=self.max_length, padding='max_length'
|
chosen_prompt, truncation=True, max_length=self.max_length, padding='max_length'
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -125,10 +125,10 @@ class Attention(nn.Module):
|
||||||
if self.flash and (seq_len > 1) and (not self.is_causal or past_key_value is None) and (attention_mask is None or torch.all(attention_mask == 1)):
|
if self.flash and (seq_len > 1) and (not self.is_causal or past_key_value is None) and (attention_mask is None or torch.all(attention_mask == 1)):
|
||||||
output = F.scaled_dot_product_attention(xq, xk, xv, dropout_p=self.dropout if self.training else 0.0, is_causal=self.is_causal)
|
output = F.scaled_dot_product_attention(xq, xk, xv, dropout_p=self.dropout if self.training else 0.0, is_causal=self.is_causal)
|
||||||
else:
|
else:
|
||||||
scores = (xq @ xk.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
scores = (xq @ xk.transpose(-2, -1)).float() / math.sqrt(self.head_dim)
|
||||||
if self.is_causal: scores[:, :, :, -seq_len:] += torch.full((seq_len, seq_len), float("-inf"), device=scores.device).triu(1)
|
if self.is_causal: scores[:, :, :, -seq_len:] += torch.full((seq_len, seq_len), float("-inf"), device=scores.device).triu(1)
|
||||||
if attention_mask is not None: scores += (1.0 - attention_mask.unsqueeze(1).unsqueeze(2)) * -1e9
|
if attention_mask is not None: scores += (1.0 - attention_mask.unsqueeze(1).unsqueeze(2)) * -1e9
|
||||||
output = self.attn_dropout(F.softmax(scores.float(), dim=-1).type_as(xq)) @ xv
|
output = self.attn_dropout(F.softmax(scores, dim=-1).type_as(xq)) @ xv
|
||||||
output = output.transpose(1, 2).reshape(bsz, seq_len, -1)
|
output = output.transpose(1, 2).reshape(bsz, seq_len, -1)
|
||||||
output = self.resid_dropout(self.o_proj(output))
|
output = self.resid_dropout(self.o_proj(output))
|
||||||
return output, past_kv
|
return output, past_kv
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,8 @@ streamlit==1.50.0
|
||||||
einops==0.8.1
|
einops==0.8.1
|
||||||
swanlab==0.9.8
|
swanlab==0.9.8
|
||||||
modelscope==1.37.0
|
modelscope==1.37.0
|
||||||
|
fastapi==0.120.1
|
||||||
|
uvicorn==0.38.0
|
||||||
# torch==2.6.0
|
# torch==2.6.0
|
||||||
# torchvision==0.21.0
|
# torchvision==0.21.0
|
||||||
# peft==0.7.1
|
# peft==0.7.1
|
||||||
|
|
|
||||||
|
|
@ -202,7 +202,7 @@ async def chat_completions(request: ChatRequest):
|
||||||
with torch.no_grad():
|
with torch.no_grad():
|
||||||
generated_ids = model.generate(
|
generated_ids = model.generate(
|
||||||
inputs["input_ids"],
|
inputs["input_ids"],
|
||||||
max_length=inputs["input_ids"].shape[1] + request.max_tokens,
|
max_new_tokens=request.max_tokens,
|
||||||
do_sample=True,
|
do_sample=True,
|
||||||
attention_mask=inputs["attention_mask"],
|
attention_mask=inputs["attention_mask"],
|
||||||
pad_token_id=tokenizer.pad_token_id,
|
pad_token_id=tokenizer.pad_token_id,
|
||||||
|
|
|
||||||
|
|
@ -273,8 +273,6 @@ def rl_train_epoch(epoch, loader, iters, rollout_engine, ref_model, reward_model
|
||||||
rewards = calculate_rewards(prompts, completions, gt_batch, tools_batch, args.num_generations, reward_model, device=args.device, turn_outputs_batch=turn_outputs_batch, unfinished_batch=unfinished_batch)
|
rewards = calculate_rewards(prompts, completions, gt_batch, tools_batch, args.num_generations, reward_model, device=args.device, turn_outputs_batch=turn_outputs_batch, unfinished_batch=unfinished_batch)
|
||||||
|
|
||||||
with autocast_ctx:
|
with autocast_ctx:
|
||||||
# 反向传播必须经过 DDP 包装后的模块:直接调用 .module 会跳过
|
|
||||||
# DDP 的 prepare_for_backward,梯度不会 all-reduce,各卡静默发散。
|
|
||||||
res = model(input_ids, attention_mask=full_mask)
|
res = model(input_ids, attention_mask=full_mask)
|
||||||
aux_loss = res.aux_loss if lm_config.use_moe else torch.tensor(0.0, device=args.device)
|
aux_loss = res.aux_loss if lm_config.use_moe else torch.tensor(0.0, device=args.device)
|
||||||
logits = res.logits[:, :-1, :]
|
logits = res.logits[:, :-1, :]
|
||||||
|
|
@ -471,7 +469,6 @@ if __name__ == "__main__":
|
||||||
if args.use_compile == 1:
|
if args.use_compile == 1:
|
||||||
model = torch.compile(model)
|
model = torch.compile(model)
|
||||||
Logger('torch.compile enabled')
|
Logger('torch.compile enabled')
|
||||||
rollout_engine.update_policy(model)
|
|
||||||
if dist.is_initialized():
|
if dist.is_initialized():
|
||||||
# 同 train_ppo:RoPE buffer 各 rank 一致,每步广播纯属浪费
|
# 同 train_ppo:RoPE buffer 各 rank 一致,每步广播纯属浪费
|
||||||
model = DistributedDataParallel(model, device_ids=[local_rank], broadcast_buffers=False)
|
model = DistributedDataParallel(model, device_ids=[local_rank], broadcast_buffers=False)
|
||||||
|
|
|
||||||
|
|
@ -96,8 +96,6 @@ def grpo_train_epoch(epoch, loader, iters, rollout_engine, ref_model, reward_mod
|
||||||
rewards = calculate_rewards(prompts, completions, reward_model).to(args.device) # [B*num_gen]
|
rewards = calculate_rewards(prompts, completions, reward_model).to(args.device) # [B*num_gen]
|
||||||
|
|
||||||
with autocast_ctx:
|
with autocast_ctx:
|
||||||
# 反向传播必须经过 DDP 包装后的模块:直接调用 .module 会跳过
|
|
||||||
# DDP 的 prepare_for_backward,梯度不会 all-reduce,各卡静默发散。
|
|
||||||
res = model(outputs, attention_mask=full_mask)
|
res = model(outputs, attention_mask=full_mask)
|
||||||
aux_loss = res.aux_loss if lm_config.use_moe else torch.tensor(0.0, device=args.device)
|
aux_loss = res.aux_loss if lm_config.use_moe else torch.tensor(0.0, device=args.device)
|
||||||
per_token_logps = F.log_softmax(res.logits[:, :-1, :], dim=-1).gather(2, outputs[:, 1:].unsqueeze(-1)).squeeze(-1).gather(1, logp_pos)
|
per_token_logps = F.log_softmax(res.logits[:, :-1, :], dim=-1).gather(2, outputs[:, 1:].unsqueeze(-1)).squeeze(-1).gather(1, logp_pos)
|
||||||
|
|
@ -312,7 +310,6 @@ if __name__ == "__main__":
|
||||||
if args.use_compile == 1:
|
if args.use_compile == 1:
|
||||||
model = torch.compile(model)
|
model = torch.compile(model)
|
||||||
Logger('torch.compile enabled')
|
Logger('torch.compile enabled')
|
||||||
rollout_engine.update_policy(model)
|
|
||||||
if dist.is_initialized():
|
if dist.is_initialized():
|
||||||
# 同 train_ppo:RoPE buffer 各 rank 一致,每步广播纯属浪费
|
# 同 train_ppo:RoPE buffer 各 rank 一致,每步广播纯属浪费
|
||||||
model = DistributedDataParallel(model, device_ids=[local_rank], broadcast_buffers=False)
|
model = DistributedDataParallel(model, device_ids=[local_rank], broadcast_buffers=False)
|
||||||
|
|
|
||||||
|
|
@ -166,16 +166,12 @@ def ppo_train_epoch(epoch, loader, iters, rollout_engine, ref_model, actor_sched
|
||||||
for i in range(0, B, mb_size):
|
for i in range(0, B, mb_size):
|
||||||
inds = b_inds[i:i + mb_size]
|
inds = b_inds[i:i + mb_size]
|
||||||
|
|
||||||
# 反向传播必须经过 DDP 包装后的模块:直接调用 .module 会跳过
|
|
||||||
# DDP 的 prepare_for_backward,梯度不会 all-reduce,各卡静默发散。
|
|
||||||
mb_values_seq = critic_model(input_ids=gen_out[inds], attention_mask=full_mask[inds])
|
mb_values_seq = critic_model(input_ids=gen_out[inds], attention_mask=full_mask[inds])
|
||||||
mb_resp_values = mb_values_seq.gather(1, logp_pos[inds])
|
mb_resp_values = mb_values_seq.gather(1, logp_pos[inds])
|
||||||
|
|
||||||
with autocast_ctx:
|
with autocast_ctx:
|
||||||
res = actor_model(input_ids=gen_out[inds], attention_mask=full_mask[inds])
|
res = actor_model(input_ids=gen_out[inds], attention_mask=full_mask[inds])
|
||||||
aux_loss = res.aux_loss if lm_config.use_moe else torch.tensor(0.0, device=args.device)
|
aux_loss = res.aux_loss if lm_config.use_moe else torch.tensor(0.0, device=args.device)
|
||||||
# 在 autocast 内计算 log_softmax,避免直接对 fp16/bf16 logits
|
|
||||||
# 计算造成额外数值偏差。
|
|
||||||
mb_resp_logp = F.log_softmax(res.logits[:, :-1], dim=-1).gather(2, labels[inds].unsqueeze(-1)).squeeze(-1).gather(1, logp_pos[inds])
|
mb_resp_logp = F.log_softmax(res.logits[:, :-1], dim=-1).gather(2, labels[inds].unsqueeze(-1)).squeeze(-1).gather(1, logp_pos[inds])
|
||||||
|
|
||||||
log_ratio = mb_resp_logp - old_resp_logp[inds]
|
log_ratio = mb_resp_logp - old_resp_logp[inds]
|
||||||
|
|
@ -427,7 +423,6 @@ if __name__ == "__main__":
|
||||||
if args.use_compile == 1:
|
if args.use_compile == 1:
|
||||||
actor_model = torch.compile(actor_model)
|
actor_model = torch.compile(actor_model)
|
||||||
Logger('torch.compile enabled')
|
Logger('torch.compile enabled')
|
||||||
rollout_engine.update_policy(actor_model)
|
|
||||||
if dist.is_initialized():
|
if dist.is_initialized():
|
||||||
# freqs_cos/freqs_sin 各 rank 由 config 确定性算出,默认每步广播一次纯属浪费
|
# freqs_cos/freqs_sin 各 rank 由 config 确定性算出,默认每步广播一次纯属浪费
|
||||||
actor_model = DistributedDataParallel(actor_model, device_ids=[local_rank], broadcast_buffers=False)
|
actor_model = DistributedDataParallel(actor_model, device_ids=[local_rank], broadcast_buffers=False)
|
||||||
|
|
|
||||||
|
|
@ -8,18 +8,39 @@ DATA_PATH = '../dataset/sft_t2t_mini.jsonl'
|
||||||
TOKENIZER_DIR = '../model_learn_tokenizer/'
|
TOKENIZER_DIR = '../model_learn_tokenizer/'
|
||||||
VOCAB_SIZE = 6400
|
VOCAB_SIZE = 6400
|
||||||
SPECIAL_TOKENS_NUM = 36
|
SPECIAL_TOKENS_NUM = 36
|
||||||
|
MAX_LINES = 0 # 0 表示读取全部;设为正数则只取前 N 条(快速试跑)
|
||||||
|
|
||||||
def get_texts(data_path):
|
def get_texts(data_path, max_lines=MAX_LINES):
|
||||||
|
"""逐行产出用于训练 BPE 的文本,兼容两种主线数据格式。
|
||||||
|
|
||||||
|
pretrain_t2t(_mini).jsonl 是 {"text": ...},
|
||||||
|
sft_t2t(_mini).jsonl 是 {"conversations": [{"role":..., "content":...}, ...]}。
|
||||||
|
原先只解析 conversations,所以把 DATA_PATH 指向预训练语料时一条文本都取不到,
|
||||||
|
BPE 仅基于 initial_alphabet 训练,产出一个没有任何 merge 的词表,且全程不报错。
|
||||||
|
"""
|
||||||
|
used = 0
|
||||||
with open(data_path, 'r', encoding='utf-8', errors='ignore') as f:
|
with open(data_path, 'r', encoding='utf-8', errors='ignore') as f:
|
||||||
for i, line in enumerate(f):
|
for line in f:
|
||||||
if i >= 10000: break # 选10000行测试
|
if max_lines and used >= max_lines:
|
||||||
|
break
|
||||||
try:
|
try:
|
||||||
data = json.loads(line)
|
data = json.loads(line)
|
||||||
contents = [item.get('content') for item in data.get('conversations', []) if item.get('content')]
|
|
||||||
if contents:
|
|
||||||
yield "\n".join(contents)
|
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
continue
|
continue
|
||||||
|
if 'text' in data:
|
||||||
|
text = str(data['text'])
|
||||||
|
else:
|
||||||
|
contents = [item.get('content') for item in data.get('conversations', []) if item.get('content')]
|
||||||
|
text = "\n".join(contents) if contents else ''
|
||||||
|
if text.strip():
|
||||||
|
used += 1
|
||||||
|
yield text
|
||||||
|
if used == 0:
|
||||||
|
raise ValueError(
|
||||||
|
f'{data_path} 中没有可用文本:每行应为 {{"text": ...}} 或 '
|
||||||
|
f'{{"conversations": [{{"role":..., "content":...}}, ...]}}。'
|
||||||
|
f'继续训练只会得到一个空词表。'
|
||||||
|
)
|
||||||
|
|
||||||
def train_tokenizer(data_path, tokenizer_dir, vocab_size, special_tokens_num=SPECIAL_TOKENS_NUM):
|
def train_tokenizer(data_path, tokenizer_dir, vocab_size, special_tokens_num=SPECIAL_TOKENS_NUM):
|
||||||
tokenizer = Tokenizer(models.BPE())
|
tokenizer = Tokenizer(models.BPE())
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue