| 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 |
|
|
| |
| |
| |
| |
| |
| |
| |
| ''' |
| 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/data_processing_hsichen/data_process_bq/model/qwen3_4b_rm_v2.2_merged" |
| 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 |
| MAX_SEQ_LEN = 1024 |
| USE_FP16 = True |
| USE_COMPILE = False |
|
|
| |
| 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) |
|
|
| |
| if hasattr(model.config, "use_cache"): |
| model.config.use_cache = False |
|
|
| |
| if USE_COMPILE and hasattr(torch, "compile"): |
| |
| model = torch.compile(model, mode="max-autotune") |
|
|
| |
| |
| |
|
|
| 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}" |
|
|
| |
| |
| |
| def get_reward_score(prompts): |
| """ |
| 输入: list[str] |
| 输出: list[float] |
| """ |
| |
| inputs = tokenizer( |
| prompts, return_tensors="pt", padding=True, truncation=True, max_length=MAX_SEQ_LEN |
| ).to(device) |
|
|
| |
| with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=True): |
| with torch.no_grad(): |
| |
| 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) |
| last_hidden = outputs.last_hidden_state |
| last_token_hidden = last_hidden[:, -1, :] |
| scores = model.v_head(last_token_hidden).squeeze(-1) |
| 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) |
|
|
| |
| |
| |
| 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] |
|
|
| |
| 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]) |
|
|
| |
| try: |
| scores = get_reward_score(prompts) |
| except torch.cuda.OutOfMemoryError: |
| torch.cuda.empty_cache() |
| |
| if cur_bs == 1: |
| |
| 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 |
|
|
| |
| 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}") |
|
|