|
@@ -8,6 +8,7 @@ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
|
|
import ast
|
|
import ast
|
|
|
import operator
|
|
import operator
|
|
|
import random
|
|
import random
|
|
|
|
|
+import re
|
|
|
import math
|
|
import math
|
|
|
import numpy as np
|
|
import numpy as np
|
|
|
import torch
|
|
import torch
|
|
@@ -17,6 +18,7 @@ from torch.utils.data import Sampler
|
|
|
from transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassification
|
|
from transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassification
|
|
|
from model.model_minimind import MiniMindForCausalLM
|
|
from model.model_minimind import MiniMindForCausalLM
|
|
|
|
|
|
|
|
|
|
+# ======== 模型参数量 ========
|
|
|
def get_model_params(model, config):
|
|
def get_model_params(model, config):
|
|
|
total = sum(p.numel() for p in model.parameters()) / 1e6
|
|
total = sum(p.numel() for p in model.parameters()) / 1e6
|
|
|
n_routed = getattr(config, 'n_routed_experts', getattr(config, 'num_experts', 0))
|
|
n_routed = getattr(config, 'n_routed_experts', getattr(config, 'num_experts', 0))
|
|
@@ -30,19 +32,23 @@ def get_model_params(model, config):
|
|
|
else: Logger(f'Model Params: {total:.2f}M')
|
|
else: Logger(f'Model Params: {total:.2f}M')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+# ======== 主进程判断 ========
|
|
|
def is_main_process():
|
|
def is_main_process():
|
|
|
return not dist.is_initialized() or dist.get_rank() == 0
|
|
return not dist.is_initialized() or dist.get_rank() == 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+# ======== 日志 ========
|
|
|
def Logger(content):
|
|
def Logger(content):
|
|
|
if is_main_process():
|
|
if is_main_process():
|
|
|
print(content)
|
|
print(content)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+# ======== 学习率 ========
|
|
|
def get_lr(current_step, total_steps, lr):
|
|
def get_lr(current_step, total_steps, lr):
|
|
|
return lr*(0.1 + 0.45*(1 + math.cos(math.pi * current_step / total_steps)))
|
|
return lr*(0.1 + 0.45*(1 + math.cos(math.pi * current_step / total_steps)))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+# ======== 分布式初始化 ========
|
|
|
def init_distributed_mode():
|
|
def init_distributed_mode():
|
|
|
if int(os.environ.get("RANK", -1)) == -1:
|
|
if int(os.environ.get("RANK", -1)) == -1:
|
|
|
return 0 # 非DDP模式
|
|
return 0 # 非DDP模式
|
|
@@ -53,6 +59,7 @@ def init_distributed_mode():
|
|
|
return local_rank
|
|
return local_rank
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+# ======== 随机种子 ========
|
|
|
def setup_seed(seed: int):
|
|
def setup_seed(seed: int):
|
|
|
random.seed(seed)
|
|
random.seed(seed)
|
|
|
np.random.seed(seed)
|
|
np.random.seed(seed)
|
|
@@ -62,6 +69,8 @@ def setup_seed(seed: int):
|
|
|
torch.backends.cudnn.deterministic = True
|
|
torch.backends.cudnn.deterministic = True
|
|
|
torch.backends.cudnn.benchmark = False
|
|
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):
|
|
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)
|
|
os.makedirs(save_dir, exist_ok=True)
|
|
|
moe_path = '_moe' if lm_config.use_moe else ''
|
|
moe_path = '_moe' if lm_config.use_moe else ''
|
|
@@ -117,6 +126,7 @@ def lm_checkpoint(lm_config, weight='full_sft', model=None, optimizer=None, epoc
|
|
|
return None
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+# ======== 模型初始化 ========
|
|
|
def init_model(lm_config, from_weight='pretrain', tokenizer_path='../model', save_dir='../out', device='cuda'):
|
|
def init_model(lm_config, from_weight='pretrain', tokenizer_path='../model', save_dir='../out', device='cuda'):
|
|
|
tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
|
|
tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
|
|
|
model = MiniMindForCausalLM(lm_config)
|
|
model = MiniMindForCausalLM(lm_config)
|
|
@@ -132,6 +142,7 @@ def init_model(lm_config, from_weight='pretrain', tokenizer_path='../model', sav
|
|
|
return model.to(device), tokenizer
|
|
return model.to(device), tokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+# ======== 跳过批次采样器 ========
|
|
|
class SkipBatchSampler(Sampler):
|
|
class SkipBatchSampler(Sampler):
|
|
|
def __init__(self, sampler, batch_size, skip_batches=0):
|
|
def __init__(self, sampler, batch_size, skip_batches=0):
|
|
|
self.sampler = sampler
|
|
self.sampler = sampler
|
|
@@ -158,6 +169,7 @@ class SkipBatchSampler(Sampler):
|
|
|
return max(0, total_batches - self.skip_batches)
|
|
return max(0, total_batches - self.skip_batches)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+# ======== 奖励模型 ========
|
|
|
class LMForRewardModel:
|
|
class LMForRewardModel:
|
|
|
def __init__(self, model_path, device="cuda", dtype=torch.float16):
|
|
def __init__(self, model_path, device="cuda", dtype=torch.float16):
|
|
|
self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
|
self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
|
@@ -178,7 +190,7 @@ class LMForRewardModel:
|
|
|
return max(min(score, 3.0), -3.0)
|
|
return max(min(score, 3.0), -3.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
-# ===== 数学表达式安全求值:替代 eval,只放行算术运算与 math 白名单(长度上限 512) =====
|
|
|
|
|
|
|
+# ======== 数学表达式安全求值 ========
|
|
|
def safe_math_eval(expression):
|
|
def safe_math_eval(expression):
|
|
|
"""对模型生成的数学表达式求值:支持 + - * / // % **、math 白名单函数与 pi/e/tau 常量。"""
|
|
"""对模型生成的数学表达式求值:支持 + - * / // % **、math 白名单函数与 pi/e/tau 常量。"""
|
|
|
def pow_guard(base, exp): # 幂运算统一走这里,拦截 9**9**9 / 10**99999 这类把进程算死的输入
|
|
def pow_guard(base, exp): # 幂运算统一走这里,拦截 9**9**9 / 10**99999 这类把进程算死的输入
|
|
@@ -206,3 +218,12 @@ def safe_math_eval(expression):
|
|
|
return walk(ast.parse(expr, mode='eval').body)
|
|
return walk(ast.parse(expr, mode='eval').body)
|
|
|
except (KeyError, SyntaxError, TypeError):
|
|
except (KeyError, SyntaxError, TypeError):
|
|
|
raise ValueError('不支持的表达式语法') from None
|
|
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
|