Browse Source

Merge upstream master and preserve the optional learning-rate warmup

林SO 2 days ago
parent
commit
693de30bc7

+ 3 - 1
README.md

@@ -1153,7 +1153,9 @@ python train_grpo.py
 
 > MiniMind 在 GRPO 训练阶段的优化走势
 
-从训练曲线可以看出,GRPO的**reward呈现更加稳定的上升趋势**,达到4左右,说明GRPO本身能更好地利用RLAIF信号。Policy Loss整体下降平稳,相比PPO的双网络优化,GRPO单网络架构训练更稳定且收敛上限更高。
+从训练曲线可以看出,GRPO的**reward呈现更加稳定的上升趋势**,达到4左右,说明GRPO本身能更好地利用RLAIF信号。相比PPO的双网络优化,GRPO单网络架构训练更稳定且收敛上限更高。
+
+需要说明的是,Policy Loss 并不是监督学习里那种“越低越好”的 loss:它是按一阶导等于策略梯度构造的代理目标(TRPO like),并且每一轮都会做组内优势归一化,因此它的绝对值主要取决于当前策略与采样分布的偏离程度,“整体下降平稳”并不等于模型在变好。判断 GRPO 是否收敛,应该看 reward 和实际生成质量。
 
 #### 7.3 [Clipped Importance Sampling Policy Optimization](https://huggingface.co/papers/2506.13585)
 

+ 3 - 1
README_en.md

@@ -1153,7 +1153,9 @@ python train_grpo.py
 
 > MiniMind optimization trends during the GRPO training stage
 
-From the training curves, it can be seen that GRPO's **reward shows a more stable upward trend**, reaching around 4, indicating that GRPO itself can better utilize RLAIF signals. Policy Loss decreases steadily overall, and compared to PPO's dual-network optimization, GRPO's single-network architecture trains more stably with a higher convergence ceiling.
+From the training curves, it can be seen that GRPO's **reward shows a more stable upward trend**, reaching around 4, indicating that GRPO itself can better utilize RLAIF signals. Compared to PPO's dual-network optimization, GRPO's single-network architecture trains more stably with a higher convergence ceiling.
+
+Worth noting: Policy Loss is not a supervised loss where "lower is better". It is a surrogate objective constructed so that its first-order derivative equals the policy gradient (TRPO like), and advantages are normalized within each group on every iteration. Its absolute value therefore mainly reflects how far the current policy has drifted from the sampling distribution, so a "steady overall decline" does not mean the model is getting better. Whether GRPO is converging should be judged from the reward and the actual generation quality.
 
 #### 7.3 [Clipped Importance Sampling Policy Optimization](https://huggingface.co/papers/2506.13585)
 

+ 5 - 3
eval_llm.py

@@ -1,3 +1,4 @@
+import os
 import time
 import argparse
 import random
@@ -11,7 +12,7 @@ warnings.filterwarnings('ignore')
 
 def init_model(args):
     tokenizer = AutoTokenizer.from_pretrained(args.load_from)
-    if 'model' in args.load_from:
+    if os.path.basename(os.path.normpath(args.load_from)) == 'model':
         model = MiniMindForCausalLM(MiniMindConfig(
             hidden_size=args.hidden_size,
             num_hidden_layers=args.num_hidden_layers,
@@ -22,8 +23,8 @@ def init_model(args):
         ckp = f'./{args.save_dir}/{args.weight}_{args.hidden_size}{moe_suffix}.pth'
         model.load_state_dict(torch.load(ckp, map_location=args.device), strict=True)
         if args.lora_weight != 'None':
-            apply_lora(model)
-            load_lora(model, f'./{args.save_dir}/{args.lora_weight}_{args.hidden_size}.pth')
+            apply_lora(model, rank=args.lora_rank)
+            load_lora(model, f'./{args.save_dir}/{args.lora_weight}_{args.hidden_size}{moe_suffix}.pth')
     else:
         model = AutoModelForCausalLM.from_pretrained(args.load_from, trust_remote_code=True)
     get_model_params(model, model.config)
@@ -35,6 +36,7 @@ def main():
     parser.add_argument('--save_dir', default='out', type=str, help="模型权重目录")
     parser.add_argument('--weight', default='full_sft', type=str, help="权重名称前缀(pretrain, full_sft, rlhf, reason, ppo_actor, grpo, spo)")
     parser.add_argument('--lora_weight', default='None', type=str, help="LoRA权重名称(None表示不使用,可选:lora_identity, lora_medical)")
+    parser.add_argument('--lora_rank', default=16, type=int, help="LoRA rank,需与训练时一致(默认16)")
     parser.add_argument('--hidden_size', default=768, type=int, help="隐藏层维度")
     parser.add_argument('--num_hidden_layers', default=8, type=int, help="隐藏层数量")
     parser.add_argument('--use_moe', default=0, type=int, choices=[0, 1], help="是否使用MoE架构(0=否,1=是)")

+ 13 - 8
model/model_lora.py

@@ -4,9 +4,11 @@ from torch import optim, nn
 
 # 定义Lora网络结构
 class LoRA(nn.Module):
-    def __init__(self, in_features, out_features, rank):
+    def __init__(self, in_features, out_features, rank, lora_alpha=None):
         super().__init__()
         self.rank = rank  # LoRA的秩(rank),控制低秩矩阵的大小
+        scaling = (rank if lora_alpha is None else lora_alpha) / rank
+        self.register_buffer("scaling", torch.tensor(scaling, dtype=torch.float32))
         self.A = nn.Linear(in_features, rank, bias=False)  # 低秩矩阵A
         self.B = nn.Linear(rank, out_features, bias=False)  # 低秩矩阵B
         # 矩阵A高斯初始化
@@ -15,13 +17,13 @@ class LoRA(nn.Module):
         self.B.weight.data.zero_()
 
     def forward(self, x):
-        return self.B(self.A(x))
+        return self.B(self.A(x)) * self.scaling
 
 
-def apply_lora(model, rank=16):
+def apply_lora(model, rank=16, lora_alpha=None):
     for name, module in model.named_modules():
         if isinstance(module, nn.Linear) and module.in_features == module.out_features:
-            lora = LoRA(module.in_features, module.out_features, rank=rank).to(model.device)
+            lora = LoRA(module.in_features, module.out_features, rank=rank, lora_alpha=lora_alpha).to(model.device)
             setattr(module, "lora", lora)
             original_forward = module.forward
 
@@ -39,7 +41,7 @@ def load_lora(model, path):
     for name, module in model.named_modules():
         if hasattr(module, 'lora'):
             lora_state = {k.replace(f'{name}.lora.', ''): v for k, v in state_dict.items() if f'{name}.lora.' in k}
-            module.lora.load_state_dict(lora_state)
+            module.lora.load_state_dict(lora_state, strict=False)
 
 
 def save_lora(model, path):
@@ -48,7 +50,8 @@ def save_lora(model, path):
     for name, module in raw_model.named_modules():
         if hasattr(module, 'lora'):
             clean_name = name[7:] if name.startswith("module.") else name
-            lora_state = {f'{clean_name}.lora.{k}': v.cpu().half() for k, v in module.lora.state_dict().items()}
+            lora_state = {f'{clean_name}.lora.{k}': v.cpu().half() if k.endswith('.weight') else v.cpu().float()
+                          for k, v in module.lora.state_dict().items()}
             state_dict.update(lora_state)
     torch.save(state_dict, path)
 
@@ -59,7 +62,9 @@ def merge_lora(model, lora_path, save_path):
     state_dict = {k: v.cpu().half() for k, v in raw_model.state_dict().items() if '.lora.' not in k}
     for name, module in raw_model.named_modules():
         if isinstance(module, nn.Linear) and '.lora.' not in name:
-            state_dict[f'{name}.weight'] = module.weight.data.clone().cpu().half()
+            state_dict[f'{name}.weight'] = module.weight.data.clone().cpu().float()
             if hasattr(module, 'lora'):
-                state_dict[f'{name}.weight'] += (module.lora.B.weight.data @ module.lora.A.weight.data).cpu().half()
+                delta = (module.lora.B.weight.data.float() @ module.lora.A.weight.data.float()) * module.lora.scaling.float()
+                state_dict[f'{name}.weight'] += delta.cpu()
+            state_dict[f'{name}.weight'] = state_dict[f'{name}.weight'].half()
     torch.save(state_dict, save_path)

+ 6 - 6
model/model_minimind.py

@@ -127,7 +127,7 @@ class Attention(nn.Module):
         else:
             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 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.to(scores.dtype).unsqueeze(1).unsqueeze(2)) * -1e9
             output = self.attn_dropout(F.softmax(scores, dim=-1).type_as(xq)) @ xv
         output = output.transpose(1, 2).reshape(bsz, seq_len, -1)
         output = self.resid_dropout(self.o_proj(output))
@@ -260,6 +260,7 @@ class MiniMindForCausalLM(PreTrainedModel, GenerationMixin):
     # https://github.com/jingyaogong/minimind/discussions/611
     @torch.inference_mode()
     def generate(self, inputs=None, attention_mask=None, max_new_tokens=8192, temperature=0.85, top_p=0.85, top_k=50, eos_token_id=2, streamer=None, use_cache=True, num_return_sequences=1, do_sample=True, repetition_penalty=1.0, **kwargs):
+        if do_sample and not 0 < temperature < math.inf: raise ValueError("Sampling temperature must be finite and positive")
         input_ids = kwargs.pop("input_ids", inputs).repeat(num_return_sequences, 1)
         attention_mask = attention_mask.repeat(num_return_sequences, 1) if attention_mask is not None else None
         past_key_values = kwargs.pop("past_key_values", None)
@@ -269,17 +270,16 @@ class MiniMindForCausalLM(PreTrainedModel, GenerationMixin):
             past_len = past_key_values[0][0].shape[1] if past_key_values else 0
             outputs = self.forward(input_ids[:, past_len:], attention_mask, past_key_values, use_cache=use_cache, **kwargs)
             attention_mask = torch.cat([attention_mask, attention_mask.new_ones(attention_mask.shape[0], 1)], -1) if attention_mask is not None else None
-            logits = outputs.logits[:, -1, :] / temperature
+            logits = outputs.logits[:, -1] / temperature if do_sample else outputs.logits[:, -1]
             if repetition_penalty != 1.0:
                 for i in range(input_ids.shape[0]):
                     seen = torch.unique(input_ids[i]); score = logits[i, seen]; logits[i, seen] = torch.where(score > 0, score / repetition_penalty, score * repetition_penalty)
-            if top_k > 0: 
+            if do_sample and top_k > 0:
                 logits[logits < torch.topk(logits, top_k)[0][..., -1, None]] = -float('inf')
-            if top_p < 1.0:
+            if do_sample and top_p < 1.0:
                 sorted_logits, sorted_indices = torch.sort(logits, descending=True)
                 mask = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1) > top_p
-                mask[..., 1:], mask[..., 0] = mask[..., :-1].clone(), 0
-                logits[mask.scatter(1, sorted_indices, mask)] = -float('inf')
+                logits[mask.scatter(1, sorted_indices, F.pad(mask[..., :-1], (1, 0)))] = -float('inf')
             next_token = torch.multinomial(torch.softmax(logits, dim=-1), num_samples=1) if do_sample else torch.argmax(logits, dim=-1, keepdim=True)
             if eos_token_id is not None: next_token = torch.where(finished.unsqueeze(-1), next_token.new_full((next_token.shape[0], 1), eos_token_id), next_token)
             input_ids = torch.cat([input_ids, next_token], dim=-1)

+ 1 - 0
requirements.txt

@@ -8,6 +8,7 @@ marshmallow==3.22.0
 ngrok==1.4.0
 nltk==3.8
 numpy==1.26.4
+pyarrow>=15.0.0,<26
 openai==1.59.6
 psutil==5.9.8
 protobuf==6.33.5

+ 2 - 2
scripts/convert_model.py

@@ -102,12 +102,12 @@ def convert_transformers2torch(transformers_path, torch_path):
     print(f"模型已保存为 PyTorch 格式: {torch_path}")
 
 
-def convert_merge_base_lora(base_torch_path, lora_path, merged_torch_path):
+def convert_merge_base_lora(base_torch_path, lora_path, merged_torch_path, lora_rank=16):
     device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
     lm_model = MiniMindForCausalLM(lm_config).to(device)
     state_dict = torch.load(base_torch_path, map_location=device)
     lm_model.load_state_dict(state_dict, strict=False)
-    apply_lora(lm_model)
+    apply_lora(lm_model, rank=lora_rank)
     merge_lora(lm_model, lora_path, merged_torch_path)
     print(f"LoRA 已合并并保存为基模结构 PyTorch 格式: {merged_torch_path}")
 

+ 1 - 1
scripts/eval_toolcall.py

@@ -56,7 +56,7 @@ TEST_CASES = [
 
 def init_model(args):
     tokenizer = AutoTokenizer.from_pretrained(args.load_from)
-    if 'model' in args.load_from:
+    if os.path.basename(os.path.normpath(args.load_from)) == 'model':
         model = MiniMindForCausalLM(MiniMindConfig(hidden_size=args.hidden_size, num_hidden_layers=args.num_hidden_layers, use_moe=bool(args.use_moe)))
         moe_suffix = '_moe' if args.use_moe else ''
         ckp = f'./{args.save_dir}/{args.weight}_{args.hidden_size}{moe_suffix}.pth'

+ 61 - 37
scripts/serve_openai_api.py

@@ -27,7 +27,7 @@ app = FastAPI()
 
 def init_model(args):
     tokenizer = AutoTokenizer.from_pretrained(args.load_from)
-    if 'model' in args.load_from:
+    if os.path.basename(os.path.normpath(args.load_from)) == 'model':
         moe_suffix = '_moe' if args.use_moe else ''
         ckp = f'../{args.save_dir}/{args.weight}_{args.hidden_size}{moe_suffix}.pth'
         model = MiniMindForCausalLM(MiniMindConfig(
@@ -39,8 +39,8 @@ def init_model(args):
         ))
         model.load_state_dict(torch.load(ckp, map_location=device), strict=True)
         if args.lora_weight != 'None':
-            apply_lora(model)
-            load_lora(model, f'../{args.save_dir}/lora/{args.lora_weight}_{args.hidden_size}.pth')
+            apply_lora(model, rank=args.lora_rank)
+            load_lora(model, f'../{args.save_dir}/{args.lora_weight}_{args.hidden_size}{moe_suffix}.pth')
     else:
         model = AutoModelForCausalLM.from_pretrained(args.load_from, trust_remote_code=True)
     print(f'MiniMind模型参数量: {sum(p.numel() for p in model.parameters()) / 1e6:.2f} M(illion)')
@@ -50,7 +50,7 @@ def init_model(args):
 class ChatRequest(BaseModel):
     model: str
     messages: list
-    temperature: float = 0.7
+    temperature: float = Field(default=0.7, ge=0.0, allow_inf_nan=False)
     top_p: float = 0.92
     max_tokens: int = 8192
     stream: bool = True
@@ -115,7 +115,7 @@ def generate_stream_response(messages, temperature, top_p, max_tokens, tools=Non
                 model.generate(
                     inputs.input_ids,
                     max_new_tokens=max_tokens,
-                    do_sample=True,
+                    do_sample=temperature > 0,
                     temperature=temperature,
                     top_p=top_p,
                     attention_mask=inputs.attention_mask,
@@ -129,9 +129,11 @@ def generate_stream_response(messages, temperature, top_p, max_tokens, tools=Non
 
         Thread(target=_generate).start()
 
-        full_text = ""
-        emitted = 0
+        pending = ""
+        in_tool_call = False
+        tool_count = 0
         thinking_ended = not bool(open_thinking)
+        strip_newlines = False
 
         while True:
             text = queue.get()
@@ -140,43 +142,64 @@ def generate_stream_response(messages, temperature, top_p, max_tokens, tools=Non
             if isinstance(text, dict):
                 yield json.dumps(text, ensure_ascii=False)
                 continue
-            full_text += text
+            pending += text
 
-            if not thinking_ended:
-                pos = full_text.find('</think>')
-                if pos >= 0:
-                    thinking_ended = True
-                    new_r = full_text[emitted:pos]
-                    if new_r:
-                        yield json.dumps({"choices": [{"delta": {"reasoning_content": new_r}}]}, ensure_ascii=False)
-                    emitted = pos + len('</think>')
-                    after = full_text[emitted:].lstrip('\n')
-                    emitted = len(full_text) - len(after)
-                    if after:
-                        yield json.dumps({"choices": [{"delta": {"content": after}}]}, ensure_ascii=False)
-                        emitted = len(full_text)
+            while pending:
+                if strip_newlines:
+                    pending = pending.lstrip('\n')
+                    if not pending:
+                        break
+                    strip_newlines = False
+                if in_tool_call:
+                    end = pending.find('</tool_call>')
+                    if end < 0:
+                        break
+                    end += len('</tool_call>')
+                    block, pending = pending[:end], pending[end:]
+                    _, _, tool_calls = parse_response(block)
+                    if tool_calls:
+                        call = tool_calls[0]
+                        call['index'] = tool_count
+                        call['id'] = f"call_{int(time.time())}_{tool_count}"
+                        tool_count += 1
+                        yield json.dumps({"choices": [{"delta": {"tool_calls": [call]}}]}, ensure_ascii=False)
+                    else:
+                        yield json.dumps({"choices": [{"delta": {"content": block}}]}, ensure_ascii=False)
+                    in_tool_call = False
+                    continue
+
+                marker = '<tool_call>' if thinking_ended else '</think>'
+                field = 'content' if thinking_ended else 'reasoning_content'
+                pos = pending.find(marker)
+                if pos < 0:
+                    keep = next((n for n in range(len(marker) - 1, 0, -1)
+                                 if pending.endswith(marker[:n])), 0)
+                    end = len(pending) - keep
+                    if end:
+                        yield json.dumps({"choices": [{"delta": {field: pending[:end]}}]}, ensure_ascii=False)
+                        pending = pending[end:]
+                    break
+                if pos:
+                    yield json.dumps({"choices": [{"delta": {field: pending[:pos]}}]}, ensure_ascii=False)
+                pending = pending[pos:]
+                if thinking_ended:
+                    in_tool_call = True
                 else:
-                    new_r = full_text[emitted:]
-                    if new_r:
-                        yield json.dumps({"choices": [{"delta": {"reasoning_content": new_r}}]}, ensure_ascii=False)
-                        emitted = len(full_text)
-            else:
-                new_c = full_text[emitted:]
-                if new_c:
-                    yield json.dumps({"choices": [{"delta": {"content": new_c}}]}, ensure_ascii=False)
-                    emitted = len(full_text)
-
-        _, _, tool_calls = parse_response(full_text)
-        if tool_calls:
-            yield json.dumps({"choices": [{"delta": {"tool_calls": tool_calls}}]}, ensure_ascii=False)
-        yield json.dumps({"choices": [{"delta": {}, "finish_reason": "tool_calls" if tool_calls else "stop"}]}, ensure_ascii=False)
+                    pending = pending[len(marker):]
+                    thinking_ended = True
+                    strip_newlines = True
+
+        if pending:
+            field = 'content' if thinking_ended else 'reasoning_content'
+            yield json.dumps({"choices": [{"delta": {field: pending}}]}, ensure_ascii=False)
+        yield json.dumps({"choices": [{"delta": {}, "finish_reason": "tool_calls" if tool_count else "stop"}]}, ensure_ascii=False)
 
     except Exception as e:
         yield json.dumps({"error": str(e)})
 
 
 @app.post("/v1/chat/completions")
-async def chat_completions(request: ChatRequest):
+def chat_completions(request: ChatRequest):
     try:
         if request.stream:
             return StreamingResponse(
@@ -203,7 +226,7 @@ async def chat_completions(request: ChatRequest):
                 generated_ids = model.generate(
                     inputs["input_ids"],
                     max_new_tokens=request.max_tokens,
-                    do_sample=True,
+                    do_sample=request.temperature > 0,
                     attention_mask=inputs["attention_mask"],
                     pad_token_id=tokenizer.pad_token_id,
                     eos_token_id=tokenizer.eos_token_id,
@@ -240,6 +263,7 @@ if __name__ == "__main__":
     parser.add_argument('--save_dir', default='out', type=str, help="模型权重目录")
     parser.add_argument('--weight', default='full_sft', type=str, help="权重名称前缀(pretrain, full_sft, dpo, reason, ppo_actor, grpo, spo)")
     parser.add_argument('--lora_weight', default='None', type=str, help="LoRA权重名称(None表示不使用,可选:lora_identity, lora_medical)")
+    parser.add_argument('--lora_rank', default=16, type=int, help="LoRA rank,需与训练时一致(默认16)")
     parser.add_argument('--hidden_size', default=768, type=int, help="隐藏层维度")
     parser.add_argument('--num_hidden_layers', default=8, type=int, help="隐藏层数量")
     parser.add_argument('--max_seq_len', default=8192, type=int, help="最大序列长度")

+ 23 - 31
trainer/train_agent.py

@@ -23,18 +23,13 @@ from torch.optim.lr_scheduler import CosineAnnealingLR
 from transformers import AutoTokenizer
 from model.model_minimind import MiniMindConfig, MiniMindForCausalLM
 from dataset.lm_dataset import AgentRLDataset
-from trainer.trainer_utils import Logger, is_main_process, lm_checkpoint, init_distributed_mode, setup_seed, SkipBatchSampler, init_model, LMForRewardModel, safe_math_eval
+from trainer.trainer_utils import Logger, is_main_process, lm_checkpoint, init_distributed_mode, setup_seed, SkipBatchSampler, init_model, LMForRewardModel, safe_math_eval, rep_penalty
 from trainer.rollout_engine import create_rollout_engine, compute_per_token_logps
 
 warnings.filterwarnings('ignore')
 
 # ================================ 工具与 Reward = Start ================================
 
-def rep_penalty(text, n=3, cap=0.5):
-    toks = re.findall(r"\w+|[^\w\s]", text.lower())
-    grams = [tuple(toks[i:i + n]) for i in range(len(toks) - n + 1)]
-    return min(cap, (len(grams) - len(set(grams))) * cap * 2 / len(grams)) if grams else 0.0
-
 # ======== 工具定义 ========
 TOOLS = [
     {"type": "function", "function": {"name": "calculate_math", "description": "计算数学表达式", "parameters": {"type": "object", "properties": {"expression": {"type": "string"}}, "required": ["expression"]}}},
@@ -76,20 +71,30 @@ CHECK_ARGS = {
 def parse_tool_calls(text):
     calls = []
     for m in re.findall(r'<tool_call>(.*?)</tool_call>', text, re.DOTALL):
-        try: calls.append(json.loads(m.strip()))
-        except: pass
+        try: call = json.loads(m.strip())
+        except: continue
+        if not isinstance(call, dict): continue
+        args = call.get("arguments", {})
+        if isinstance(args, str):
+            try: args = json.loads(args)
+            except (ValueError, RecursionError): args = {}
+        call["name"], call["arguments"] = str(call.get("name", "")), args if isinstance(args, dict) else {}
+        calls.append(call)
     return calls
 
-def execute_tool(name, args):
+def execute_tool(name, args, valid_names=None):
     fn = MOCK_RESULTS.get(name)
-    if not fn: return None
+    if not fn: return {"error": f"未知工具: {name}"}
+    if valid_names is not None and name not in valid_names: return {"error": f"当前样本未提供工具: {name}"}
+    if not CHECK_ARGS[name](args): return {"error": f"工具参数无效: {name}"}
     try:
         return fn(args)
-    except Exception:
-        return None
+    except Exception as e:
+        return {"error": f"工具执行失败: {str(e)[:80]}"}
 
 # ======== 多轮 Rollout ========
 def rollout_single(rollout_engine, tokenizer, messages, tools, max_turns=3, max_new_tokens=256, thinking_ratio=0.5, device="cuda"):
+    valid_names = {t['function']['name'] for t in tools} if tools else set()
     all_outputs = []
     prompt_ids = None
     response_ids = []
@@ -128,12 +133,8 @@ def rollout_single(rollout_engine, tokenizer, messages, tools, max_turns=3, max_
         assistant_message = {"role": "assistant", "content": new_text}
         messages.append(assistant_message)
         for call in calls:
-            name, raw = call.get("name", ""), call.get("arguments", {})
-            if isinstance(raw, str):
-                try: raw = json.loads(raw)
-                except: raw = {}
-            result = execute_tool(name, raw)
-            result_str = (json.dumps(result, ensure_ascii=False) if result else '{"error": "tool not found"}')[:2048]  # 防止天文数字撑爆tokenizer
+            result = execute_tool(call["name"], call["arguments"], valid_names)
+            result_str = json.dumps(result, ensure_ascii=False)[:2048]  # 防止天文数字撑爆tokenizer
             messages.append({"role": "tool", "content": result_str})
 
         marker = f"<|agent_observation_{id(messages)}_{len(response_ids)}|>"
@@ -182,8 +183,8 @@ def rollout_batch(rollout_engine, tokenizer, messages_batch, tools_batch, num_ge
 # ======== Reward 计算 ========
 def validate_gt_in_text(text, gt_list):
     text, text_num = str(text), str(text).replace(',', '')
-    nums = [float(x) for x in re.findall(r'(?<![\w.])[-+]?\d+(?:\.\d+)?(?![\w.])', text_num)]
-    return {g for g in gt_list if ((s := str(g).strip()) and s.lower() in text.lower()) or (re.fullmatch(r'[-+]?\d+(?:\.\d+)?', str(g).strip().replace(',', '')) and any(abs(float(str(g).strip().replace(',', '')) - n) < 1e-6 for n in nums))}
+    nums = [float(x) for x in re.findall(r'(?<![A-Za-z0-9_.])[-+]?\d+(?:\.\d+)?(?![A-Za-z0-9_]|\.\d)', text_num)]
+    return {g for g in gt_list if (s := str(g).strip()) and (any(abs(float(s.replace(',', '')) - n) < 1e-6 for n in nums) if re.fullmatch(r'[-+]?\d+(?:\.\d+)?', s.replace(',', '')) else s.lower() in text.lower())}
 
 def calculate_rewards(prompts, completions, gt_batch, tools_batch, num_gen, reward_model=None, device="cuda", turn_outputs_batch=None, unfinished_batch=None):
     rewards = torch.zeros(len(completions), device=device)
@@ -221,10 +222,7 @@ def calculate_rewards(prompts, completions, gt_batch, tools_batch, num_gen, rewa
             gt = gt_batch[sample_idx]
             valid_call_count = 0
             for tool_call in tool_calls:
-                name, raw = tool_call.get("name", ""), tool_call.get("arguments", {})
-                if isinstance(raw, str):
-                    try: raw = json.loads(raw)
-                    except: raw = {}
+                name, raw = tool_call["name"], tool_call["arguments"]
                 check = CHECK_ARGS.get(name)
                 valid_call_count += int(bool(name in valid_names and check and check(raw)))
             tool_gap = abs(valid_call_count - len(gt)) + max(0, len(tool_calls) - valid_call_count)  # tool数差值
@@ -240,12 +238,10 @@ def calculate_rewards(prompts, completions, gt_batch, tools_batch, num_gen, rewa
 
 # ================================ 工具与 Reward = End ================================
 def rl_train_epoch(epoch, loader, iters, rollout_engine, ref_model, reward_model=None, start_step=0, wandb=None, use_sglang=False):
-    last_step = start_step
     for step, batch in enumerate(loader, start=start_step + 1):
         messages_batch = batch['messages']
         tools_batch = batch['tools']
         gt_batch = batch['gt']
-        last_step = step
 
         with torch.no_grad():
             completions, contexts, prompt_ids_batch, response_ids_batch, response_masks_batch, response_old_logps_batch, turn_outputs_batch, unfinished_batch = rollout_batch(rollout_engine, tokenizer, messages_batch, tools_batch, args.num_generations, max_turns=3, max_new_tokens=args.max_gen_len, thinking_ratio=args.thinking_ratio, device=args.device)
@@ -331,7 +327,7 @@ def rl_train_epoch(epoch, loader, iters, rollout_engine, ref_model, reward_model
         loss = (policy_loss + aux_loss) / args.accumulation_steps
         loss.backward()
 
-        if step % args.accumulation_steps == 0:
+        if step % args.accumulation_steps == 0 or step == iters:
             if args.grad_clip > 0: torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
             optimizer.step(); scheduler.step(); optimizer.zero_grad()
 
@@ -365,10 +361,6 @@ def rl_train_epoch(epoch, loader, iters, rollout_engine, ref_model, reward_model
         del per_token_logps, ref_per_token_logps
         del completions, rewards, grouped_rewards, mean_r, std_r, advantages, completion_mask
 
-    if last_step > start_step and last_step % args.accumulation_steps != 0:
-        if args.grad_clip > 0: torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
-        optimizer.step(); scheduler.step(); optimizer.zero_grad()
-
 
 if __name__ == "__main__":
     parser = argparse.ArgumentParser(description="MiniMind Agent RL")

+ 3 - 10
trainer/train_distillation.py

@@ -23,6 +23,8 @@ warnings.filterwarnings('ignore')
 
 
 def distillation_loss(student_logits, teacher_logits, temperature=1.0, reduction='batchmean'):
+    if student_logits.size(0) == 0 and reduction == 'batchmean':
+        return student_logits.sum() * 0.0
     with torch.no_grad():
         teacher_probs = F.softmax(teacher_logits / temperature, dim=-1).detach()
 
@@ -38,14 +40,12 @@ def distillation_loss(student_logits, teacher_logits, temperature=1.0, reduction
 
 def train_epoch(epoch, loader, iters, teacher_model, lm_config_student, start_step=0, wandb=None, alpha=0.0, temperature=1.0):
     start_time = time.time()
-    last_step = start_step
     
     if teacher_model is not None:
         teacher_model.eval()
         teacher_model.requires_grad_(False)
 
     for step, (input_ids, labels) in enumerate(loader, start=start_step + 1):
-        last_step = step
         input_ids = input_ids.to(args.device)
         labels = labels.to(args.device)
         loss_mask = (labels[..., 1:] != -100).float()
@@ -94,7 +94,7 @@ def train_epoch(epoch, loader, iters, teacher_model, lm_config_student, start_st
 
         scaler.scale(loss).backward()
 
-        if step % args.accumulation_steps == 0:
+        if step % args.accumulation_steps == 0 or step == iters:
             scaler.unscale_(optimizer)
             torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
             scaler.step(optimizer)
@@ -135,13 +135,6 @@ def train_epoch(epoch, loader, iters, teacher_model, lm_config_student, start_st
 
         del input_ids, labels, loss_mask, res, student_logits, ce_loss, distill_loss, loss
 
-    if last_step > start_step and last_step % args.accumulation_steps != 0:
-        scaler.unscale_(optimizer)
-        torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
-        scaler.step(optimizer)
-        scaler.update()
-        optimizer.zero_grad(set_to_none=True)
-
 
 if __name__ == "__main__":
     # 模拟用moe模型蒸馏dense模型,也可以用更大teacher_hidden_size模型蒸馏更小student_hidden_size的

+ 1 - 10
trainer/train_dpo.py

@@ -52,10 +52,8 @@ def dpo_loss(ref_log_probs, policy_log_probs, mask, beta):
 
 def train_epoch(epoch, loader, iters, ref_model, lm_config, start_step=0, wandb=None, beta=0.1):
     start_time = time.time()
-    last_step = start_step
 
     for step, batch in enumerate(loader, start=start_step + 1):
-        last_step = step
         x_chosen = batch['x_chosen'].to(args.device)
         x_rejected = batch['x_rejected'].to(args.device)
         y_chosen = batch['y_chosen'].to(args.device)
@@ -86,7 +84,7 @@ def train_epoch(epoch, loader, iters, ref_model, lm_config, start_step=0, wandb=
 
         scaler.scale(loss).backward()
 
-        if step % args.accumulation_steps == 0:
+        if step % args.accumulation_steps == 0 or step == iters:
             scaler.unscale_(optimizer)
             torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
             scaler.step(optimizer)
@@ -120,13 +118,6 @@ def train_epoch(epoch, loader, iters, ref_model, lm_config, start_step=0, wandb=
         del x_chosen, x_rejected, y_chosen, y_rejected, mask_chosen, mask_rejected, x, y, mask
         del ref_outputs, ref_logits, ref_log_probs, outputs, logits, policy_log_probs, loss
 
-    if last_step > start_step and last_step % args.accumulation_steps != 0:
-        scaler.unscale_(optimizer)
-        torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
-        scaler.step(optimizer)
-        scaler.update()
-        optimizer.zero_grad(set_to_none=True)
-
 
 if __name__ == "__main__":
     parser = argparse.ArgumentParser(description="MiniMind DPO (Direct Preference Optimization)")

+ 1 - 10
trainer/train_full_sft.py

@@ -23,11 +23,9 @@ warnings.filterwarnings('ignore')
 
 def train_epoch(epoch, loader, iters, start_step=0, wandb=None):
     start_time = time.time()
-    last_step = start_step
     for step, (input_ids, labels) in enumerate(loader, start=start_step + 1):
         input_ids = input_ids.to(args.device)
         labels = labels.to(args.device)
-        last_step = step
         lr = get_lr(epoch * iters + step, args.epochs * iters, args.learning_rate)
         for param_group in optimizer.param_groups:
             param_group['lr'] = lr
@@ -39,7 +37,7 @@ def train_epoch(epoch, loader, iters, start_step=0, wandb=None):
 
         scaler.scale(loss).backward()
 
-        if step % args.accumulation_steps == 0:
+        if step % args.accumulation_steps == 0 or step == iters:
             scaler.unscale_(optimizer)
             torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
 
@@ -73,13 +71,6 @@ def train_epoch(epoch, loader, iters, start_step=0, wandb=None):
 
         del input_ids, labels, res, loss
 
-    if last_step > start_step and last_step % args.accumulation_steps != 0:
-        scaler.unscale_(optimizer)
-        torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
-        scaler.step(optimizer)
-        scaler.update()
-        optimizer.zero_grad(set_to_none=True)
-
 
 if __name__ == "__main__":
     parser = argparse.ArgumentParser(description="MiniMind Full SFT")

+ 2 - 15
trainer/train_grpo.py

@@ -22,18 +22,12 @@ from torch.optim.lr_scheduler import CosineAnnealingLR
 from transformers import AutoModel
 from model.model_minimind import MiniMindConfig, MiniMindForCausalLM
 from dataset.lm_dataset import RLAIFDataset
-from trainer.trainer_utils import Logger, is_main_process, lm_checkpoint, init_distributed_mode, setup_seed, SkipBatchSampler, init_model, LMForRewardModel
+from trainer.trainer_utils import Logger, is_main_process, lm_checkpoint, init_distributed_mode, setup_seed, SkipBatchSampler, init_model, LMForRewardModel, rep_penalty
 from trainer.rollout_engine import create_rollout_engine
 
 warnings.filterwarnings('ignore')
 
 
-def rep_penalty(text, n=3, cap=0.5):
-    toks = re.findall(r"\w+|[^\w\s]", text.lower())
-    grams = [tuple(toks[i:i + n]) for i in range(len(toks) - n + 1)]
-    return min(cap, (len(grams) - len(set(grams))) * cap * 2 / len(grams)) if grams else 0.0
-
-
 def calculate_rewards(prompts, responses, reward_model):
     rewards = torch.zeros(len(responses), device=args.device)
 
@@ -144,7 +138,7 @@ def grpo_train_epoch(epoch, loader, iters, rollout_engine, ref_model, reward_mod
         loss = (policy_loss + aux_loss) / args.accumulation_steps  # scalar
         loss.backward()
 
-        if step % args.accumulation_steps == 0:
+        if step % args.accumulation_steps == 0 or step == iters:
             if args.grad_clip > 0:
                 torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
             optimizer.step()
@@ -195,13 +189,6 @@ def grpo_train_epoch(epoch, loader, iters, rollout_engine, ref_model, reward_mod
         del prompt_inputs, outputs, completion_ids, per_token_logps, ref_per_token_logps
         del completions, rewards, grouped_rewards, mean_r, std_r, advantages, completion_mask, completion_pad_mask, prompt_lens, logp_pos
 
-    if step > start_step and step % args.accumulation_steps != 0:
-        if args.grad_clip > 0:
-            torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
-        optimizer.step()
-        scheduler.step()
-        optimizer.zero_grad()
-
 
 if __name__ == "__main__":
     parser = argparse.ArgumentParser(description="MiniMind GRPO (Group Relative Policy Optimization)")

+ 4 - 11
trainer/train_lora.py

@@ -24,11 +24,9 @@ warnings.filterwarnings('ignore')
 
 def train_epoch(epoch, loader, iters, lora_params, start_step=0, wandb=None):
     start_time = time.time()
-    last_step = start_step
     for step, (input_ids, labels) in enumerate(loader, start=start_step + 1):
         input_ids = input_ids.to(args.device)
         labels = labels.to(args.device)
-        last_step = step
         lr = get_lr(epoch * iters + step, args.epochs * iters, args.learning_rate)
         for param_group in optimizer.param_groups:
             param_group['lr'] = lr
@@ -40,7 +38,7 @@ def train_epoch(epoch, loader, iters, lora_params, start_step=0, wandb=None):
 
         scaler.scale(loss).backward()
 
-        if step % args.accumulation_steps == 0:
+        if step % args.accumulation_steps == 0 or step == iters:
             scaler.unscale_(optimizer)
             torch.nn.utils.clip_grad_norm_(lora_params, args.grad_clip)
             scaler.step(optimizer)
@@ -68,16 +66,11 @@ def train_epoch(epoch, loader, iters, lora_params, start_step=0, wandb=None):
 
         del input_ids, labels, res, loss
 
-    if last_step > start_step and last_step % args.accumulation_steps != 0:
-        scaler.unscale_(optimizer)
-        torch.nn.utils.clip_grad_norm_(lora_params, args.grad_clip)
-        scaler.step(optimizer)
-        scaler.update()
-        optimizer.zero_grad(set_to_none=True)
-
 if __name__ == "__main__":
     parser = argparse.ArgumentParser(description="MiniMind LoRA Fine-tuning")
     parser.add_argument("--save_dir", type=str, default="../out", help="模型保存目录")
+    parser.add_argument("--lora_rank", default=16, type=int, help="LoRA rank")
+    parser.add_argument("--lora_alpha", default=None, type=float, help="LoRA alpha(默认等于 rank,即 scaling=1)")
     parser.add_argument("--lora_name", type=str, default="lora_medical", help="LoRA权重名称(如lora_identity/lora_medical等)")
     parser.add_argument("--epochs", type=int, default=10, help="训练轮数")
     parser.add_argument("--batch_size", type=int, default=32, help="batch size")
@@ -127,7 +120,7 @@ if __name__ == "__main__":
     
     # ========== 5. 定义模型、应用LoRA、冻结非LoRA参数 ==========
     model, tokenizer = init_model(lm_config, args.from_weight, device=args.device)
-    apply_lora(model)
+    apply_lora(model, rank=args.lora_rank, lora_alpha=args.lora_alpha)
     
     # 统计参数
     total_params = sum(p.numel() for p in model.parameters())

+ 1 - 7
trainer/train_ppo.py

@@ -20,18 +20,12 @@ from torch.nn.utils import clip_grad_norm_
 from torch.optim.lr_scheduler import CosineAnnealingLR
 from model.model_minimind import MiniMindConfig, MiniMindForCausalLM
 from dataset.lm_dataset import RLAIFDataset
-from trainer.trainer_utils import Logger, is_main_process, lm_checkpoint, init_distributed_mode, setup_seed, SkipBatchSampler, init_model, LMForRewardModel
+from trainer.trainer_utils import Logger, is_main_process, lm_checkpoint, init_distributed_mode, setup_seed, SkipBatchSampler, init_model, LMForRewardModel, rep_penalty
 from trainer.rollout_engine import create_rollout_engine
 
 warnings.filterwarnings('ignore')
 
 
-def rep_penalty(text, n=3, cap=0.5):
-    toks = re.findall(r"\w+|[^\w\s]", text.lower())
-    grams = [tuple(toks[i:i + n]) for i in range(len(toks) - n + 1)]
-    return min(cap, (len(grams) - len(set(grams))) * cap * 2 / len(grams)) if grams else 0.0
-
-
 # 自定义的Critic模型,继承自MiniMindLM
 class CriticModel(MiniMindForCausalLM):
     def __init__(self, params):

+ 1 - 10
trainer/train_pretrain.py

@@ -23,11 +23,9 @@ warnings.filterwarnings('ignore')
 
 def train_epoch(epoch, loader, iters, start_step=0, wandb=None):
     start_time = time.time()
-    last_step = start_step
     for step, (input_ids, labels) in enumerate(loader, start=start_step + 1):
         input_ids = input_ids.to(args.device)
         labels = labels.to(args.device)
-        last_step = step
         lr = get_lr(epoch * iters + step, args.epochs * iters, args.learning_rate)
         for param_group in optimizer.param_groups:
             param_group['lr'] = lr
@@ -39,7 +37,7 @@ def train_epoch(epoch, loader, iters, start_step=0, wandb=None):
 
         scaler.scale(loss).backward()
 
-        if step % args.accumulation_steps == 0:
+        if step % args.accumulation_steps == 0 or step == iters:
             scaler.unscale_(optimizer)
             torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
 
@@ -72,13 +70,6 @@ def train_epoch(epoch, loader, iters, start_step=0, wandb=None):
 
         del input_ids, labels, res, loss
 
-    if last_step > start_step and last_step % args.accumulation_steps != 0:
-        scaler.unscale_(optimizer)
-        torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
-        scaler.step(optimizer)
-        scaler.update()
-        optimizer.zero_grad(set_to_none=True)
-
 
 if __name__ == "__main__":
     parser = argparse.ArgumentParser(description="MiniMind Pretraining")

+ 24 - 4
trainer/trainer_utils.py

@@ -8,6 +8,7 @@ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
 import ast
 import operator
 import random
+import re
 import math
 import numpy as np
 import torch
@@ -17,6 +18,7 @@ from torch.utils.data import Sampler
 from transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassification
 from model.model_minimind import MiniMindForCausalLM
 
+# ======== 模型参数量 ========
 def get_model_params(model, config):
     total = sum(p.numel() for p in model.parameters()) / 1e6
     n_routed = getattr(config, 'n_routed_experts', getattr(config, 'num_experts', 0))
@@ -30,15 +32,18 @@ def get_model_params(model, config):
     else: Logger(f'Model Params: {total:.2f}M')
 
 
+# ======== 主进程判断 ========
 def is_main_process():
     return not dist.is_initialized() or dist.get_rank() == 0
 
 
+# ======== 日志 ========
 def Logger(content):
     if is_main_process():
         print(content)
 
 
+# ======== 学习率 ========
 def get_lr(current_step, total_steps, lr, warmup_frac=0.0):
     # warmup_frac=0(默认)时与原实现逐值相同。需要 warmup 的场景可以传入一个比例,
     # 前 warmup_frac*total_steps 步把 lr 线性升到满值,其后在剩余步数上走原来的余弦。
@@ -51,6 +56,7 @@ def get_lr(current_step, total_steps, lr, warmup_frac=0.0):
     return lr*(0.1 + 0.45*(1 + math.cos(math.pi * current_step / total_steps)))
 
 
+# ======== 分布式初始化 ========
 def init_distributed_mode():
     if int(os.environ.get("RANK", -1)) == -1:
         return 0  # 非DDP模式
@@ -61,6 +67,7 @@ def init_distributed_mode():
     return local_rank
 
 
+# ======== 随机种子 ========
 def setup_seed(seed: int):
     random.seed(seed)
     np.random.seed(seed)
@@ -70,6 +77,8 @@ def setup_seed(seed: int):
     torch.backends.cudnn.deterministic = True
     torch.backends.cudnn.benchmark = False
 
+
+# ======== 断点保存与续训 ========
 def lm_checkpoint(lm_config, weight='full_sft', model=None, optimizer=None, epoch=0, step=0, wandb=None, save_dir='../checkpoints', **kwargs):
     os.makedirs(save_dir, exist_ok=True)
     moe_path = '_moe' if lm_config.use_moe else ''
@@ -79,10 +88,9 @@ def lm_checkpoint(lm_config, weight='full_sft', model=None, optimizer=None, epoc
     if model is not None:
         raw_model = model.module if isinstance(model, DistributedDataParallel) else model
         raw_model = getattr(raw_model, '_orig_mod', raw_model)
-        state_dict = raw_model.state_dict()
-        state_dict = {k: v.half().cpu() for k, v in state_dict.items()}
+        state_dict = {k: v.cpu() for k, v in raw_model.state_dict().items()}
         ckp_tmp = ckp_path + '.tmp'
-        torch.save(state_dict, ckp_tmp)
+        torch.save({k: v.half() for k, v in state_dict.items()}, ckp_tmp)
         os.replace(ckp_tmp, ckp_path)
         wandb_id = None
         if wandb:
@@ -126,6 +134,7 @@ def lm_checkpoint(lm_config, weight='full_sft', model=None, optimizer=None, epoc
         return None
 
 
+# ======== 模型初始化 ========
 def init_model(lm_config, from_weight='pretrain', tokenizer_path='../model', save_dir='../out', device='cuda'):
     tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
     model = MiniMindForCausalLM(lm_config)
@@ -141,6 +150,7 @@ def init_model(lm_config, from_weight='pretrain', tokenizer_path='../model', sav
     return model.to(device), tokenizer
 
 
+# ======== 跳过批次采样器 ========
 class SkipBatchSampler(Sampler):
     def __init__(self, sampler, batch_size, skip_batches=0):
         self.sampler = sampler
@@ -167,6 +177,7 @@ class SkipBatchSampler(Sampler):
         return max(0, total_batches - self.skip_batches)
 
 
+# ======== 奖励模型 ========
 class LMForRewardModel:
     def __init__(self, model_path, device="cuda", dtype=torch.float16):
         self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
@@ -187,7 +198,7 @@ class LMForRewardModel:
         return max(min(score, 3.0), -3.0)
 
 
-# ===== 数学表达式安全求值:替代 eval,只放行算术运算与 math 白名单(长度上限 512) =====
+# ======== 数学表达式安全求值 ========
 def safe_math_eval(expression):
     """对模型生成的数学表达式求值:支持 + - * / // % **、math 白名单函数与 pi/e/tau 常量。"""
     def pow_guard(base, exp):  # 幂运算统一走这里,拦截 9**9**9 / 10**99999 这类把进程算死的输入
@@ -215,3 +226,12 @@ def safe_math_eval(expression):
         return walk(ast.parse(expr, mode='eval').body)
     except (KeyError, SyntaxError, TypeError):
         raise ValueError('不支持的表达式语法') from None
+
+
+# ======== 重复惩罚 ========
+def rep_penalty(text, n=3, cap=0.5):
+    cjk = ("\u3007\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af"
+           "\U00020000-\U0002ee5f\U0002f800-\U0002fa1f\U00030000-\U0003347f")
+    toks = re.findall(rf"[{cjk}]|[^\W{cjk}]+|[^\w\s]", text.lower())
+    grams = [tuple(toks[i:i + n]) for i in range(len(toks) - n + 1)]
+    return min(cap, (len(grams) - len(set(grams))) * cap * 2 / len(grams)) if grams else 0.0