data_process_bq / script /infer /async_rm_infer.py
bingqin111's picture
Upload folder using huggingface_hub
3d27cfe verified
Raw
History Blame Contribute Delete
8.11 kB
import os
import json
import torch
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModel
from torch import nn
from safetensors.torch import load_file
# =========================
# 配置
#加速方法:
#真正的加速来自:
#✅ 批量并行(一次性喂多个样本)
#✅ AMP 半精度加速
#✅ 显存优化(禁用 cache)
'''
1.批量并行 (Batching)
传统做法:一条数据跑一次前向,GPU 每次只处理一条输入。
现在的做法:把 cur_bs 条数据拼成一个 batch,一次送进 GPU。
GPU 的矩阵乘法 (GEMM) 对大 batch 并行效率高,吞吐量提升明显。
换句话说,“加速”来自 利用 GPU 的并行算力,不是 CPU 开线程。
2.CUDA 内核并行
PyTorch 在 GPU 上的算子(比如 Attention、Linear)本身就是用 CUDA 内核实现的。
CUDA 内核里有成千上万的线程在跑矩阵乘法和 softmax,这部分完全由 GPU 管理。
你虽然没写 threading 或 multiprocessing,但 GPU 在底层自动开了成百上千个线程。
3.自动混合精度 (AMP)
with torch.cuda.amp.autocast(dtype=torch.float16):
这让很多矩阵运算走 FP16 / TensorCore,比 FP32 快 2~8 倍,还能节省显存。
所以 速度 + 批量大小 叠加,整体吞吐量大幅提高。
4.KV Cache 关闭
训练 Reward Model 不需要自回归生成,只做一次全序列前向。
关掉 KV Cache → 避免显存里存一堆 key/value,减少显存占用。
这样就能跑更大的 batch,间接提升速度。
'''
# =========================
#MODEL_PATH="/root/test/weitiao/output/qwen3_4B_rm" #v1
#MODEL_PATH="/root/test/weitiao/data_processing_hsichen/data_process_bq/model/qwen3_4B_rm_merged_v2" #v2
MODEL_PATH="/root/test/weitiao/data_processing_hsichen/data_process_bq/model/qwen3_4b_rm_v2.2_merged" #v2.2复现v2看稳定性
INPUT_FILE="/root/test/weitiao/data_processing_hsichen/data_process_bq/data/rm_dpo_scored_quota_filtered.json"
OUTPUT_FILE = "/root/test/weitiao/data_processing_hsichen/data_process_bq/data/rm_dpo_scored_infered_v1.json" # 输出结果文件
INIT_BATCH_SIZE = 32 # 初始 batch,后面会根据显存自动回退
MAX_SEQ_LEN = 1024 # 先把长度砍到 1024(从 2048 降一半,显存压力四分之一)
USE_FP16 = True # 建议保持 True
USE_COMPILE = False # 先关闭 compile,Qwen3 + inductor 在长序列上显存放大明显
# 可选:让 float32 matmul 走 TF32(速度更快;仅 Ampere+ 生效)
torch.set_float32_matmul_precision("high")
print(f"🚀 Loading reward model from: {MODEL_PATH}")
device = "cuda" if torch.cuda.is_available() else "cpu"
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
torch_dtype = torch.float16 if (USE_FP16 and torch.cuda.is_available()) else torch.float32
model = AutoModel.from_pretrained(
MODEL_PATH,
trust_remote_code=True,
torch_dtype=torch_dtype
)
# === 加载奖励头 ===
value_head_path = f"{MODEL_PATH}/value_head.safetensors"
value_head_state = load_file(value_head_path)
print("✅ Loaded value head keys:", value_head_state.keys())
hidden_size = model.config.hidden_size
value_head = nn.Linear(hidden_size, 1, bias=True)
value_head.load_state_dict({
"weight": value_head_state["v_head.summary.weight"].to(dtype=torch_dtype),
"bias": value_head_state["v_head.summary.bias"].to(dtype=torch_dtype),
})
value_head.to(device=device, dtype=torch_dtype)
model.v_head = value_head
model.eval()
model.to(device)
# 关键:禁用 KV cache;不做自回归生成,只做全序列前向,开 cache 反而占显存
if hasattr(model.config, "use_cache"):
model.config.use_cache = False
# 先不要 compile,稳定为主
if USE_COMPILE and hasattr(torch, "compile"):
# 对于 Qwen3 + 长序列,compile 可能放大峰值显存;确认显存足够再打开
model = torch.compile(model, mode="max-autotune")
# =========================
# 构造 prompt(保持简单,长度靠 tokenizer 截断)
# =========================
def build_prompt(conversations, response):
sys = [c["value"] for c in conversations if c["from"] == "system"]
sys_text = "\n".join([f"System: {s}" for s in sys]) + "\n" if sys else ""
hist = [
f"{c['from'].capitalize()}: {c['value']}\n"
for c in conversations if c["from"] != "system"
]
return sys_text + "".join(hist) + f"Assistant: {response}"
# =========================
# 批量打分(强制 memory-efficient attention + 自动半精度)
# =========================
def get_reward_score(prompts):
"""
输入: list[str]
输出: list[float]
"""
# 注意:decoder-only 模型下 padding='longest' 足够;让 tokenizer 自己截断到 MAX_SEQ_LEN
inputs = tokenizer(
prompts, return_tensors="pt", padding=True, truncation=True, max_length=MAX_SEQ_LEN
).to(device)
# 强制 SDPA 使用 memory-efficient kernel,避免 flash 不可用时退到 math 内核吃更多显存
with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=True):
with torch.no_grad():
# autocast 能保证偶发的 float32 op 也尽量走半精度/TF32
autocast_dtype = torch.float16 if torch_dtype == torch.float16 else torch.bfloat16
with torch.cuda.amp.autocast(dtype=autocast_dtype):
outputs = model(**inputs, use_cache=False) # 再次显式禁用 cache
last_hidden = outputs.last_hidden_state # [B, L, H]
last_token_hidden = last_hidden[:, -1, :] # [B, H]
scores = model.v_head(last_token_hidden).squeeze(-1) # [B]
return scores.detach().cpu().tolist()
# =========================
# 加载数据
# =========================
print(f"📄 Loading dataset: {INPUT_FILE}")
with open(INPUT_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
# =========================
# 自适应 batch 的主循环(OOM 自动回退)
# =========================
def score_all(data):
scored = []
i = 0
cur_bs = INIT_BATCH_SIZE
pbar = tqdm(total=len(data), desc="Scoring", dynamic_ncols=True)
try:
while i < len(data):
batch = data[i : i + cur_bs]
# 1) 打平 prompts(chosen + rejected 一起跑)
prompts = []
for sample in batch:
pc = build_prompt(sample["conversations"], sample["chosen"]["value"])
pr = build_prompt(sample["conversations"], sample["rejected"]["value"])
prompts.extend([pc, pr])
# 2) 推理(若 OOM,缩小 batch 重试)
try:
scores = get_reward_score(prompts) # [2 * cur_bs]
except torch.cuda.OutOfMemoryError:
torch.cuda.empty_cache()
# 动态降批次
if cur_bs == 1:
# 仍然 OOM:再把序列长降一档再试
raise RuntimeError(
f"OOM at batch_size=1, MAX_SEQ_LEN={MAX_SEQ_LEN}. "
f"请进一步降低 MAX_SEQ_LEN 或确保输入更短。"
)
cur_bs = max(1, cur_bs // 2)
print(f"\n⚠️ OOM detected. Reducing batch_size to {cur_bs} and retrying...")
continue
# 3) 回填
for j, sample in enumerate(batch):
rc = float(scores[2*j])
rr = float(scores[2*j + 1])
sample["reward_chosen"] = rc
sample["reward_rejected"] = rr
sample["delta_score"] = rc - rr
scored.append(sample)
i += cur_bs
pbar.update(cur_bs)
finally:
pbar.close()
return scored
print("⚡ Scoring samples...")
scored_data = score_all(data)
# =========================
# 保存结果
# =========================
with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
json.dump(scored_data, f, ensure_ascii=False, indent=2)
print(f"✅ Scoring finished! Results saved to: {OUTPUT_FILE}")