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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Union
|
| 2 |
+
|
| 3 |
+
import deepspeed
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from flash_attn.utils.distributed import all_gather
|
| 7 |
+
from peft import LoraConfig, get_peft_model
|
| 8 |
+
from peft.tuners.lora import LoraLayer
|
| 9 |
+
from transformers import AutoConfig, AutoModel, BitsAndBytesConfig
|
| 10 |
+
from transformers.integrations.deepspeed import HfDeepSpeedConfig
|
| 11 |
+
|
| 12 |
+
from openrlhf.utils.logging_utils import init_logger
|
| 13 |
+
|
| 14 |
+
from .ring_attn_utils import convert_ring_attn_params
|
| 15 |
+
from .utils import reset_position_ids
|
| 16 |
+
|
| 17 |
+
logger = init_logger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# Construct transformer with a value head for sequence classification.
|
| 21 |
+
# https://github.com/huggingface/transformers/blob/405b56269812056d9593869e22b7b264d806cb1e/src/transformers/models/llama/modeling_llama.py#L1254
|
| 22 |
+
def get_llm_for_sequence_regression(
|
| 23 |
+
model_name_or_path: str,
|
| 24 |
+
model_type: str,
|
| 25 |
+
*,
|
| 26 |
+
bf16=True,
|
| 27 |
+
load_in_4bit=False,
|
| 28 |
+
lora_rank=0,
|
| 29 |
+
lora_alpha=16,
|
| 30 |
+
target_modules=None,
|
| 31 |
+
lora_dropout=0,
|
| 32 |
+
normalize_reward=False,
|
| 33 |
+
use_flash_attention_2=False,
|
| 34 |
+
ds_config: dict = None,
|
| 35 |
+
init_value_head: bool = False,
|
| 36 |
+
value_head_prefix="score",
|
| 37 |
+
device_map=None,
|
| 38 |
+
packing_samples=False,
|
| 39 |
+
**kwargs,
|
| 40 |
+
) -> nn.Module:
|
| 41 |
+
"""Retrieve a transformer model with a sequence regression head on top.
|
| 42 |
+
|
| 43 |
+
This function loads a pretrained transformer model and attaches a linear layer for sequence regression.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
model_name_or_path (str): Path to the pretrained model.
|
| 47 |
+
model_type (str): Type of the model, either "reward" or "critic".
|
| 48 |
+
bf16 (bool, optional): Enable bfloat16 precision. Defaults to True.
|
| 49 |
+
load_in_4bit (bool, optional): Load the model in 4-bit precision. Defaults to False.
|
| 50 |
+
lora_rank (int, optional): Rank for LoRA adaptation. Defaults to 0.
|
| 51 |
+
lora_alpha (int, optional): Alpha parameter for LoRA. Defaults to 16.
|
| 52 |
+
target_modules (list, optional): List of target modules for LoRA. Defaults to None.
|
| 53 |
+
lora_dropout (float, optional): Dropout rate for LoRA layers. Defaults to 0.
|
| 54 |
+
normalize_reward (bool, optional): Normalize reward values. Defaults to False.
|
| 55 |
+
use_flash_attention_2 (bool, optional): Use Flash Attention 2.0. Defaults to False.
|
| 56 |
+
ds_config (dict, optional): Deepspeed configuration for model partitioning across multiple GPUs when ZeRO-3 is enabled. Defaults to None.
|
| 57 |
+
init_value_head (bool, optional): Initialize the value head. Defaults to False.
|
| 58 |
+
value_head_prefix (str, optional): Prefix for the value head. Defaults to "score".
|
| 59 |
+
device_map (dict, optional): Map of devices for model loading. Defaults to None.
|
| 60 |
+
packing_samples (bool, optional): Whether to pack samples during training. Defaults to False.
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
nn.Module: A pretrained transformer model with a sequence regression head.
|
| 64 |
+
"""
|
| 65 |
+
assert (
|
| 66 |
+
model_type == "critic" or model_type == "reward"
|
| 67 |
+
), f"invalid model_type: {model_type}, should be critic or reward."
|
| 68 |
+
|
| 69 |
+
config = AutoConfig.from_pretrained(model_name_or_path, trust_remote_code=True)
|
| 70 |
+
config.normalize_reward = normalize_reward
|
| 71 |
+
config._attn_implementation = "flash_attention_2" if use_flash_attention_2 else "eager"
|
| 72 |
+
|
| 73 |
+
# Prioritize using the value_head_prefix in the model configuration.
|
| 74 |
+
value_head_prefix = getattr(config, "value_head_prefix", value_head_prefix)
|
| 75 |
+
logger.info(f"set value_head_prefix to `{value_head_prefix}`")
|
| 76 |
+
|
| 77 |
+
base_class = AutoModel._model_mapping[type(config)]
|
| 78 |
+
base_pretrained_class = base_class.__base__
|
| 79 |
+
if model_type == "reward":
|
| 80 |
+
cls_class = _get_reward_model(base_pretrained_class, base_class, value_head_prefix, packing_samples)
|
| 81 |
+
else:
|
| 82 |
+
cls_class = _get_critic_model(base_pretrained_class, base_class, value_head_prefix, packing_samples)
|
| 83 |
+
|
| 84 |
+
# Note: dschf is defined in function scope to avoid global effects
|
| 85 |
+
# https://huggingface.co/docs/transformers/main_classes/deepspeed#nontrainer-deepspeed-integration
|
| 86 |
+
if ds_config is not None and ds_config["zero_optimization"]["stage"] == 3:
|
| 87 |
+
dschf = HfDeepSpeedConfig(ds_config)
|
| 88 |
+
else:
|
| 89 |
+
dschf = None
|
| 90 |
+
|
| 91 |
+
if load_in_4bit:
|
| 92 |
+
assert bf16, "we only support bnb_4bit_compute_dtype = bf16"
|
| 93 |
+
nf4_config = BitsAndBytesConfig(
|
| 94 |
+
load_in_4bit=True,
|
| 95 |
+
bnb_4bit_quant_type="nf4",
|
| 96 |
+
bnb_4bit_use_double_quant=True,
|
| 97 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 98 |
+
)
|
| 99 |
+
else:
|
| 100 |
+
nf4_config = None
|
| 101 |
+
|
| 102 |
+
model = cls_class.from_pretrained(
|
| 103 |
+
model_name_or_path,
|
| 104 |
+
config=config,
|
| 105 |
+
trust_remote_code=True,
|
| 106 |
+
torch_dtype=torch.bfloat16 if bf16 else "auto",
|
| 107 |
+
quantization_config=nf4_config,
|
| 108 |
+
device_map=device_map,
|
| 109 |
+
**kwargs,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# LoRA
|
| 113 |
+
if lora_rank > 0:
|
| 114 |
+
model.enable_input_require_grads()
|
| 115 |
+
lora_config = LoraConfig(
|
| 116 |
+
r=lora_rank,
|
| 117 |
+
lora_alpha=lora_alpha,
|
| 118 |
+
target_modules=target_modules,
|
| 119 |
+
lora_dropout=lora_dropout,
|
| 120 |
+
bias="none",
|
| 121 |
+
)
|
| 122 |
+
model = get_peft_model(model, lora_config)
|
| 123 |
+
|
| 124 |
+
if load_in_4bit:
|
| 125 |
+
for name, module in model.named_modules():
|
| 126 |
+
if isinstance(module, LoraLayer):
|
| 127 |
+
module = module.to(torch.bfloat16)
|
| 128 |
+
if "norm" in name:
|
| 129 |
+
module = module.to(torch.float32)
|
| 130 |
+
if value_head_prefix in name or "embed_tokens" in name:
|
| 131 |
+
if hasattr(module, "weight"):
|
| 132 |
+
module = module.to(torch.bfloat16)
|
| 133 |
+
|
| 134 |
+
# MoE - balancing loss
|
| 135 |
+
model_config = model.config.to_dict()
|
| 136 |
+
if "output_router_logits" in model_config:
|
| 137 |
+
print("[MoE] set output_router_logits as True")
|
| 138 |
+
model.config.output_router_logits = True
|
| 139 |
+
|
| 140 |
+
# https://github.com/huggingface/transformers/issues/26877
|
| 141 |
+
model.config.use_cache = False
|
| 142 |
+
|
| 143 |
+
# NOTE: For reward model training only, intialize value_head manually
|
| 144 |
+
# because deepspeed.zero.Init() will not intialize them.
|
| 145 |
+
# TODO: Find a better way to clarify reward model training.
|
| 146 |
+
if init_value_head:
|
| 147 |
+
value_head = getattr(model, value_head_prefix)
|
| 148 |
+
if dschf is not None:
|
| 149 |
+
logger.info("initialize value_head for ZeRO-3 reward model training.")
|
| 150 |
+
with deepspeed.zero.GatheredParameters([value_head.weight], modifier_rank=0):
|
| 151 |
+
if torch.distributed.get_rank() == 0:
|
| 152 |
+
value_head.weight.data.normal_(mean=0.0, std=1 / (config.hidden_size + 1))
|
| 153 |
+
else:
|
| 154 |
+
value_head.weight.data.normal_(mean=0.0, std=1 / (config.hidden_size + 1))
|
| 155 |
+
|
| 156 |
+
return model
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _get_reward_model(base_pretrained_model, base_llm_model, value_head_prefix="score", packing_samples=False):
|
| 160 |
+
class RewardModel(base_pretrained_model):
|
| 161 |
+
supports_gradient_checkpointing = True
|
| 162 |
+
|
| 163 |
+
def __init__(self, config: AutoConfig):
|
| 164 |
+
super().__init__(config)
|
| 165 |
+
setattr(self, self.base_model_prefix, base_llm_model(config))
|
| 166 |
+
|
| 167 |
+
self.value_head_prefix = value_head_prefix
|
| 168 |
+
setattr(self, value_head_prefix, nn.Linear(config.hidden_size, 1, bias=False))
|
| 169 |
+
|
| 170 |
+
self.packing_samples = packing_samples
|
| 171 |
+
|
| 172 |
+
# mean std
|
| 173 |
+
self.normalize_reward = config.normalize_reward
|
| 174 |
+
self.register_buffer("mean", torch.zeros(1), persistent=False)
|
| 175 |
+
self.register_buffer("std", torch.ones(1), persistent=False)
|
| 176 |
+
|
| 177 |
+
# load mean/std from config.json
|
| 178 |
+
if hasattr(config, "mean"):
|
| 179 |
+
self.mean[0] = config.mean
|
| 180 |
+
self.std[0] = config.std
|
| 181 |
+
|
| 182 |
+
def forward(
|
| 183 |
+
self,
|
| 184 |
+
input_ids: torch.LongTensor = None,
|
| 185 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 186 |
+
return_output=False,
|
| 187 |
+
ring_attn_group=None,
|
| 188 |
+
packed_seq_lens=None,
|
| 189 |
+
) -> torch.Tensor:
|
| 190 |
+
if not self.packing_samples:
|
| 191 |
+
# https://github.com/OpenRLHF/OpenRLHF/issues/217
|
| 192 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 193 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 194 |
+
else:
|
| 195 |
+
# convert attention_mask to position_ids
|
| 196 |
+
if ring_attn_group is not None:
|
| 197 |
+
input_ids, attention_mask, position_ids = convert_ring_attn_params(
|
| 198 |
+
input_ids, attention_mask, packed_seq_lens, ring_attn_group
|
| 199 |
+
)
|
| 200 |
+
else:
|
| 201 |
+
position_ids = reset_position_ids(attention_mask)
|
| 202 |
+
# explicitly ignore attention_mask for packing_samples
|
| 203 |
+
attention_mask = None
|
| 204 |
+
|
| 205 |
+
outputs = getattr(self, self.base_model_prefix)(
|
| 206 |
+
input_ids, attention_mask=attention_mask, position_ids=position_ids
|
| 207 |
+
)
|
| 208 |
+
last_hidden_states = outputs["last_hidden_state"]
|
| 209 |
+
values = getattr(self, self.value_head_prefix)(last_hidden_states).squeeze(-1)
|
| 210 |
+
|
| 211 |
+
if self.packing_samples:
|
| 212 |
+
if ring_attn_group is not None:
|
| 213 |
+
reward = all_gather(values, ring_attn_group).reshape(1, -1)
|
| 214 |
+
else:
|
| 215 |
+
reward = values
|
| 216 |
+
# TODO: convert packed_seq_lens into torch tensor in advance
|
| 217 |
+
packed_seq_lens = torch.tensor(packed_seq_lens, device=values.device)
|
| 218 |
+
eos_indices = packed_seq_lens.cumsum(dim=0) - 1
|
| 219 |
+
reward = reward.squeeze(0).gather(dim=0, index=eos_indices)
|
| 220 |
+
else:
|
| 221 |
+
eos_indices = attention_mask.size(1) - 1 - attention_mask.long().fliplr().argmax(dim=1, keepdim=True)
|
| 222 |
+
reward = values.gather(dim=1, index=eos_indices).squeeze(1)
|
| 223 |
+
|
| 224 |
+
if not self.training and self.normalize_reward:
|
| 225 |
+
reward = (reward - self.mean) / self.std
|
| 226 |
+
|
| 227 |
+
return (reward, outputs) if return_output else reward
|
| 228 |
+
|
| 229 |
+
return RewardModel
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _get_critic_model(base_pretrained_model, base_llm_model, value_head_prefix="score", packing_samples=False):
|
| 233 |
+
class CriticModel(base_pretrained_model):
|
| 234 |
+
supports_gradient_checkpointing = True
|
| 235 |
+
|
| 236 |
+
def __init__(self, config: AutoConfig):
|
| 237 |
+
super().__init__(config)
|
| 238 |
+
setattr(self, self.base_model_prefix, base_llm_model(config))
|
| 239 |
+
|
| 240 |
+
self.value_head_prefix = value_head_prefix
|
| 241 |
+
setattr(self, value_head_prefix, nn.Linear(config.hidden_size, 1, bias=False))
|
| 242 |
+
|
| 243 |
+
self.packing_samples = packing_samples
|
| 244 |
+
|
| 245 |
+
# mean std
|
| 246 |
+
self.normalize_reward = config.normalize_reward
|
| 247 |
+
self.register_buffer("mean", torch.zeros(1), persistent=False)
|
| 248 |
+
self.register_buffer("std", torch.ones(1), persistent=False)
|
| 249 |
+
|
| 250 |
+
# load mean/std from config.json
|
| 251 |
+
if hasattr(config, "mean"):
|
| 252 |
+
self.mean[0] = config.mean
|
| 253 |
+
self.std[0] = config.std
|
| 254 |
+
|
| 255 |
+
def forward(
|
| 256 |
+
self,
|
| 257 |
+
input_ids: torch.LongTensor = None,
|
| 258 |
+
num_actions: Optional[Union[int, list[int]]] = None,
|
| 259 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 260 |
+
return_output=False,
|
| 261 |
+
packed_seq_lens=None,
|
| 262 |
+
) -> torch.Tensor:
|
| 263 |
+
if not self.packing_samples:
|
| 264 |
+
# https://github.com/OpenRLHF/OpenRLHF/issues/217
|
| 265 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 266 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 267 |
+
else:
|
| 268 |
+
# convert attention_mask to position_ids
|
| 269 |
+
position_ids = reset_position_ids(attention_mask)
|
| 270 |
+
# explicitly ignore attention_mask for packing_samples
|
| 271 |
+
attention_mask = None
|
| 272 |
+
|
| 273 |
+
outputs = getattr(self, self.base_model_prefix)(
|
| 274 |
+
input_ids, attention_mask=attention_mask, position_ids=position_ids
|
| 275 |
+
)
|
| 276 |
+
last_hidden_states = outputs["last_hidden_state"]
|
| 277 |
+
values = getattr(self, self.value_head_prefix)(last_hidden_states).squeeze(-1)[:, :-1]
|
| 278 |
+
|
| 279 |
+
# normalize reward
|
| 280 |
+
if self.normalize_reward:
|
| 281 |
+
values = (values - self.mean) / self.std
|
| 282 |
+
|
| 283 |
+
if num_actions is None:
|
| 284 |
+
assert return_output
|
| 285 |
+
return outputs
|
| 286 |
+
|
| 287 |
+
if not self.packing_samples:
|
| 288 |
+
action_values = values[:, -num_actions:]
|
| 289 |
+
else:
|
| 290 |
+
assert isinstance(num_actions, list) and len(num_actions) == len(packed_seq_lens)
|
| 291 |
+
action_values = []
|
| 292 |
+
offset = 0
|
| 293 |
+
for num_action, seq_len in zip(num_actions, packed_seq_lens):
|
| 294 |
+
start, end = max(0, offset + seq_len - num_action - 1), offset + seq_len - 1
|
| 295 |
+
action_values.append(values[:, start:end])
|
| 296 |
+
offset += seq_len
|
| 297 |
+
action_values = torch.cat(action_values, dim=1)
|
| 298 |
+
|
| 299 |
+
if return_output:
|
| 300 |
+
return (action_values, outputs)
|
| 301 |
+
else:
|
| 302 |
+
return action_values
|
| 303 |
+
|
| 304 |
+
return CriticModel
|