|
| 1 | +from typing import List, Dict |
| 2 | +from easydict import EasyDict |
| 3 | +from torch.utils.tensorboard import SummaryWriter |
| 4 | +from transformers import AutoTokenizer, AutoModelForCausalLM |
| 5 | +import torch |
| 6 | +from ding.utils import REWARD_MODEL_REGISTRY |
| 7 | +from .base_reward_model import BaseRewardModel |
| 8 | + |
| 9 | + |
| 10 | +@REWARD_MODEL_REGISTRY.register('multi_modal') |
| 11 | +class MultiModalRewardModel(BaseRewardModel): |
| 12 | + config = dict( |
| 13 | + type='multi_modal', |
| 14 | + model_name='internlm/internlm-xcomposer2d5-7b-reward', |
| 15 | + hd_num=9, # Number of high-definition patches for image processing |
| 16 | + ) |
| 17 | + |
| 18 | + def __init__(self, config: EasyDict, device: str, logger, tb_logger: 'SummaryWriter') -> None: |
| 19 | + self.cfg = config |
| 20 | + self.device = device |
| 21 | + self.logger = logger |
| 22 | + self.tb_logger = tb_logger |
| 23 | + |
| 24 | + self.tokenizer = AutoTokenizer.from_pretrained( |
| 25 | + self.cfg.model_name, trust_remote_code=True, local_files_only=True |
| 26 | + ) |
| 27 | + self.model = AutoModelForCausalLM.from_pretrained( |
| 28 | + self.cfg.model_name, torch_dtype=torch.float16, trust_remote_code=True |
| 29 | + ) |
| 30 | + |
| 31 | + self.model.tokenizer = self.tokenizer |
| 32 | + self.model.cuda().eval() |
| 33 | + |
| 34 | + def estimate(self, data: List[Dict], image: List[str], output_mode: str = 'score') -> List[Dict]: |
| 35 | + """ |
| 36 | + Estimate rewards for multi-modal inputs using internlm-xcomposer model. |
| 37 | +
|
| 38 | + Arguments: |
| 39 | + data (List[Dict]): List of chat dictionaries, each containing: |
| 40 | + - chat (List[Dict]): List of messages, each message is a dict with: |
| 41 | + - role (str): Either "user" or "assistant" |
| 42 | + - content (str): The message content |
| 43 | + image (List[str]): List of image paths. If fewer images than chats, last image will be reused |
| 44 | + output_mode (str, optional): Evaluation mode. Defaults to 'score'. |
| 45 | + - 'score': Return reward scores for each chat |
| 46 | + - 'rank': Return ranking indices (0 is best) for all chats |
| 47 | + - 'compare': Compare first two chats (returns 1.0 for better, 0.0 for worse) |
| 48 | +
|
| 49 | + Returns: |
| 50 | + List[Dict]: Results depending on output_mode: |
| 51 | + - For 'score' mode: |
| 52 | + [{ |
| 53 | + 'reward': float, # Reward score |
| 54 | + 'metadata': { |
| 55 | + 'mode': 'score', |
| 56 | + 'chat_idx': int, # Index of the chat |
| 57 | + 'image_path': str # Path of the image used |
| 58 | + } |
| 59 | + }, ...] |
| 60 | + - For 'rank' mode: |
| 61 | + [{ |
| 62 | + 'rank': int, # Ranking position (0 is best) |
| 63 | + 'metadata': { |
| 64 | + 'mode': 'rank', |
| 65 | + 'chat_idx': int, |
| 66 | + 'image_path': str |
| 67 | + } |
| 68 | + }, ...] |
| 69 | + - For 'compare' mode: |
| 70 | + [{ |
| 71 | + 'reward': float, # 1.0 for better, 0.0 for worse |
| 72 | + 'metadata': { |
| 73 | + 'mode': 'compare', |
| 74 | + 'chat_idx': int, |
| 75 | + 'image_path': str, |
| 76 | + 'compared_with': int # Index of the compared chat |
| 77 | + } |
| 78 | + }, ...] |
| 79 | + """ |
| 80 | + # Get chat data |
| 81 | + chats = [item['chat'] for item in data] |
| 82 | + |
| 83 | + with torch.autocast(device_type='cuda', dtype=torch.float16): |
| 84 | + if output_mode == 'score': |
| 85 | + # Ensure each chat has a corresponding image, use the last image if not enough |
| 86 | + if len(image) < len(chats): |
| 87 | + image = image + [image[-1]] * (len(chats) - len(image)) |
| 88 | + |
| 89 | + # Get scores for each chat |
| 90 | + scores = [] |
| 91 | + for chat, img in zip(chats, image): |
| 92 | + score = self.model.get_score(chat, [img], hd_num=self.cfg.hd_num) |
| 93 | + scores.append(score) |
| 94 | + |
| 95 | + return [ |
| 96 | + { |
| 97 | + 'reward': float(score), |
| 98 | + 'metadata': { |
| 99 | + 'mode': 'score', |
| 100 | + 'chat_idx': idx, |
| 101 | + 'image_path': img |
| 102 | + } |
| 103 | + } for idx, (score, img) in enumerate(zip(scores, image)) |
| 104 | + ] |
| 105 | + |
| 106 | + elif output_mode == 'rank': |
| 107 | + # Use the first image for ranking |
| 108 | + img = image[0] |
| 109 | + ranks = self.model.rank(chats, [[img]] * len(chats), hd_num=self.cfg.hd_num) |
| 110 | + |
| 111 | + return [ |
| 112 | + { |
| 113 | + 'rank': int(rank), |
| 114 | + 'metadata': { |
| 115 | + 'mode': 'rank', |
| 116 | + 'chat_idx': idx, |
| 117 | + 'image_path': img |
| 118 | + } |
| 119 | + } for idx, rank in enumerate(ranks) |
| 120 | + ] |
| 121 | + |
| 122 | + elif output_mode == 'compare': |
| 123 | + if len(data) < 2: |
| 124 | + raise ValueError("Compare mode requires at least 2 samples") |
| 125 | + |
| 126 | + # Use the first image for comparison |
| 127 | + img = image[0] |
| 128 | + is_better = self.model.compare(chats[0], [img], chats[1], [img], hd_num=self.cfg.hd_num) |
| 129 | + |
| 130 | + return [ |
| 131 | + { |
| 132 | + 'reward': 1.0 if is_better else 0.0, |
| 133 | + 'metadata': { |
| 134 | + 'mode': 'compare', |
| 135 | + 'chat_idx': 0, |
| 136 | + 'image_path': img, |
| 137 | + 'compared_with': 1 |
| 138 | + } |
| 139 | + }, { |
| 140 | + 'reward': 0.0 if is_better else 1.0, |
| 141 | + 'metadata': { |
| 142 | + 'mode': 'compare', |
| 143 | + 'chat_idx': 1, |
| 144 | + 'image_path': img, |
| 145 | + 'compared_with': 0 |
| 146 | + } |
| 147 | + } |
| 148 | + ] |
| 149 | + else: |
| 150 | + raise ValueError(f"Invalid output mode: {output_mode}") |
| 151 | + |
| 152 | + def train(self): |
| 153 | + """Training is not implemented for this reward model""" |
| 154 | + self.logger.warning("Training is not implemented for this reward model") |
| 155 | + pass |
| 156 | + |
| 157 | + def collect_data(self, data: list) -> None: |
| 158 | + """Data collection is not needed for this reward model""" |
| 159 | + pass |
| 160 | + |
| 161 | + def clear_data(self) -> None: |
| 162 | + """Data clearing is not needed for this reward model""" |
| 163 | + pass |
0 commit comments