prt14-codebase / examples /prt12_qwen25vl /inference_prt12.py
rosssso's picture
Upload folder using huggingface_hub
09c07bd verified
import torch
import torch.nn.functional as F
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
from peft import PeftModel
from PIL import Image
import requests
import argparse
@torch.no_grad()
def prt_greedy_generate(
ref_model,
reward_model,
input_ids,
attention_mask=None,
pixel_values=None,
image_grid_thw=None,
video_grid_thw=None,
max_new_tokens=64,
eos_token_id=None,
):
"""
PRT (Portable Reward Tuning) を用いた Greedy 生成関数
論文の Algorithm 2 (Inference/Generation) を実装しています。
毎回のトークン生成ステップにおいて、RefモデルとRewardモデルの両方を推論し、
その出力を合成して次のトークンを決定します。
数式: v_theta = log_softmax(ref_logits) + reward_logits
"""
# 評価モードへ
ref_model.eval()
reward_model.eval()
# KV Cache (過去の計算結果) の初期化
# これを使うことで、過去のトークンを再計算せずに済み、高速化できます。
past_ref = None
past_reward = None
# 入力IDの形状確認 (Batch, Seq)
if input_ids.dim() == 1:
input_ids = input_ids.unsqueeze(0)
current_input_ids = input_ids
generated_ids = input_ids.clone()
first_step = True # 最初のステップだけ画像入力を渡すフラグ
# トークン生成ループ
for i in range(max_new_tokens):
# --- 1. 報酬モデル (Reward Model) の推論 ---
reward_kwargs = {
"use_cache": True,
"past_key_values": past_reward
}
# 初回のみ画像関連の入力を渡します (以降は past_key_values に保存されるため不要)
if first_step:
reward_kwargs.update({
"attention_mask": attention_mask,
"pixel_values": pixel_values,
"image_grid_thw": image_grid_thw,
"video_grid_thw": video_grid_thw,
})
out_r = reward_model(
input_ids=current_input_ids,
**reward_kwargs
)
past_reward = out_r.past_key_values
# 最後のトークンのロジットのみを取得 [Batch, Vocab]
reward_logits = out_r.logits[:, -1, :]
# --- 2. 参照モデル (Ref Model) の推論 ---
ref_kwargs = {
"use_cache": True,
"past_key_values": past_ref
}
if first_step:
ref_kwargs.update({
"attention_mask": attention_mask,
"pixel_values": pixel_values,
"image_grid_thw": image_grid_thw,
"video_grid_thw": video_grid_thw,
})
out_ref = ref_model(
input_ids=current_input_ids,
**ref_kwargs
)
past_ref = out_ref.past_key_values
# 最後のトークンのロジットのみを取得 [Batch, Vocab]
ref_logits = out_ref.logits[:, -1, :]
# --- 3. PRT合成 (Composition) ---
# ここで2つのモデルの出力を合成します。
# Refモデルは確率分布に変換してから対数を取り (LogSoftmax)、
# Rewardモデルは生のロジット (Logits) をそのまま足します。
scores = torch.log_softmax(ref_logits, dim=-1) + reward_logits
# Greedy Search: スコアが最大のトークンを選択
next_token = torch.argmax(scores, dim=-1, keepdim=True)
# 生成結果に追加
generated_ids = torch.cat([generated_ids, next_token], dim=-1)
# 次のステップの入力は、今生成したトークンのみ
current_input_ids = next_token
first_step = False
# 終了判定 (EOSトークンが出たら終了)
if eos_token_id is not None and (next_token == eos_token_id).all():
break
return generated_ids
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model_id", type=str, default="Qwen/Qwen2.5-VL-3B-Instruct")
parser.add_argument("--adapter_path", type=str, default=None, help="学習済みアダプタのパス")
parser.add_argument("--image_path", type=str, default="http://images.cocodataset.org/val2017/000000039769.jpg")
parser.add_argument("--prompt", type=str, default="Describe this image.")
args = parser.parse_args()
# デバイス設定 (CUDA > MPS > CPU)
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
dtype = torch.bfloat16 if device != "cpu" else torch.float32 # CPUはBFloat16未対応の場合があるため
print(f"Using device: {device}")
# --- モデルのロード ---
# 1. Reference Model (凍結モデル)
print(f"Loading Ref Model: {args.model_id}...")
ref_model = Qwen2VLForConditionalGeneration.from_pretrained(
args.model_id,
torch_dtype=dtype,
device_map=device,
trust_remote_code=True
).eval()
# 2. Reward Model (ベース + アダプタ)
print(f"Loading Reward Model Base: {args.model_id}...")
reward_model = Qwen2VLForConditionalGeneration.from_pretrained(
args.model_id,
torch_dtype=dtype,
device_map=device,
trust_remote_code=True
)
if args.adapter_path:
print(f"Loading Adapter from {args.adapter_path}...")
# 学習済みのLoRAアダプタをマージしてロード
reward_model = PeftModel.from_pretrained(reward_model, args.adapter_path)
else:
print("アダプタパスが指定されていません。ベースモデルのみ(報酬なし)として動作します。")
reward_model.to(device).eval()
# --- データ処理 ---
processor = AutoProcessor.from_pretrained(args.model_id, trust_remote_code=True)
# 画像ロード
if args.image_path.startswith("http"):
image = Image.open(requests.get(args.image_path, stream=True).raw).convert("RGB")
else:
image = Image.open(args.image_path).convert("RGB")
# プロンプト作成
messages = [
{
"role": "user",
"content": [
{"type": "image", "image": image},
{"type": "text", "text": args.prompt},
],
}
]
text_prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
# 入力テンソル作成
inputs = processor(
text=[text_prompt],
images=[image],
padding=True,
return_tensors="pt",
).to(device)
# --- 生成実行 ---
print("Generating...")
gen_ids = prt_greedy_generate(
ref_model=ref_model,
reward_model=reward_model,
input_ids=inputs.input_ids,
attention_mask=inputs.attention_mask,
pixel_values=inputs.pixel_values,
image_grid_thw=inputs.image_grid_thw,
max_new_tokens=100,
eos_token_id=processor.tokenizer.eos_token_id
)
# デコードして表示
# 入力プロンプト部分を除去して、生成されたテキストのみを取り出します
generated_ids_trimmed = [
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, gen_ids)
]
output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)
print("\n[Output]:")
print(output_text[0])
if __name__ == "__main__":
main()