Add files using upload-large-folder tool
Browse files- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/__init__.py +44 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/core.py +329 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/extras/__init__.py +16 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/extras/best_of_n_sampler.py +113 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/extras/dataset_formatting.py +86 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/import_utils.py +108 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/models/__init__.py +35 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/models/modeling_base.py +640 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/models/modeling_sd_base.py +624 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/models/modeling_value_head.py +421 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/models/utils.py +83 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/__init__.py +46 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/base.py +46 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/ddpo_config.py +115 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/ddpo_trainer.py +604 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/dpo_trainer.py +1186 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/ppo_trainer.py +1397 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/reward_config.py +38 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/reward_trainer.py +257 -0
- 之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/sft_trainer.py +480 -0
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/__init__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa
|
| 2 |
+
|
| 3 |
+
__version__ = "0.7.11.dev0"
|
| 4 |
+
|
| 5 |
+
from .core import set_seed
|
| 6 |
+
from .environment import TextEnvironment, TextHistory
|
| 7 |
+
from .extras import BestOfNSampler
|
| 8 |
+
from .import_utils import (
|
| 9 |
+
is_bitsandbytes_available,
|
| 10 |
+
is_diffusers_available,
|
| 11 |
+
is_npu_available,
|
| 12 |
+
is_peft_available,
|
| 13 |
+
is_wandb_available,
|
| 14 |
+
is_xpu_available,
|
| 15 |
+
)
|
| 16 |
+
from .models import (
|
| 17 |
+
AutoModelForCausalLMWithValueHead,
|
| 18 |
+
AutoModelForSeq2SeqLMWithValueHead,
|
| 19 |
+
PreTrainedModelWrapper,
|
| 20 |
+
create_reference_model,
|
| 21 |
+
setup_chat_format,
|
| 22 |
+
)
|
| 23 |
+
from .trainer import (
|
| 24 |
+
DataCollatorForCompletionOnlyLM,
|
| 25 |
+
DPOTrainer,
|
| 26 |
+
IterativeSFTTrainer,
|
| 27 |
+
ModelConfig,
|
| 28 |
+
PPOConfig,
|
| 29 |
+
PPOTrainer,
|
| 30 |
+
RewardConfig,
|
| 31 |
+
RewardTrainer,
|
| 32 |
+
SFTTrainer,
|
| 33 |
+
)
|
| 34 |
+
from .trainer.utils import get_kbit_device_map, get_peft_config, get_quantization_config
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if is_diffusers_available():
|
| 38 |
+
from .models import (
|
| 39 |
+
DDPOPipelineOutput,
|
| 40 |
+
DDPOSchedulerOutput,
|
| 41 |
+
DDPOStableDiffusionPipeline,
|
| 42 |
+
DefaultDDPOStableDiffusionPipeline,
|
| 43 |
+
)
|
| 44 |
+
from .trainer import DDPOConfig, DDPOTrainer
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/core.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import gc
|
| 15 |
+
import random
|
| 16 |
+
import warnings
|
| 17 |
+
from contextlib import contextmanager
|
| 18 |
+
from typing import Dict, List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn as nn
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
from torch.nn.utils.rnn import pad_sequence
|
| 25 |
+
|
| 26 |
+
# from transformers import top_k_top_p_filtering
|
| 27 |
+
|
| 28 |
+
from .import_utils import is_npu_available, is_xpu_available
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
from collections.abc import Mapping
|
| 33 |
+
except ImportError:
|
| 34 |
+
from collections import Mapping
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
WANDB_PADDING = -1
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def top_k_top_p_filtering(
|
| 41 |
+
logits: torch.FloatTensor,
|
| 42 |
+
top_k: int = 0,
|
| 43 |
+
top_p: float = 1.0,
|
| 44 |
+
filter_value: float = -float("Inf"),
|
| 45 |
+
min_tokens_to_keep: int = 1,
|
| 46 |
+
) -> torch.FloatTensor:
|
| 47 |
+
"""
|
| 48 |
+
Filter a distribution of logits using top-k and/or nucleus (top-p) filtering.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
logits: logits distribution shape (batch size, vocabulary size)
|
| 52 |
+
top_k (`int`, *optional*, defaults to 0):
|
| 53 |
+
If > 0, only keep the top k tokens with highest probability (top-k filtering)
|
| 54 |
+
top_p (`float`, *optional*, defaults to 1.0):
|
| 55 |
+
If < 1.0, only keep the top tokens with cumulative probability >= top_p (nucleus filtering). Nucleus
|
| 56 |
+
filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
|
| 57 |
+
min_tokens_to_keep (`int`, *optional*, defaults to 1):
|
| 58 |
+
Minimumber of tokens we keep per batch example in the output.
|
| 59 |
+
|
| 60 |
+
From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
if top_k > 0:
|
| 64 |
+
logits = TopKLogitsWarper(top_k=top_k, filter_value=filter_value, min_tokens_to_keep=min_tokens_to_keep)(None, logits)
|
| 65 |
+
|
| 66 |
+
if 0 <= top_p <= 1.0:
|
| 67 |
+
logits = TopPLogitsWarper(top_p=top_p, filter_value=filter_value, min_tokens_to_keep=min_tokens_to_keep)(None, logits)
|
| 68 |
+
|
| 69 |
+
return logits
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def flatten_dict(nested: Dict, sep: str = "/") -> Dict:
|
| 73 |
+
"""Flatten dictionary and concatenate nested keys with separator."""
|
| 74 |
+
|
| 75 |
+
def recurse(nest: Dict, prefix: str, into: Dict) -> None:
|
| 76 |
+
for k, v in nest.items():
|
| 77 |
+
if sep in k:
|
| 78 |
+
raise ValueError(f"separator '{sep}' not allowed to be in key '{k}'")
|
| 79 |
+
if isinstance(v, Mapping):
|
| 80 |
+
recurse(v, prefix + k + sep, into)
|
| 81 |
+
else:
|
| 82 |
+
into[prefix + k] = v
|
| 83 |
+
|
| 84 |
+
flat = {}
|
| 85 |
+
recurse(nested, "", flat)
|
| 86 |
+
return flat
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def convert_to_scalar(stats: Dict) -> Dict:
|
| 90 |
+
"""
|
| 91 |
+
Converts the stats from a flattened dict to single scalar dicts
|
| 92 |
+
"""
|
| 93 |
+
tensorboard_stats = {}
|
| 94 |
+
for k, v in stats.items():
|
| 95 |
+
# for tensorboard compatibility - arrays and tensors are ignored with tensorboard
|
| 96 |
+
# therefore we convert single element tensors to scalars
|
| 97 |
+
if (isinstance(v, torch.Tensor) or isinstance(v, np.ndarray)) and (len(v.shape) == 0 or (len(v.shape) == 1 and v.shape[0] == 1)):
|
| 98 |
+
v = v.item()
|
| 99 |
+
tensorboard_stats[k] = v
|
| 100 |
+
return tensorboard_stats
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def stack_dicts(stats_dicts: List[Dict]) -> Dict:
|
| 104 |
+
"""Stack the values of a dict."""
|
| 105 |
+
results = dict()
|
| 106 |
+
for k in stats_dicts[0]:
|
| 107 |
+
stats_list = [torch.flatten(d[k]) for d in stats_dicts]
|
| 108 |
+
results[k] = pad_sequence(stats_list, batch_first=True, padding_value=WANDB_PADDING)
|
| 109 |
+
return results
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def add_suffix(input_dict: Dict, suffix: str) -> Dict:
|
| 113 |
+
"""Add suffix to dict keys."""
|
| 114 |
+
return dict((k + suffix, v) for k, v in input_dict.items())
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def pad_to_size(tensor: torch.Tensor, size: int, dim: int = 1, padding: int = 50256) -> torch.Tensor:
|
| 118 |
+
"""Pad tensor to size."""
|
| 119 |
+
t_size = tensor.size()[dim]
|
| 120 |
+
if t_size == size:
|
| 121 |
+
return tensor
|
| 122 |
+
else:
|
| 123 |
+
return torch.nn.functional.pad(tensor, (0, size - t_size), "constant", padding)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def logprobs_from_logits(logits: torch.Tensor, labels: torch.Tensor, gather: bool = True) -> torch.Tensor:
|
| 127 |
+
"""
|
| 128 |
+
See: https://github.com/pytorch/pytorch/issues/563#issuecomment-330103591
|
| 129 |
+
"""
|
| 130 |
+
logp = F.log_softmax(logits, dim=2)
|
| 131 |
+
|
| 132 |
+
if not gather:
|
| 133 |
+
return logp
|
| 134 |
+
logpy = torch.gather(logp, 2, labels.unsqueeze(2)).squeeze(-1)
|
| 135 |
+
return logpy
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def whiten(values: torch.Tensor, shift_mean: bool = True) -> torch.Tensor:
|
| 139 |
+
"""Whiten values."""
|
| 140 |
+
mean, var = torch.mean(values), torch.var(values)
|
| 141 |
+
whitened = (values - mean) * torch.rsqrt(var + 1e-8)
|
| 142 |
+
if not shift_mean:
|
| 143 |
+
whitened += mean
|
| 144 |
+
return whitened
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def masked_mean(values: torch.Tensor, mask: torch.Tensor, axis: bool = None) -> torch.Tensor:
|
| 148 |
+
"""Compute mean of tensor with a masked values."""
|
| 149 |
+
if axis is not None:
|
| 150 |
+
return (values * mask).sum(axis=axis) / mask.sum(axis=axis)
|
| 151 |
+
else:
|
| 152 |
+
return (values * mask).sum() / mask.sum()
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def masked_var(values: torch.Tensor, mask: torch.Tensor, unbiased: bool = True) -> torch.Tensor:
|
| 156 |
+
"""Compute variance of tensor with masked values."""
|
| 157 |
+
mean = masked_mean(values, mask)
|
| 158 |
+
centered_values = values - mean
|
| 159 |
+
variance = masked_mean(centered_values**2, mask)
|
| 160 |
+
if unbiased:
|
| 161 |
+
mask_sum = mask.sum()
|
| 162 |
+
if mask_sum == 0:
|
| 163 |
+
raise ValueError("The sum of the mask is zero, which can happen when `mini_batch_size=1`;" "try increase the `mini_batch_size` or `gradient_accumulation_steps`")
|
| 164 |
+
# note that if mask_sum == 1, then there is a division by zero issue
|
| 165 |
+
# to avoid it you just need to use a larger minibatch_size
|
| 166 |
+
bessel_correction = mask_sum / (mask_sum - 1)
|
| 167 |
+
variance = variance * bessel_correction
|
| 168 |
+
return variance
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def masked_whiten(values: torch.Tensor, mask: torch.Tensor, shift_mean: bool = True) -> torch.Tensor:
|
| 172 |
+
"""Whiten values with masked values."""
|
| 173 |
+
mean, var = masked_mean(values, mask), masked_var(values, mask)
|
| 174 |
+
whitened = (values - mean) * torch.rsqrt(var + 1e-8)
|
| 175 |
+
if not shift_mean:
|
| 176 |
+
whitened += mean
|
| 177 |
+
return whitened
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def clip_by_value(x: torch.Tensor, tensor_min: float, tensor_max: float) -> torch.Tensor:
|
| 181 |
+
"""
|
| 182 |
+
Tensor extension to torch.clamp
|
| 183 |
+
https://github.com/pytorch/pytorch/issues/2793#issuecomment-428784713
|
| 184 |
+
"""
|
| 185 |
+
clipped = torch.max(torch.min(x, tensor_max), tensor_min)
|
| 186 |
+
return clipped
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def entropy_from_logits(logits: torch.Tensor) -> torch.Tensor:
|
| 190 |
+
"""Calculate entropy from logits."""
|
| 191 |
+
pd = torch.nn.functional.softmax(logits, dim=-1)
|
| 192 |
+
entropy = torch.logsumexp(logits, axis=-1) - torch.sum(pd * logits, axis=-1)
|
| 193 |
+
return entropy
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def average_torch_dicts(list_of_dicts: List[Dict]) -> Dict:
|
| 197 |
+
"""Average values of a list of dicts with torch tensors."""
|
| 198 |
+
average_dict = dict()
|
| 199 |
+
for key in list_of_dicts[0].keys():
|
| 200 |
+
average_dict[key] = torch.mean(torch.stack([d[key] for d in list_of_dicts]), axis=0)
|
| 201 |
+
return average_dict
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def stats_to_np(stats_dict: Dict) -> Dict:
|
| 205 |
+
"""Cast all torch.tensors in dict to numpy arrays."""
|
| 206 |
+
new_dict = dict()
|
| 207 |
+
for k, v in stats_dict.items():
|
| 208 |
+
if isinstance(v, torch.Tensor):
|
| 209 |
+
new_dict[k] = v.detach().cpu()
|
| 210 |
+
if new_dict[k].dtype == torch.bfloat16:
|
| 211 |
+
new_dict[k] = new_dict[k].float()
|
| 212 |
+
new_dict[k] = new_dict[k].numpy()
|
| 213 |
+
else:
|
| 214 |
+
new_dict[k] = v
|
| 215 |
+
if np.isscalar(new_dict[k]):
|
| 216 |
+
new_dict[k] = float(new_dict[k])
|
| 217 |
+
return new_dict
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def respond_to_batch(model: nn.Module, queries: List[torch.LongTensor], txt_len: int = 20, top_k: int = 0, top_p: float = 1.0) -> torch.LongTensor:
|
| 221 |
+
"""Sample text from language model."""
|
| 222 |
+
input_ids = queries
|
| 223 |
+
for i in range(txt_len):
|
| 224 |
+
# Get Logits
|
| 225 |
+
outputs = model(input_ids)
|
| 226 |
+
next_token_logits = outputs[0][:, -1, :]
|
| 227 |
+
next_token_logits = top_k_top_p_filtering(next_token_logits, top_k=top_k, top_p=top_p)
|
| 228 |
+
# Sample
|
| 229 |
+
probs = F.softmax(next_token_logits, dim=-1)
|
| 230 |
+
next_token = torch.multinomial(probs, num_samples=1).squeeze(1)
|
| 231 |
+
input_ids = torch.cat([input_ids, next_token.unsqueeze(-1)], dim=-1)
|
| 232 |
+
return input_ids[:, -txt_len:]
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def set_seed(seed: int) -> None:
|
| 236 |
+
"""
|
| 237 |
+
Helper function for reproducible behavior to set the seed in `random`, `numpy`, and `torch`.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
seed (`int`): The seed to set.
|
| 241 |
+
"""
|
| 242 |
+
random.seed(seed)
|
| 243 |
+
np.random.seed(seed)
|
| 244 |
+
torch.manual_seed(seed)
|
| 245 |
+
if is_xpu_available():
|
| 246 |
+
torch.xpu.manual_seed_all(seed)
|
| 247 |
+
elif is_npu_available():
|
| 248 |
+
torch.npu.manual_seed_all(seed)
|
| 249 |
+
else:
|
| 250 |
+
torch.cuda.manual_seed_all(seed)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class LengthSampler:
|
| 254 |
+
"""
|
| 255 |
+
Samples a length
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
def __init__(self, min_value: int, max_value: int):
|
| 259 |
+
self.values = list(range(min_value, max_value))
|
| 260 |
+
|
| 261 |
+
def __call__(self) -> int:
|
| 262 |
+
return np.random.choice(self.values)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class PPODecorators(object):
|
| 266 |
+
optimize_device_cache = False
|
| 267 |
+
|
| 268 |
+
@classmethod
|
| 269 |
+
@contextmanager
|
| 270 |
+
def empty_device_cache(cls):
|
| 271 |
+
yield
|
| 272 |
+
if cls.optimize_device_cache:
|
| 273 |
+
if is_xpu_available():
|
| 274 |
+
gc.collect()
|
| 275 |
+
torch.xpu.empty_cache()
|
| 276 |
+
gc.collect()
|
| 277 |
+
elif is_npu_available():
|
| 278 |
+
gc.collect()
|
| 279 |
+
torch.npu.empty_cache()
|
| 280 |
+
gc.collect()
|
| 281 |
+
elif torch.cuda.is_available():
|
| 282 |
+
gc.collect()
|
| 283 |
+
torch.cuda.empty_cache()
|
| 284 |
+
gc.collect()
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def randn_tensor(
|
| 288 |
+
shape: Union[Tuple, List],
|
| 289 |
+
generator: Optional[Union[List[torch.Generator], torch.Generator]] = None,
|
| 290 |
+
device: Optional[torch.device] = None,
|
| 291 |
+
dtype: Optional[torch.dtype] = None,
|
| 292 |
+
layout: Optional[torch.layout] = None,
|
| 293 |
+
) -> torch.Tensor:
|
| 294 |
+
"""A helper function to create random tensors on the desired `device` with the desired `dtype`. When
|
| 295 |
+
passing a list of generators, you can seed each batch size individually. If CPU generators are passed, the tensor
|
| 296 |
+
is always created on the CPU.
|
| 297 |
+
"""
|
| 298 |
+
# device on which tensor is created defaults to device
|
| 299 |
+
rand_device = device
|
| 300 |
+
batch_size = shape[0]
|
| 301 |
+
|
| 302 |
+
layout = layout or torch.strided
|
| 303 |
+
device = device or torch.device("cpu")
|
| 304 |
+
|
| 305 |
+
if generator is not None:
|
| 306 |
+
gen_device_type = generator.device.type if not isinstance(generator, list) else generator[0].device.type
|
| 307 |
+
if gen_device_type != device.type and gen_device_type == "cpu":
|
| 308 |
+
rand_device = "cpu"
|
| 309 |
+
if device != "mps":
|
| 310 |
+
warnings.warn(
|
| 311 |
+
f"The passed generator was created on 'cpu' even though a tensor on {device} was expected."
|
| 312 |
+
f" Tensors will be created on 'cpu' and then moved to {device}. Note that one can probably"
|
| 313 |
+
f" slighly speed up this function by passing a generator that was created on the {device} device."
|
| 314 |
+
)
|
| 315 |
+
elif gen_device_type != device.type and gen_device_type == "cuda":
|
| 316 |
+
raise ValueError(f"Cannot generate a {device} tensor from a generator of type {gen_device_type}.")
|
| 317 |
+
|
| 318 |
+
# make sure generator list of length 1 is treated like a non-list
|
| 319 |
+
if isinstance(generator, list) and len(generator) == 1:
|
| 320 |
+
generator = generator[0]
|
| 321 |
+
|
| 322 |
+
if isinstance(generator, list):
|
| 323 |
+
shape = (1,) + shape[1:]
|
| 324 |
+
latents = [torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype, layout=layout) for i in range(batch_size)]
|
| 325 |
+
latents = torch.cat(latents, dim=0).to(device)
|
| 326 |
+
else:
|
| 327 |
+
latents = torch.randn(shape, generator=generator, device=rand_device, dtype=dtype, layout=layout).to(device)
|
| 328 |
+
|
| 329 |
+
return latents
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/extras/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa
|
| 2 |
+
|
| 3 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
from .best_of_n_sampler import BestOfNSampler
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/extras/best_of_n_sampler.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Callable, List, Optional, Union
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import GenerationConfig, PreTrainedTokenizer, PreTrainedTokenizerFast
|
| 5 |
+
|
| 6 |
+
from ..core import set_seed
|
| 7 |
+
from ..models import SUPPORTED_ARCHITECTURES, PreTrainedModelWrapper
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class BestOfNSampler(object):
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
model: PreTrainedModelWrapper,
|
| 14 |
+
tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast],
|
| 15 |
+
queries_to_scores: Callable[[List[str]], List[float]],
|
| 16 |
+
length_sampler: Any,
|
| 17 |
+
sample_size: int = 4,
|
| 18 |
+
seed: Optional[int] = None,
|
| 19 |
+
n_candidates: int = 1,
|
| 20 |
+
generation_config: Optional[GenerationConfig] = None,
|
| 21 |
+
) -> None:
|
| 22 |
+
r"""
|
| 23 |
+
Initialize the sampler for best-of-n generation
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
model (`PreTrainedModelWrapper`):
|
| 27 |
+
The pretrained model to use for generation
|
| 28 |
+
tokenizer (`PreTrainedTokenizer` or `PreTrainedTokenizerFast`):
|
| 29 |
+
Tokenizer associated with the pretrained model
|
| 30 |
+
queries_to_scores (`Callable[[List[str]], List[float]]`):
|
| 31 |
+
Callable that takes a list of generated texts and returns the associated reward scores
|
| 32 |
+
length_sampler (`Any`):
|
| 33 |
+
Sampler used to sample the length of the generated text
|
| 34 |
+
sample_size (`int`):
|
| 35 |
+
Number of samples to generate for each query
|
| 36 |
+
seed (`int`, *optional*):
|
| 37 |
+
Random seed used to control generation
|
| 38 |
+
n_candidates (`int`):
|
| 39 |
+
Number of candidates to return for each query
|
| 40 |
+
generation_config (`GenerationConfig`, *optional*):
|
| 41 |
+
Generation config passed to the underlying model's `generate` method.
|
| 42 |
+
See `GenerationConfig` (https://huggingface.co/docs/transformers/v4.29.1/en/main_classes/text_generation#transformers.GenerationConfig) for more details
|
| 43 |
+
"""
|
| 44 |
+
if seed is not None:
|
| 45 |
+
set_seed(seed)
|
| 46 |
+
|
| 47 |
+
if not isinstance(tokenizer, (PreTrainedTokenizer, PreTrainedTokenizerFast)):
|
| 48 |
+
raise ValueError(f"tokenizer must be a PreTrainedTokenizer or PreTrainedTokenizerFast, got {type(tokenizer)}")
|
| 49 |
+
if not isinstance(model, (SUPPORTED_ARCHITECTURES)):
|
| 50 |
+
raise ValueError(f"model must be a PreTrainedModelWrapper, got {type(model)} - supported architectures are: {SUPPORTED_ARCHITECTURES}")
|
| 51 |
+
|
| 52 |
+
self.model = model
|
| 53 |
+
self.tokenizer = tokenizer
|
| 54 |
+
|
| 55 |
+
self.queries_to_scores = queries_to_scores
|
| 56 |
+
self.length_sampler = length_sampler
|
| 57 |
+
self.gen_config = generation_config
|
| 58 |
+
self.sample_size = sample_size
|
| 59 |
+
self.n_candidates = n_candidates
|
| 60 |
+
|
| 61 |
+
def generate(
|
| 62 |
+
self,
|
| 63 |
+
tokenized_query: Union[List[int], torch.Tensor, List[torch.Tensor], List[List[int]]],
|
| 64 |
+
skip_special_tokens: bool = True,
|
| 65 |
+
device: Optional[Union[str, torch.device]] = None,
|
| 66 |
+
**generation_kwargs,
|
| 67 |
+
) -> List[List[str]]:
|
| 68 |
+
r"""
|
| 69 |
+
Generate the best of n samples for input queries
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
tokenized_query (`List[int]` or `torch.Tensor` or `List[torch.Tensor]` or `List[int]`):
|
| 73 |
+
represents either a single tokenized query (a single tensor or a list of integers) or a batch of tokenized queries (a list of tensors or a list of lists of integers)
|
| 74 |
+
skip_special_tokens (`bool`):
|
| 75 |
+
Whether to remove the special tokens from the output
|
| 76 |
+
device (`str` or `torch.device`, *optional*):
|
| 77 |
+
The device on which the model will be loaded
|
| 78 |
+
**generation_kwargs (`dict`, *optional*):
|
| 79 |
+
Additional keyword arguments passed along to the underlying model's `generate` method.
|
| 80 |
+
This is used to override generation config
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
List[List[str]]: A list of lists of generated texts
|
| 84 |
+
"""
|
| 85 |
+
queries = None
|
| 86 |
+
|
| 87 |
+
if isinstance(tokenized_query, torch.Tensor) and tokenized_query.ndim == 1:
|
| 88 |
+
queries = tokenized_query.unsqueeze(0)
|
| 89 |
+
elif isinstance(tokenized_query, List):
|
| 90 |
+
element_type = type(tokenized_query[0])
|
| 91 |
+
if element_type == int:
|
| 92 |
+
queries = torch.tensor(tokenized_query).unsqueeze(0)
|
| 93 |
+
elif element_type == torch.Tensor:
|
| 94 |
+
queries = [tensor.reshape((1, -1)) for tensor in tokenized_query]
|
| 95 |
+
else:
|
| 96 |
+
queries = [torch.tensor(query).reshape((1, -1)) for query in tokenized_query]
|
| 97 |
+
|
| 98 |
+
result = []
|
| 99 |
+
|
| 100 |
+
for query in queries:
|
| 101 |
+
queries = query.repeat((self.sample_size, 1))
|
| 102 |
+
output = self.model.generate(
|
| 103 |
+
queries.to(device),
|
| 104 |
+
max_new_tokens=self.length_sampler(),
|
| 105 |
+
generation_config=self.gen_config,
|
| 106 |
+
**generation_kwargs,
|
| 107 |
+
).squeeze()
|
| 108 |
+
output = self.tokenizer.batch_decode(output, skip_special_tokens=skip_special_tokens)
|
| 109 |
+
scores = torch.tensor(self.queries_to_scores(output))
|
| 110 |
+
output = [output[i] for i in scores.topk(self.n_candidates).indices]
|
| 111 |
+
result.append(output)
|
| 112 |
+
|
| 113 |
+
return result
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/extras/dataset_formatting.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from typing import Callable, Literal, Optional, Union
|
| 3 |
+
|
| 4 |
+
from datasets import Dataset, Value
|
| 5 |
+
from transformers import AutoTokenizer
|
| 6 |
+
|
| 7 |
+
from ..trainer.utils import ConstantLengthDataset
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
FORMAT_MAPPING = {
|
| 11 |
+
"chatml": [{"content": Value(dtype="string", id=None), "role": Value(dtype="string", id=None)}],
|
| 12 |
+
"instruction": {"completion": Value(dtype="string", id=None), "prompt": Value(dtype="string", id=None)},
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def conversations_formatting_function(tokenizer: AutoTokenizer, messages_field: Literal["messages", "conversations"]):
|
| 17 |
+
r"""
|
| 18 |
+
return a callable function that takes in a "messages" dataset and returns a formatted dataset, based on the tokenizer
|
| 19 |
+
apply chat template to the dataset
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def format_dataset(examples):
|
| 23 |
+
if isinstance(examples[messages_field][0], list):
|
| 24 |
+
output_texts = []
|
| 25 |
+
for i in range(len(examples[messages_field])):
|
| 26 |
+
output_texts.append(tokenizer.apply_chat_template(examples[messages_field][i], tokenize=False))
|
| 27 |
+
return output_texts
|
| 28 |
+
else:
|
| 29 |
+
return tokenizer.apply_chat_template(examples[messages_field], tokenize=False)
|
| 30 |
+
|
| 31 |
+
return format_dataset
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def instructions_formatting_function(tokenizer: AutoTokenizer):
|
| 35 |
+
r"""
|
| 36 |
+
return a callable function that takes in an "instructions" dataset and returns a formatted dataset, based on the tokenizer
|
| 37 |
+
apply chat template to the dataset
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def format_dataset(examples):
|
| 41 |
+
if isinstance(examples["prompt"], list):
|
| 42 |
+
output_texts = []
|
| 43 |
+
for i in range(len(examples["prompt"])):
|
| 44 |
+
converted_sample = [
|
| 45 |
+
{"role": "user", "content": examples["prompt"][i]},
|
| 46 |
+
{"role": "assistant", "content": examples["completion"][i]},
|
| 47 |
+
]
|
| 48 |
+
output_texts.append(tokenizer.apply_chat_template(converted_sample, tokenize=False))
|
| 49 |
+
return output_texts
|
| 50 |
+
else:
|
| 51 |
+
converted_sample = [
|
| 52 |
+
{"role": "user", "content": examples["prompt"]},
|
| 53 |
+
{"role": "assistant", "content": examples["completion"]},
|
| 54 |
+
]
|
| 55 |
+
return tokenizer.apply_chat_template(converted_sample, tokenize=False)
|
| 56 |
+
|
| 57 |
+
return format_dataset
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def get_formatting_func_from_dataset(dataset: Union[Dataset, ConstantLengthDataset], tokenizer: AutoTokenizer) -> Optional[Callable]:
|
| 61 |
+
r"""
|
| 62 |
+
Finds the correct formatting function based on the dataset structure. Currently supported datasets are:
|
| 63 |
+
- `ChatML` with [{"role": str, "content": str}]
|
| 64 |
+
- `instruction` with [{"prompt": str, "completion": str}]
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
dataset (Dataset): User dataset
|
| 68 |
+
tokenizer (AutoTokenizer): Tokenizer used for formatting
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
Callable: Formatting function if the dataset format is supported else None
|
| 72 |
+
"""
|
| 73 |
+
if isinstance(dataset, Dataset):
|
| 74 |
+
if "messages" in dataset.features:
|
| 75 |
+
if dataset.features["messages"] == FORMAT_MAPPING["chatml"]:
|
| 76 |
+
logging.info("Formatting dataset with chatml format")
|
| 77 |
+
return conversations_formatting_function(tokenizer, "messages")
|
| 78 |
+
if "conversations" in dataset.features:
|
| 79 |
+
if dataset.features["conversations"] == FORMAT_MAPPING["chatml"]:
|
| 80 |
+
logging.info("Formatting dataset with chatml format")
|
| 81 |
+
return conversations_formatting_function(tokenizer, "conversations")
|
| 82 |
+
elif dataset.features == FORMAT_MAPPING["instruction"]:
|
| 83 |
+
logging.info("Formatting dataset with instruction format")
|
| 84 |
+
return instructions_formatting_function(tokenizer)
|
| 85 |
+
|
| 86 |
+
return None
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/import_utils.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import importlib
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if sys.version_info < (3, 8):
|
| 19 |
+
_is_python_greater_3_8 = False
|
| 20 |
+
else:
|
| 21 |
+
_is_python_greater_3_8 = True
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def is_peft_available() -> bool:
|
| 25 |
+
return importlib.util.find_spec("peft") is not None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def is_unsloth_available() -> bool:
|
| 29 |
+
return importlib.util.find_spec("unsloth") is not None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def is_accelerate_greater_20_0() -> bool:
|
| 33 |
+
if _is_python_greater_3_8:
|
| 34 |
+
from importlib.metadata import version
|
| 35 |
+
|
| 36 |
+
accelerate_version = version("accelerate")
|
| 37 |
+
else:
|
| 38 |
+
import pkg_resources
|
| 39 |
+
|
| 40 |
+
accelerate_version = pkg_resources.get_distribution("accelerate").version
|
| 41 |
+
return accelerate_version >= "0.20.0"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def is_transformers_greater_than(version: str) -> bool:
|
| 45 |
+
_transformers_version = importlib.metadata.version("transformers")
|
| 46 |
+
return _transformers_version > version
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def is_torch_greater_2_0() -> bool:
|
| 50 |
+
if _is_python_greater_3_8:
|
| 51 |
+
from importlib.metadata import version
|
| 52 |
+
|
| 53 |
+
torch_version = version("torch")
|
| 54 |
+
else:
|
| 55 |
+
import pkg_resources
|
| 56 |
+
|
| 57 |
+
torch_version = pkg_resources.get_distribution("torch").version
|
| 58 |
+
return torch_version >= "2.0"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def is_diffusers_available() -> bool:
|
| 62 |
+
return importlib.util.find_spec("diffusers") is not None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def is_bitsandbytes_available() -> bool:
|
| 66 |
+
import torch
|
| 67 |
+
|
| 68 |
+
# bnb can be imported without GPU but is not usable.
|
| 69 |
+
return importlib.util.find_spec("bitsandbytes") is not None and torch.cuda.is_available()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def is_torchvision_available() -> bool:
|
| 73 |
+
return importlib.util.find_spec("torchvision") is not None
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def is_rich_available() -> bool:
|
| 77 |
+
return importlib.util.find_spec("rich") is not None
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def is_wandb_available() -> bool:
|
| 81 |
+
return importlib.util.find_spec("wandb") is not None
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def is_xpu_available() -> bool:
|
| 85 |
+
if is_accelerate_greater_20_0():
|
| 86 |
+
import accelerate
|
| 87 |
+
|
| 88 |
+
return accelerate.utils.is_xpu_available()
|
| 89 |
+
else:
|
| 90 |
+
if importlib.util.find_spec("intel_extension_for_pytorch") is None:
|
| 91 |
+
return False
|
| 92 |
+
try:
|
| 93 |
+
import torch
|
| 94 |
+
|
| 95 |
+
return hasattr(torch, "xpu") and torch.xpu.is_available()
|
| 96 |
+
except RuntimeError:
|
| 97 |
+
return False
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def is_npu_available() -> bool:
|
| 101 |
+
"""Checks if `torch_npu` is installed and potentially if a NPU is in the environment"""
|
| 102 |
+
if importlib.util.find_spec("torch") is None or importlib.util.find_spec("torch_npu") is None:
|
| 103 |
+
return False
|
| 104 |
+
|
| 105 |
+
import torch
|
| 106 |
+
import torch_npu # noqa: F401
|
| 107 |
+
|
| 108 |
+
return hasattr(torch, "npu") and torch.npu.is_available()
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/models/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa
|
| 2 |
+
|
| 3 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
from .modeling_base import PreTrainedModelWrapper, create_reference_model
|
| 17 |
+
from .modeling_value_head import AutoModelForCausalLMWithValueHead, AutoModelForSeq2SeqLMWithValueHead
|
| 18 |
+
from .utils import setup_chat_format
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
SUPPORTED_ARCHITECTURES = (
|
| 22 |
+
AutoModelForCausalLMWithValueHead,
|
| 23 |
+
AutoModelForSeq2SeqLMWithValueHead,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
from ..import_utils import is_diffusers_available
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_diffusers_available():
|
| 30 |
+
from .modeling_sd_base import (
|
| 31 |
+
DDPOPipelineOutput,
|
| 32 |
+
DDPOSchedulerOutput,
|
| 33 |
+
DDPOStableDiffusionPipeline,
|
| 34 |
+
DefaultDDPOStableDiffusionPipeline,
|
| 35 |
+
)
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/models/modeling_base.py
ADDED
|
@@ -0,0 +1,640 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import json
|
| 15 |
+
import logging
|
| 16 |
+
import os
|
| 17 |
+
from copy import deepcopy
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
from accelerate import PartialState
|
| 22 |
+
from huggingface_hub import hf_hub_download
|
| 23 |
+
from huggingface_hub.utils import (
|
| 24 |
+
EntryNotFoundError,
|
| 25 |
+
HFValidationError,
|
| 26 |
+
LocalEntryNotFoundError,
|
| 27 |
+
RepositoryNotFoundError,
|
| 28 |
+
)
|
| 29 |
+
from safetensors.torch import load_file as safe_load_file
|
| 30 |
+
from transformers import PreTrainedModel
|
| 31 |
+
|
| 32 |
+
from ..import_utils import is_npu_available, is_peft_available, is_transformers_greater_than, is_xpu_available
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if is_peft_available():
|
| 36 |
+
from peft import (
|
| 37 |
+
PeftConfig,
|
| 38 |
+
PeftModel,
|
| 39 |
+
PeftModelForCausalLM,
|
| 40 |
+
PeftModelForSeq2SeqLM,
|
| 41 |
+
PromptLearningConfig,
|
| 42 |
+
get_peft_model,
|
| 43 |
+
prepare_model_for_kbit_training,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
if is_transformers_greater_than("4.33.0"):
|
| 47 |
+
from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled
|
| 48 |
+
else:
|
| 49 |
+
from transformers.deepspeed import is_deepspeed_zero3_enabled
|
| 50 |
+
|
| 51 |
+
LAYER_PATTERNS = [
|
| 52 |
+
"transformer.h.{layer}",
|
| 53 |
+
"model.decoder.layers.{layer}",
|
| 54 |
+
"gpt_neox.layers.{layer}",
|
| 55 |
+
"model.layers.{layer}",
|
| 56 |
+
]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class PreTrainedModelWrapper(nn.Module):
|
| 60 |
+
r"""
|
| 61 |
+
A wrapper class around a (`transformers.PreTrainedModel`) to be compatible with the
|
| 62 |
+
(`~transformers.PreTrained`) class in order to keep some attributes and methods of the
|
| 63 |
+
(`~transformers.PreTrainedModel`) class.
|
| 64 |
+
|
| 65 |
+
Attributes:
|
| 66 |
+
pretrained_model: (`transformers.PreTrainedModel`)
|
| 67 |
+
The model to be wrapped.
|
| 68 |
+
parent_class: (`transformers.PreTrainedModel`)
|
| 69 |
+
The parent class of the model to be wrapped.
|
| 70 |
+
supported_args: (`list`)
|
| 71 |
+
The list of arguments that are supported by the wrapper class.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
transformers_parent_class = None
|
| 75 |
+
supported_args = None
|
| 76 |
+
supported_modules = ("v_head",)
|
| 77 |
+
supported_rm_modules = ("score",)
|
| 78 |
+
supported_pretrained_model_architectures = (PreTrainedModel) if not is_peft_available() else (PreTrainedModel, PeftModelForCausalLM, PeftModelForSeq2SeqLM)
|
| 79 |
+
|
| 80 |
+
def __init__(self, pretrained_model=None, score_module=None, supports_rm_adapter=False, rm_adapter_name=None, **kwargs):
|
| 81 |
+
super().__init__()
|
| 82 |
+
self.pretrained_model = pretrained_model
|
| 83 |
+
|
| 84 |
+
self.config = pretrained_model.config
|
| 85 |
+
self.prepare_inputs_for_generation = pretrained_model.prepare_inputs_for_generation
|
| 86 |
+
self.is_loaded_in_8bit = getattr(pretrained_model, "is_loaded_in_8bit", False)
|
| 87 |
+
self.is_loaded_in_4bit = getattr(pretrained_model, "is_loaded_in_4bit", False)
|
| 88 |
+
self.is_sequential_parallel = False
|
| 89 |
+
|
| 90 |
+
if hasattr(pretrained_model, "gradient_checkpointing_disable"):
|
| 91 |
+
self.gradient_checkpointing_disable = pretrained_model.gradient_checkpointing_disable
|
| 92 |
+
|
| 93 |
+
if hasattr(pretrained_model, "gradient_checkpointing_enable"):
|
| 94 |
+
self.gradient_checkpointing_enable = pretrained_model.gradient_checkpointing_enable
|
| 95 |
+
|
| 96 |
+
self.supports_rm_adapter = supports_rm_adapter
|
| 97 |
+
self.rm_adapter_name = rm_adapter_name
|
| 98 |
+
self.policy_adapter_name = "default"
|
| 99 |
+
if score_module is not None:
|
| 100 |
+
self.score = score_module
|
| 101 |
+
|
| 102 |
+
@classmethod
|
| 103 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 104 |
+
r"""
|
| 105 |
+
Instantiates a new model from a pretrained model from `transformers`. The
|
| 106 |
+
pretrained model is loaded using the `from_pretrained` method of the
|
| 107 |
+
`transformers.PreTrainedModel` class. The arguments that are specific to the
|
| 108 |
+
`transformers.PreTrainedModel` class are passed along this method and filtered
|
| 109 |
+
out from the `kwargs` argument.
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
pretrained_model_name_or_path (`str` or `transformers.PreTrainedModel`):
|
| 114 |
+
The path to the pretrained model or its name.
|
| 115 |
+
*model_args (`list`, *optional*)):
|
| 116 |
+
Additional positional arguments passed along to the underlying model's
|
| 117 |
+
`from_pretrained` method.
|
| 118 |
+
**kwargs (`dict`, *optional*):
|
| 119 |
+
Additional keyword arguments passed along to the underlying model's
|
| 120 |
+
`from_pretrained` method. We also pre-process the kwargs to extract
|
| 121 |
+
the arguments that are specific to the `transformers.PreTrainedModel`
|
| 122 |
+
class and the arguments that are specific to trl models. The kwargs
|
| 123 |
+
also support `prepare_model_for_kbit_training` arguments from
|
| 124 |
+
`peft` library.
|
| 125 |
+
"""
|
| 126 |
+
if kwargs is not None:
|
| 127 |
+
peft_config = kwargs.pop("peft_config", None)
|
| 128 |
+
reward_adapter = kwargs.pop("reward_adapter", None)
|
| 129 |
+
reward_adapter_name = kwargs.pop("reward_adapter_name", "reward_adapter")
|
| 130 |
+
is_trainable = kwargs.pop("is_trainable", False)
|
| 131 |
+
trl_model_args, pretrained_kwargs, peft_quantization_kwargs = cls._split_kwargs(kwargs)
|
| 132 |
+
token = pretrained_kwargs.get("token", None)
|
| 133 |
+
else:
|
| 134 |
+
peft_config = None
|
| 135 |
+
is_trainable = False
|
| 136 |
+
trl_model_args = {}
|
| 137 |
+
pretrained_kwargs = {}
|
| 138 |
+
peft_quantization_kwargs = {}
|
| 139 |
+
token = None
|
| 140 |
+
|
| 141 |
+
if reward_adapter is not None and not isinstance(reward_adapter, str):
|
| 142 |
+
raise ValueError("The `reward_adapter` argument should be a string representing the name of local path or the Hub id to the Reward Modeling adapter.")
|
| 143 |
+
|
| 144 |
+
is_peft_model = False
|
| 145 |
+
|
| 146 |
+
current_device = cls._get_current_device()
|
| 147 |
+
if isinstance(pretrained_model_name_or_path, str):
|
| 148 |
+
is_loaded_in_8bit = pretrained_kwargs["load_in_8bit"] if "load_in_8bit" in pretrained_kwargs else False
|
| 149 |
+
is_loaded_in_4bit = pretrained_kwargs["load_in_4bit"] if "load_in_4bit" in pretrained_kwargs else False
|
| 150 |
+
else:
|
| 151 |
+
is_loaded_in_8bit = getattr(pretrained_model_name_or_path, "is_loaded_in_8bit", False)
|
| 152 |
+
is_loaded_in_4bit = getattr(pretrained_model_name_or_path, "is_loaded_in_4bit", False)
|
| 153 |
+
|
| 154 |
+
if (is_loaded_in_8bit or is_loaded_in_4bit) and "device_map" not in pretrained_kwargs:
|
| 155 |
+
# warn users
|
| 156 |
+
logging.warning(
|
| 157 |
+
"The `device_map` argument is not provided. We will override the device_map argument."
|
| 158 |
+
" to set the entire"
|
| 159 |
+
" model on the current device. If you want to set the model on multiple devices, please provide"
|
| 160 |
+
" a custom `device_map` argument."
|
| 161 |
+
)
|
| 162 |
+
pretrained_kwargs["device_map"] = {"": current_device}
|
| 163 |
+
|
| 164 |
+
if is_peft_available() and peft_config is not None and not isinstance(peft_config, PeftConfig):
|
| 165 |
+
raise ValueError("The `peft_config` argument should be an instance of `peft.PeftConfig` class.")
|
| 166 |
+
|
| 167 |
+
# First, load the pre-trained model using the parent-class
|
| 168 |
+
# either `AutoModelForCausalLM` or `AutoModelForSeq2SeqLM`
|
| 169 |
+
if isinstance(pretrained_model_name_or_path, str):
|
| 170 |
+
if is_peft_available():
|
| 171 |
+
try:
|
| 172 |
+
# If there is a trained peft adapter in the hub, load its config.
|
| 173 |
+
remote_adapter_config = hf_hub_download(
|
| 174 |
+
pretrained_model_name_or_path,
|
| 175 |
+
"adapter_config.json",
|
| 176 |
+
token=token,
|
| 177 |
+
)
|
| 178 |
+
except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError):
|
| 179 |
+
remote_adapter_config = None
|
| 180 |
+
else:
|
| 181 |
+
remote_adapter_config = None
|
| 182 |
+
|
| 183 |
+
local_adapter_present = os.path.exists(os.path.join(pretrained_model_name_or_path, "adapter_config.json"))
|
| 184 |
+
|
| 185 |
+
if (local_adapter_present or remote_adapter_config is not None) and is_peft_available():
|
| 186 |
+
if peft_config is not None:
|
| 187 |
+
logging.warning("`peft_config` argument ignored since a peft config file was found in " f"{pretrained_model_name_or_path}")
|
| 188 |
+
|
| 189 |
+
# Load the trained peft adapter config
|
| 190 |
+
if local_adapter_present:
|
| 191 |
+
trained_adapter_config = PeftConfig.from_pretrained(pretrained_model_name_or_path)
|
| 192 |
+
else:
|
| 193 |
+
remote_adapter_dir = os.path.dirname(remote_adapter_config)
|
| 194 |
+
trained_adapter_config = PeftConfig.from_pretrained(remote_adapter_dir)
|
| 195 |
+
|
| 196 |
+
# Load the pretrained base model
|
| 197 |
+
pretrained_model = cls.transformers_parent_class.from_pretrained(trained_adapter_config.base_model_name_or_path, *model_args, **pretrained_kwargs)
|
| 198 |
+
|
| 199 |
+
# Wrap the pretrained model with the trained peft adapter
|
| 200 |
+
pretrained_model = PeftModel.from_pretrained(pretrained_model, pretrained_model_name_or_path, is_trainable=is_trainable)
|
| 201 |
+
logging.info("Trained peft adapter loaded")
|
| 202 |
+
else:
|
| 203 |
+
pretrained_model = cls.transformers_parent_class.from_pretrained(pretrained_model_name_or_path, *model_args, **pretrained_kwargs)
|
| 204 |
+
|
| 205 |
+
if peft_config is not None:
|
| 206 |
+
# Initialize a new peft adapter with the given config
|
| 207 |
+
if is_loaded_in_8bit or is_loaded_in_4bit:
|
| 208 |
+
pretrained_model = prepare_model_for_kbit_training(
|
| 209 |
+
pretrained_model,
|
| 210 |
+
**peft_quantization_kwargs,
|
| 211 |
+
)
|
| 212 |
+
pretrained_model = get_peft_model(pretrained_model, peft_config)
|
| 213 |
+
logging.info("peft adapter initialised")
|
| 214 |
+
|
| 215 |
+
elif isinstance(pretrained_model_name_or_path, cls.supported_pretrained_model_architectures):
|
| 216 |
+
pretrained_model = pretrained_model_name_or_path
|
| 217 |
+
|
| 218 |
+
if peft_config is not None and isinstance(pretrained_model, PreTrainedModel):
|
| 219 |
+
# Initialize a new peft adapter with the given config
|
| 220 |
+
if is_loaded_in_8bit or is_loaded_in_4bit:
|
| 221 |
+
pretrained_model = prepare_model_for_kbit_training(
|
| 222 |
+
pretrained_model,
|
| 223 |
+
**peft_quantization_kwargs,
|
| 224 |
+
)
|
| 225 |
+
pretrained_model = get_peft_model(pretrained_model, peft_config)
|
| 226 |
+
logging.info("peft adapter initialised")
|
| 227 |
+
else:
|
| 228 |
+
raise ValueError("pretrained_model_name_or_path should be a string or a PreTrainedModel, " f"but is {type(pretrained_model_name_or_path)}")
|
| 229 |
+
|
| 230 |
+
if is_peft_available():
|
| 231 |
+
if isinstance(pretrained_model, PeftModel):
|
| 232 |
+
is_peft_model = True
|
| 233 |
+
# for backward compatibility
|
| 234 |
+
if hasattr(pretrained_model, "active_peft_config") and isinstance(pretrained_model.active_peft_config, PromptLearningConfig):
|
| 235 |
+
raise ValueError("PromptLearningConfig is not supported for PPO training.")
|
| 236 |
+
|
| 237 |
+
# Add reward modeling adapter if specified
|
| 238 |
+
if not is_peft_model and reward_adapter is not None:
|
| 239 |
+
raise ValueError("reward_adapter can only be used with a PeftModel. ")
|
| 240 |
+
elif is_peft_model and reward_adapter is not None:
|
| 241 |
+
score_module = cls.add_and_load_reward_modeling_adapter(pretrained_model, reward_adapter, reward_adapter_name, token=token)
|
| 242 |
+
multi_adapter_args = {
|
| 243 |
+
"score_module": score_module,
|
| 244 |
+
"supports_rm_adapter": True,
|
| 245 |
+
"rm_adapter_name": reward_adapter_name,
|
| 246 |
+
}
|
| 247 |
+
else:
|
| 248 |
+
multi_adapter_args = {"supports_rm_adapter": False}
|
| 249 |
+
|
| 250 |
+
# Then, create the full model by instantiating the wrapper class
|
| 251 |
+
model = cls(pretrained_model, **multi_adapter_args, **trl_model_args)
|
| 252 |
+
|
| 253 |
+
# if resume_training, load the state_dict again - this is ok since the
|
| 254 |
+
# state_dict is removed from the model after loading it.
|
| 255 |
+
is_resuming_training = True
|
| 256 |
+
if isinstance(pretrained_model_name_or_path, str):
|
| 257 |
+
safe_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors")
|
| 258 |
+
filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin")
|
| 259 |
+
|
| 260 |
+
sharded_index_filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin.index.json")
|
| 261 |
+
safe_sharded_index_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors.index.json")
|
| 262 |
+
is_sharded = False
|
| 263 |
+
use_safe = os.path.exists(safe_filename)
|
| 264 |
+
|
| 265 |
+
if not (os.path.exists(filename) or os.path.exists(safe_filename)):
|
| 266 |
+
# Try with `pytorch_model.bin`
|
| 267 |
+
filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub(
|
| 268 |
+
pretrained_model,
|
| 269 |
+
pretrained_model_name_or_path,
|
| 270 |
+
sharded_index_filename,
|
| 271 |
+
token=token,
|
| 272 |
+
)
|
| 273 |
+
# Try with safetensors
|
| 274 |
+
if filename is None and files_to_download is None:
|
| 275 |
+
safe_filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub(
|
| 276 |
+
pretrained_model,
|
| 277 |
+
pretrained_model_name_or_path,
|
| 278 |
+
safe_sharded_index_filename,
|
| 279 |
+
token=token,
|
| 280 |
+
model_name="model.safetensors",
|
| 281 |
+
model_index_name="model.safetensors.index.json",
|
| 282 |
+
)
|
| 283 |
+
use_safe = True
|
| 284 |
+
else:
|
| 285 |
+
use_safe = False
|
| 286 |
+
|
| 287 |
+
loading_func = safe_load_file if use_safe else torch.load
|
| 288 |
+
load_kwargs = {} if use_safe else {"map_location": "cpu"}
|
| 289 |
+
|
| 290 |
+
if is_resuming_training:
|
| 291 |
+
if is_sharded:
|
| 292 |
+
# download each file and add it to the state_dict
|
| 293 |
+
state_dict = {}
|
| 294 |
+
|
| 295 |
+
for shard_file in files_to_download:
|
| 296 |
+
filename = hf_hub_download(
|
| 297 |
+
pretrained_model_name_or_path,
|
| 298 |
+
shard_file,
|
| 299 |
+
token=token,
|
| 300 |
+
)
|
| 301 |
+
state_dict.update(loading_func(filename, **load_kwargs))
|
| 302 |
+
else:
|
| 303 |
+
state_dict = loading_func(filename if not use_safe else safe_filename, **load_kwargs)
|
| 304 |
+
|
| 305 |
+
else:
|
| 306 |
+
state_dict = pretrained_model_name_or_path.state_dict()
|
| 307 |
+
|
| 308 |
+
model.is_peft_model = is_peft_model
|
| 309 |
+
model.current_device = current_device
|
| 310 |
+
|
| 311 |
+
if is_resuming_training:
|
| 312 |
+
model.post_init(state_dict=state_dict)
|
| 313 |
+
|
| 314 |
+
return model
|
| 315 |
+
|
| 316 |
+
@classmethod
|
| 317 |
+
def _get_checkpoint_from_hub(
|
| 318 |
+
cls,
|
| 319 |
+
pretrained_model,
|
| 320 |
+
pretrained_model_name_or_path,
|
| 321 |
+
index_filename,
|
| 322 |
+
token=None,
|
| 323 |
+
model_name="pytorch_model.bin",
|
| 324 |
+
model_index_name="pytorch_model.bin.index.json",
|
| 325 |
+
):
|
| 326 |
+
files_to_download = None
|
| 327 |
+
filename = None
|
| 328 |
+
is_resuming_training = True
|
| 329 |
+
is_sharded = False
|
| 330 |
+
|
| 331 |
+
try:
|
| 332 |
+
filename = hf_hub_download(
|
| 333 |
+
pretrained_model_name_or_path,
|
| 334 |
+
model_name,
|
| 335 |
+
token=token,
|
| 336 |
+
)
|
| 337 |
+
# sharded
|
| 338 |
+
except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError):
|
| 339 |
+
if os.path.exists(index_filename):
|
| 340 |
+
index_file_name = index_filename
|
| 341 |
+
else:
|
| 342 |
+
try:
|
| 343 |
+
index_file_name = hf_hub_download(
|
| 344 |
+
pretrained_model_name_or_path,
|
| 345 |
+
model_index_name,
|
| 346 |
+
token=token,
|
| 347 |
+
)
|
| 348 |
+
except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError):
|
| 349 |
+
# not continue training, do not have v_head weight
|
| 350 |
+
is_resuming_training = False
|
| 351 |
+
logging.warning(f"A {type(pretrained_model)} model is loaded from '{pretrained_model_name_or_path}', " f"and no v_head weight is found. This IS expected if you are not resuming PPO training.")
|
| 352 |
+
# load json
|
| 353 |
+
if is_resuming_training:
|
| 354 |
+
with open(index_file_name, "r") as f:
|
| 355 |
+
index = json.load(f)
|
| 356 |
+
# check filename with `v_head` or any known extra module:
|
| 357 |
+
files_to_download = set()
|
| 358 |
+
for k, v in index["weight_map"].items():
|
| 359 |
+
if any([module in k for module in cls.supported_modules]):
|
| 360 |
+
files_to_download.add(v)
|
| 361 |
+
is_sharded = True
|
| 362 |
+
|
| 363 |
+
return filename, files_to_download, is_sharded, is_resuming_training
|
| 364 |
+
|
| 365 |
+
@classmethod
|
| 366 |
+
def _get_current_device(cls):
|
| 367 |
+
r"""
|
| 368 |
+
Get the current device. For GPU, we return the local process index using the `accelerate.PartialState`
|
| 369 |
+
object to handle corner cases when running scripts in distributed environments.
|
| 370 |
+
|
| 371 |
+
Returns:
|
| 372 |
+
current_device (`Union[int, str]`):
|
| 373 |
+
The current device.
|
| 374 |
+
"""
|
| 375 |
+
state = PartialState()
|
| 376 |
+
if is_xpu_available():
|
| 377 |
+
return f"xpu:{state.local_process_index}"
|
| 378 |
+
elif is_npu_available():
|
| 379 |
+
return f"npu:{state.local_process_index}"
|
| 380 |
+
else:
|
| 381 |
+
return state.local_process_index if torch.cuda.is_available() else "cpu"
|
| 382 |
+
|
| 383 |
+
@classmethod
|
| 384 |
+
def _split_kwargs(cls, kwargs):
|
| 385 |
+
"""
|
| 386 |
+
Separate the kwargs from the arguments that we support inside
|
| 387 |
+
`supported_args` and the ones that we don't.
|
| 388 |
+
"""
|
| 389 |
+
check_peft_kwargs = False
|
| 390 |
+
|
| 391 |
+
if is_peft_available():
|
| 392 |
+
from peft import prepare_model_for_kbit_training
|
| 393 |
+
|
| 394 |
+
check_peft_kwargs = True
|
| 395 |
+
|
| 396 |
+
supported_kwargs = {}
|
| 397 |
+
unsupported_kwargs = {}
|
| 398 |
+
peft_kwargs = {}
|
| 399 |
+
|
| 400 |
+
for key, value in kwargs.items():
|
| 401 |
+
if key in cls.supported_args:
|
| 402 |
+
supported_kwargs[key] = value
|
| 403 |
+
else:
|
| 404 |
+
unsupported_kwargs[key] = value
|
| 405 |
+
|
| 406 |
+
if check_peft_kwargs:
|
| 407 |
+
if key in prepare_model_for_kbit_training.__code__.co_varnames:
|
| 408 |
+
peft_kwargs[key] = value
|
| 409 |
+
if key in unsupported_kwargs:
|
| 410 |
+
unsupported_kwargs.pop(key)
|
| 411 |
+
|
| 412 |
+
return supported_kwargs, unsupported_kwargs, peft_kwargs
|
| 413 |
+
|
| 414 |
+
@classmethod
|
| 415 |
+
def add_and_load_reward_modeling_adapter(cls, pretrained_model, adapter_model_id, adapter_name="reward_model_adapter", token=None):
|
| 416 |
+
r"""
|
| 417 |
+
Add and load a reward modeling adapter. This method can only be used if the
|
| 418 |
+
model is a `PeftModel` and if you have initialized the model with the `reward_modeling_adapter_id`
|
| 419 |
+
argument, pointing to the id of the reward modeling adapter. The latest needs also to contain the
|
| 420 |
+
score head in order to produce the reward.
|
| 421 |
+
"""
|
| 422 |
+
pretrained_model.load_adapter(adapter_model_id, adapter_name, is_trainable=False)
|
| 423 |
+
pretrained_model.train()
|
| 424 |
+
|
| 425 |
+
filename = os.path.join(adapter_model_id, "adapter_model.bin")
|
| 426 |
+
safe_loading = False
|
| 427 |
+
if not os.path.exists(filename):
|
| 428 |
+
try:
|
| 429 |
+
local_filename = hf_hub_download(
|
| 430 |
+
adapter_model_id,
|
| 431 |
+
"adapter_model.bin",
|
| 432 |
+
token=token,
|
| 433 |
+
)
|
| 434 |
+
except: # noqa
|
| 435 |
+
filename = os.path.join(adapter_model_id, "adapter_model.safetensors")
|
| 436 |
+
safe_loading = True
|
| 437 |
+
if not os.path.exists(filename):
|
| 438 |
+
try:
|
| 439 |
+
local_filename = hf_hub_download(
|
| 440 |
+
adapter_model_id,
|
| 441 |
+
"adapter_model.safetensors",
|
| 442 |
+
token=token,
|
| 443 |
+
)
|
| 444 |
+
except: # noqa
|
| 445 |
+
raise ValueError("Could not find adapter model in the Hub, make sure you have the correct adapter model id.")
|
| 446 |
+
else:
|
| 447 |
+
local_filename = filename
|
| 448 |
+
else:
|
| 449 |
+
local_filename = filename
|
| 450 |
+
|
| 451 |
+
loading_func = safe_load_file if safe_loading else torch.load
|
| 452 |
+
load_kwargs = {} if safe_loading else {"map_location": "cpu"}
|
| 453 |
+
|
| 454 |
+
adapter_state_dict = loading_func(local_filename, **load_kwargs)
|
| 455 |
+
|
| 456 |
+
for score_name_candidate in cls.supported_rm_modules:
|
| 457 |
+
if any([score_name_candidate in name for name in adapter_state_dict.keys()]):
|
| 458 |
+
score_name = score_name_candidate
|
| 459 |
+
# we have found the correct head name and can break
|
| 460 |
+
break
|
| 461 |
+
|
| 462 |
+
score_dict = {}
|
| 463 |
+
|
| 464 |
+
for name, param in adapter_state_dict.items():
|
| 465 |
+
if score_name in name:
|
| 466 |
+
key_name = ".".join(name.split(".")[-1:])
|
| 467 |
+
score_dict[key_name] = param.to(cls._get_current_device())
|
| 468 |
+
|
| 469 |
+
num_labels, hidden_dim = score_dict["weight"].shape
|
| 470 |
+
has_bias = any(["bias" in name for name in adapter_state_dict.keys()])
|
| 471 |
+
|
| 472 |
+
score = nn.Linear(hidden_dim, num_labels, bias=has_bias).to(
|
| 473 |
+
device=cls._get_current_device(),
|
| 474 |
+
dtype=pretrained_model.dtype,
|
| 475 |
+
)
|
| 476 |
+
score.load_state_dict(score_dict)
|
| 477 |
+
for param in score.parameters():
|
| 478 |
+
param.requires_grad = False
|
| 479 |
+
|
| 480 |
+
return score
|
| 481 |
+
|
| 482 |
+
def push_to_hub(self, *args, **kwargs):
|
| 483 |
+
r"""
|
| 484 |
+
Push the pretrained model to the hub. This method is a wrapper around
|
| 485 |
+
`transformers.PreTrainedModel.push_to_hub`. Please refer to the documentation
|
| 486 |
+
of `transformers.PreTrainedModel.push_to_hub` for more information.
|
| 487 |
+
|
| 488 |
+
Args:
|
| 489 |
+
*args (`list`, *optional*):
|
| 490 |
+
Positional arguments passed along to the underlying model's
|
| 491 |
+
`push_to_hub` method.
|
| 492 |
+
**kwargs (`dict`, *optional*):
|
| 493 |
+
Keyword arguments passed along to the underlying model's
|
| 494 |
+
`push_to_hub` method.
|
| 495 |
+
"""
|
| 496 |
+
raise NotImplementedError
|
| 497 |
+
|
| 498 |
+
def save_pretrained(self, *args, **kwargs):
|
| 499 |
+
r"""
|
| 500 |
+
Save the pretrained model to a directory. This method is a wrapper around
|
| 501 |
+
`transformers.PreTrainedModel.save_pretrained`. Please refer to the documentation
|
| 502 |
+
of `transformers.PreTrainedModel.save_pretrained` for more information.
|
| 503 |
+
|
| 504 |
+
Args:
|
| 505 |
+
*args (`list`, *optional*):
|
| 506 |
+
Positional arguments passed along to the underlying model's
|
| 507 |
+
`save_pretrained` method.
|
| 508 |
+
**kwargs (`dict`, *optional*):
|
| 509 |
+
Keyword arguments passed along to the underlying model's
|
| 510 |
+
`save_pretrained` method.
|
| 511 |
+
"""
|
| 512 |
+
state_dict = kwargs.get("state_dict")
|
| 513 |
+
if state_dict is None:
|
| 514 |
+
state_dict = self.state_dict()
|
| 515 |
+
kwargs["state_dict"] = state_dict
|
| 516 |
+
|
| 517 |
+
# if it is a peft model only save the `v_head` state_dict and
|
| 518 |
+
# pop the `state_dict` from the kwargs to avoid slient bugs with `peft`
|
| 519 |
+
if self.is_peft_model:
|
| 520 |
+
save_path = args[0]
|
| 521 |
+
save_path = os.path.join(save_path, "pytorch_model.bin")
|
| 522 |
+
torch.save(state_dict, save_path)
|
| 523 |
+
_ = kwargs.pop("state_dict", None)
|
| 524 |
+
|
| 525 |
+
return self.pretrained_model.save_pretrained(*args, **kwargs)
|
| 526 |
+
|
| 527 |
+
def state_dict(self, *args, **kwargs):
|
| 528 |
+
r"""
|
| 529 |
+
Return the state_dict of the pretrained model.
|
| 530 |
+
"""
|
| 531 |
+
raise NotImplementedError
|
| 532 |
+
|
| 533 |
+
def post_init(self, *args, **kwargs):
|
| 534 |
+
r"""
|
| 535 |
+
Post initialization method. This method is called after the model is
|
| 536 |
+
instantiated and loaded from a checkpoint. It can be used to perform
|
| 537 |
+
additional operations such as loading the state_dict.
|
| 538 |
+
"""
|
| 539 |
+
raise NotImplementedError
|
| 540 |
+
|
| 541 |
+
def compute_reward_score(self, input_ids, attention_mask=None, **kwargs):
|
| 542 |
+
r"""
|
| 543 |
+
Computes the reward score for a given input. The method has first to enable the adapter
|
| 544 |
+
and then compute the reward score. After that the model disables the reward modeling
|
| 545 |
+
adapter and enables the default ppo adapter again.
|
| 546 |
+
"""
|
| 547 |
+
if not self.supports_rm_adapter:
|
| 548 |
+
raise ValueError("This model does not support reward modeling adapter.")
|
| 549 |
+
|
| 550 |
+
# enable rm adapter
|
| 551 |
+
self.pretrained_model.set_adapter(self.rm_adapter_name)
|
| 552 |
+
self.pretrained_model.eval()
|
| 553 |
+
|
| 554 |
+
with torch.no_grad():
|
| 555 |
+
base_model_output = self.pretrained_model(
|
| 556 |
+
input_ids=input_ids,
|
| 557 |
+
attention_mask=attention_mask,
|
| 558 |
+
output_hidden_states=True,
|
| 559 |
+
return_dict=True,
|
| 560 |
+
**kwargs,
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
last_hidden_states = base_model_output.hidden_states[-1]
|
| 564 |
+
scores = self.score(last_hidden_states)
|
| 565 |
+
|
| 566 |
+
self.pretrained_model.set_adapter(self.policy_adapter_name)
|
| 567 |
+
self.pretrained_model.eval()
|
| 568 |
+
|
| 569 |
+
return scores
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def create_reference_model(model: PreTrainedModelWrapper, num_shared_layers: int = None, pattern: str = None) -> PreTrainedModelWrapper:
|
| 573 |
+
"""
|
| 574 |
+
Creates a static reference copy of a model. Note that model will be in `.eval()` mode.
|
| 575 |
+
|
| 576 |
+
Args:
|
| 577 |
+
model (`PreTrainedModelWrapper`): The model to be copied.
|
| 578 |
+
num_shared_layers (`int`, *optional*): The number of initial layers that are shared between both models and kept frozen.
|
| 579 |
+
pattern (`str`, *optional*): The shared layers are selected with a string pattern
|
| 580 |
+
(e.g. "transformer.h.{layer}" for GPT2) and if a custom pattern is necessary it can be passed here.
|
| 581 |
+
|
| 582 |
+
Returns
|
| 583 |
+
`PreTrainedModelWrapper`
|
| 584 |
+
"""
|
| 585 |
+
if is_deepspeed_zero3_enabled():
|
| 586 |
+
raise ValueError("DeepSpeed ZeRO-3 is enabled and is not compatible with `create_reference_model()`. Please instantiate your reference model directly with `AutoCausalLM.from_pretrained()`.")
|
| 587 |
+
|
| 588 |
+
parameter_names = [n for n, _ in model.named_parameters()]
|
| 589 |
+
ref_model = deepcopy(model)
|
| 590 |
+
|
| 591 |
+
# if no layers are shared, return copy of model
|
| 592 |
+
if num_shared_layers is None:
|
| 593 |
+
for param_name in parameter_names:
|
| 594 |
+
param = ref_model.get_parameter(param_name)
|
| 595 |
+
param.requires_grad = False
|
| 596 |
+
return ref_model.eval()
|
| 597 |
+
|
| 598 |
+
# identify layer name pattern
|
| 599 |
+
if pattern is not None:
|
| 600 |
+
pattern = pattern.format(layer=num_shared_layers)
|
| 601 |
+
else:
|
| 602 |
+
for pattern_candidate in LAYER_PATTERNS:
|
| 603 |
+
pattern_candidate = pattern_candidate.format(layer=num_shared_layers)
|
| 604 |
+
if any([pattern_candidate in name for name in parameter_names]):
|
| 605 |
+
pattern = pattern_candidate
|
| 606 |
+
break
|
| 607 |
+
|
| 608 |
+
if pattern is None:
|
| 609 |
+
raise ValueError("Layer pattern could not be matched.")
|
| 610 |
+
|
| 611 |
+
# divide parameters in shared and unshared parameter lists
|
| 612 |
+
shared_param_list = []
|
| 613 |
+
unshared_param_list = []
|
| 614 |
+
|
| 615 |
+
shared_parameter = True
|
| 616 |
+
for name, param in model.named_parameters():
|
| 617 |
+
if pattern in name:
|
| 618 |
+
shared_parameter = False
|
| 619 |
+
if shared_parameter:
|
| 620 |
+
shared_param_list.append(name)
|
| 621 |
+
else:
|
| 622 |
+
unshared_param_list.append(name)
|
| 623 |
+
|
| 624 |
+
# create reference of the original parameter if they are shared
|
| 625 |
+
for param_name in shared_param_list:
|
| 626 |
+
param = model.get_parameter(param_name)
|
| 627 |
+
param.requires_grad = False
|
| 628 |
+
|
| 629 |
+
ref_param = ref_model.get_parameter(param_name) # noqa
|
| 630 |
+
ref_param = param # noqa
|
| 631 |
+
|
| 632 |
+
# for all other parameters just make sure they don't use gradients
|
| 633 |
+
for param_name in unshared_param_list:
|
| 634 |
+
param = ref_model.get_parameter(param_name)
|
| 635 |
+
param.requires_grad = False
|
| 636 |
+
|
| 637 |
+
if pattern is not None and len(unshared_param_list) == 0:
|
| 638 |
+
logging.warning("Pattern passed or found, but no layers matched in the model. Check for a typo.")
|
| 639 |
+
|
| 640 |
+
return ref_model.eval()
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/models/modeling_sd_base.py
ADDED
|
@@ -0,0 +1,624 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 DDPO-pytorch authors (Kevin Black), The HuggingFace Team, metric-space. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import contextlib
|
| 16 |
+
import os
|
| 17 |
+
import warnings
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
from diffusers import DDIMScheduler, StableDiffusionPipeline, UNet2DConditionModel
|
| 24 |
+
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import rescale_noise_cfg
|
| 25 |
+
from diffusers.utils import convert_state_dict_to_diffusers
|
| 26 |
+
|
| 27 |
+
from ..core import randn_tensor
|
| 28 |
+
from ..import_utils import is_peft_available
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if is_peft_available():
|
| 32 |
+
from peft import LoraConfig
|
| 33 |
+
from peft.utils import get_peft_model_state_dict
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@dataclass
|
| 37 |
+
class DDPOPipelineOutput(object):
|
| 38 |
+
"""
|
| 39 |
+
Output class for the diffusers pipeline to be finetuned with the DDPO trainer
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
images (`torch.Tensor`):
|
| 43 |
+
The generated images.
|
| 44 |
+
latents (`List[torch.Tensor]`):
|
| 45 |
+
The latents used to generate the images.
|
| 46 |
+
log_probs (`List[torch.Tensor]`):
|
| 47 |
+
The log probabilities of the latents.
|
| 48 |
+
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
images: torch.Tensor
|
| 52 |
+
latents: torch.Tensor
|
| 53 |
+
log_probs: torch.Tensor
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@dataclass
|
| 57 |
+
class DDPOSchedulerOutput(object):
|
| 58 |
+
"""
|
| 59 |
+
Output class for the diffusers scheduler to be finetuned with the DDPO trainer
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
latents (`torch.Tensor`):
|
| 63 |
+
Predicted sample at the previous timestep. Shape: `(batch_size, num_channels, height, width)`
|
| 64 |
+
log_probs (`torch.Tensor`):
|
| 65 |
+
Log probability of the above mentioned sample. Shape: `(batch_size)`
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
latents: torch.Tensor
|
| 69 |
+
log_probs: torch.Tensor
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class DDPOStableDiffusionPipeline(object):
|
| 73 |
+
"""
|
| 74 |
+
Main class for the diffusers pipeline to be finetuned with the DDPO trainer
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
def __call__(self, *args, **kwargs) -> DDPOPipelineOutput:
|
| 78 |
+
raise NotImplementedError
|
| 79 |
+
|
| 80 |
+
def scheduler_step(self, *args, **kwargs) -> DDPOSchedulerOutput:
|
| 81 |
+
raise NotImplementedError
|
| 82 |
+
|
| 83 |
+
@property
|
| 84 |
+
def unet(self):
|
| 85 |
+
"""
|
| 86 |
+
Returns the 2d U-Net model used for diffusion.
|
| 87 |
+
"""
|
| 88 |
+
raise NotImplementedError
|
| 89 |
+
|
| 90 |
+
@property
|
| 91 |
+
def vae(self):
|
| 92 |
+
"""
|
| 93 |
+
Returns the Variational Autoencoder model used from mapping images to and from the latent space
|
| 94 |
+
"""
|
| 95 |
+
raise NotImplementedError
|
| 96 |
+
|
| 97 |
+
@property
|
| 98 |
+
def tokenizer(self):
|
| 99 |
+
"""
|
| 100 |
+
Returns the tokenizer used for tokenizing text inputs
|
| 101 |
+
"""
|
| 102 |
+
raise NotImplementedError
|
| 103 |
+
|
| 104 |
+
@property
|
| 105 |
+
def scheduler(self):
|
| 106 |
+
"""
|
| 107 |
+
Returns the scheduler associated with the pipeline used for the diffusion process
|
| 108 |
+
"""
|
| 109 |
+
raise NotImplementedError
|
| 110 |
+
|
| 111 |
+
@property
|
| 112 |
+
def text_encoder(self):
|
| 113 |
+
"""
|
| 114 |
+
Returns the text encoder used for encoding text inputs
|
| 115 |
+
"""
|
| 116 |
+
raise NotImplementedError
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def autocast(self):
|
| 120 |
+
"""
|
| 121 |
+
Returns the autocast context manager
|
| 122 |
+
"""
|
| 123 |
+
raise NotImplementedError
|
| 124 |
+
|
| 125 |
+
def set_progress_bar_config(self, *args, **kwargs):
|
| 126 |
+
"""
|
| 127 |
+
Sets the progress bar config for the pipeline
|
| 128 |
+
"""
|
| 129 |
+
raise NotImplementedError
|
| 130 |
+
|
| 131 |
+
def save_pretrained(self, *args, **kwargs):
|
| 132 |
+
"""
|
| 133 |
+
Saves all of the model weights
|
| 134 |
+
"""
|
| 135 |
+
raise NotImplementedError
|
| 136 |
+
|
| 137 |
+
def get_trainable_layers(self, *args, **kwargs):
|
| 138 |
+
"""
|
| 139 |
+
Returns the trainable parameters of the pipeline
|
| 140 |
+
"""
|
| 141 |
+
raise NotImplementedError
|
| 142 |
+
|
| 143 |
+
def save_checkpoint(self, *args, **kwargs):
|
| 144 |
+
"""
|
| 145 |
+
Light wrapper around accelerate's register_save_state_pre_hook which is run before saving state
|
| 146 |
+
"""
|
| 147 |
+
raise NotImplementedError
|
| 148 |
+
|
| 149 |
+
def load_checkpoint(self, *args, **kwargs):
|
| 150 |
+
"""
|
| 151 |
+
Light wrapper around accelerate's register_lad_state_pre_hook which is run before loading state
|
| 152 |
+
"""
|
| 153 |
+
raise NotImplementedError
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _left_broadcast(input_tensor, shape):
|
| 157 |
+
"""
|
| 158 |
+
As opposed to the default direction of broadcasting (right to left), this function broadcasts
|
| 159 |
+
from left to right
|
| 160 |
+
Args:
|
| 161 |
+
input_tensor (`torch.FloatTensor`): is the tensor to broadcast
|
| 162 |
+
shape (`Tuple[int]`): is the shape to broadcast to
|
| 163 |
+
"""
|
| 164 |
+
input_ndim = input_tensor.ndim
|
| 165 |
+
if input_ndim > len(shape):
|
| 166 |
+
raise ValueError("The number of dimensions of the tensor to broadcast cannot be greater than the length of the shape to broadcast to")
|
| 167 |
+
return input_tensor.reshape(input_tensor.shape + (1,) * (len(shape) - input_ndim)).broadcast_to(shape)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _get_variance(self, timestep, prev_timestep):
|
| 171 |
+
alpha_prod_t = torch.gather(self.alphas_cumprod, 0, timestep.cpu()).to(timestep.device)
|
| 172 |
+
alpha_prod_t_prev = torch.where(
|
| 173 |
+
prev_timestep.cpu() >= 0,
|
| 174 |
+
self.alphas_cumprod.gather(0, prev_timestep.cpu()),
|
| 175 |
+
self.final_alpha_cumprod,
|
| 176 |
+
).to(timestep.device)
|
| 177 |
+
beta_prod_t = 1 - alpha_prod_t
|
| 178 |
+
beta_prod_t_prev = 1 - alpha_prod_t_prev
|
| 179 |
+
|
| 180 |
+
variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)
|
| 181 |
+
|
| 182 |
+
return variance
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def scheduler_step(
|
| 186 |
+
self,
|
| 187 |
+
model_output: torch.FloatTensor,
|
| 188 |
+
timestep: int,
|
| 189 |
+
sample: torch.FloatTensor,
|
| 190 |
+
eta: float = 0.0,
|
| 191 |
+
use_clipped_model_output: bool = False,
|
| 192 |
+
generator=None,
|
| 193 |
+
prev_sample: Optional[torch.FloatTensor] = None,
|
| 194 |
+
) -> DDPOSchedulerOutput:
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
|
| 198 |
+
process from the learned model outputs (most often the predicted noise).
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
model_output (`torch.FloatTensor`): direct output from learned diffusion model.
|
| 202 |
+
timestep (`int`): current discrete timestep in the diffusion chain.
|
| 203 |
+
sample (`torch.FloatTensor`):
|
| 204 |
+
current instance of sample being created by diffusion process.
|
| 205 |
+
eta (`float`): weight of noise for added noise in diffusion step.
|
| 206 |
+
use_clipped_model_output (`bool`): if `True`, compute "corrected" `model_output` from the clipped
|
| 207 |
+
predicted original sample. Necessary because predicted original sample is clipped to [-1, 1] when
|
| 208 |
+
`self.config.clip_sample` is `True`. If no clipping has happened, "corrected" `model_output` would
|
| 209 |
+
coincide with the one provided as input and `use_clipped_model_output` will have not effect.
|
| 210 |
+
generator: random number generator.
|
| 211 |
+
variance_noise (`torch.FloatTensor`): instead of generating noise for the variance using `generator`, we
|
| 212 |
+
can directly provide the noise for the variance itself. This is useful for methods such as
|
| 213 |
+
CycleDiffusion. (https://arxiv.org/abs/2210.05559)
|
| 214 |
+
|
| 215 |
+
Returns:
|
| 216 |
+
`DDPOSchedulerOutput`: the predicted sample at the previous timestep and the log probability of the sample
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
if self.num_inference_steps is None:
|
| 220 |
+
raise ValueError("Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler")
|
| 221 |
+
|
| 222 |
+
# See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
|
| 223 |
+
# Ideally, read DDIM paper in-detail understanding
|
| 224 |
+
|
| 225 |
+
# Notation (<variable name> -> <name in paper>
|
| 226 |
+
# - pred_noise_t -> e_theta(x_t, t)
|
| 227 |
+
# - pred_original_sample -> f_theta(x_t, t) or x_0
|
| 228 |
+
# - std_dev_t -> sigma_t
|
| 229 |
+
# - eta -> η
|
| 230 |
+
# - pred_sample_direction -> "direction pointing to x_t"
|
| 231 |
+
# - pred_prev_sample -> "x_t-1"
|
| 232 |
+
|
| 233 |
+
# 1. get previous step value (=t-1)
|
| 234 |
+
prev_timestep = timestep - self.config.num_train_timesteps // self.num_inference_steps
|
| 235 |
+
# to prevent OOB on gather
|
| 236 |
+
prev_timestep = torch.clamp(prev_timestep, 0, self.config.num_train_timesteps - 1)
|
| 237 |
+
|
| 238 |
+
# 2. compute alphas, betas
|
| 239 |
+
alpha_prod_t = self.alphas_cumprod.gather(0, timestep.cpu())
|
| 240 |
+
alpha_prod_t_prev = torch.where(
|
| 241 |
+
prev_timestep.cpu() >= 0,
|
| 242 |
+
self.alphas_cumprod.gather(0, prev_timestep.cpu()),
|
| 243 |
+
self.final_alpha_cumprod,
|
| 244 |
+
)
|
| 245 |
+
alpha_prod_t = _left_broadcast(alpha_prod_t, sample.shape).to(sample.device)
|
| 246 |
+
alpha_prod_t_prev = _left_broadcast(alpha_prod_t_prev, sample.shape).to(sample.device)
|
| 247 |
+
|
| 248 |
+
beta_prod_t = 1 - alpha_prod_t
|
| 249 |
+
|
| 250 |
+
# 3. compute predicted original sample from predicted noise also called
|
| 251 |
+
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
|
| 252 |
+
if self.config.prediction_type == "epsilon":
|
| 253 |
+
pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
|
| 254 |
+
pred_epsilon = model_output
|
| 255 |
+
elif self.config.prediction_type == "sample":
|
| 256 |
+
pred_original_sample = model_output
|
| 257 |
+
pred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)
|
| 258 |
+
elif self.config.prediction_type == "v_prediction":
|
| 259 |
+
pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
|
| 260 |
+
pred_epsilon = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
|
| 261 |
+
else:
|
| 262 |
+
raise ValueError(f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" " `v_prediction`")
|
| 263 |
+
|
| 264 |
+
# 4. Clip or threshold "predicted x_0"
|
| 265 |
+
if self.config.thresholding:
|
| 266 |
+
pred_original_sample = self._threshold_sample(pred_original_sample)
|
| 267 |
+
elif self.config.clip_sample:
|
| 268 |
+
pred_original_sample = pred_original_sample.clamp(-self.config.clip_sample_range, self.config.clip_sample_range)
|
| 269 |
+
|
| 270 |
+
# 5. compute variance: "sigma_t(η)" -> see formula (16)
|
| 271 |
+
# σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
|
| 272 |
+
variance = _get_variance(self, timestep, prev_timestep)
|
| 273 |
+
std_dev_t = eta * variance ** (0.5)
|
| 274 |
+
std_dev_t = _left_broadcast(std_dev_t, sample.shape).to(sample.device)
|
| 275 |
+
|
| 276 |
+
if use_clipped_model_output:
|
| 277 |
+
# the pred_epsilon is always re-derived from the clipped x_0 in Glide
|
| 278 |
+
pred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)
|
| 279 |
+
|
| 280 |
+
# 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
|
| 281 |
+
pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * pred_epsilon
|
| 282 |
+
|
| 283 |
+
# 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
|
| 284 |
+
prev_sample_mean = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
|
| 285 |
+
|
| 286 |
+
if prev_sample is not None and generator is not None:
|
| 287 |
+
raise ValueError("Cannot pass both generator and prev_sample. Please make sure that either `generator` or" " `prev_sample` stays `None`.")
|
| 288 |
+
|
| 289 |
+
if prev_sample is None:
|
| 290 |
+
variance_noise = randn_tensor(
|
| 291 |
+
model_output.shape,
|
| 292 |
+
generator=generator,
|
| 293 |
+
device=model_output.device,
|
| 294 |
+
dtype=model_output.dtype,
|
| 295 |
+
)
|
| 296 |
+
prev_sample = prev_sample_mean + std_dev_t * variance_noise
|
| 297 |
+
|
| 298 |
+
# log prob of prev_sample given prev_sample_mean and std_dev_t
|
| 299 |
+
log_prob = -((prev_sample.detach() - prev_sample_mean) ** 2) / (2 * (std_dev_t**2)) - torch.log(std_dev_t) - torch.log(torch.sqrt(2 * torch.as_tensor(np.pi)))
|
| 300 |
+
# mean along all but batch dimension
|
| 301 |
+
log_prob = log_prob.mean(dim=tuple(range(1, log_prob.ndim)))
|
| 302 |
+
|
| 303 |
+
return DDPOSchedulerOutput(prev_sample.type(sample.dtype), log_prob)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# 1. The output type for call is different as the logprobs are now returned
|
| 307 |
+
# 2. An extra method called `scheduler_step` is added which is used to constraint the scheduler output
|
| 308 |
+
@torch.no_grad()
|
| 309 |
+
def pipeline_step(
|
| 310 |
+
self,
|
| 311 |
+
prompt: Optional[Union[str, List[str]]] = None,
|
| 312 |
+
height: Optional[int] = None,
|
| 313 |
+
width: Optional[int] = None,
|
| 314 |
+
num_inference_steps: int = 50,
|
| 315 |
+
guidance_scale: float = 7.5,
|
| 316 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 317 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 318 |
+
eta: float = 0.0,
|
| 319 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 320 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 321 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 322 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 323 |
+
output_type: Optional[str] = "pil",
|
| 324 |
+
return_dict: bool = True,
|
| 325 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 326 |
+
callback_steps: int = 1,
|
| 327 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 328 |
+
guidance_rescale: float = 0.0,
|
| 329 |
+
):
|
| 330 |
+
r"""
|
| 331 |
+
Function invoked when calling the pipeline for generation. Args: prompt (`str` or `List[str]`, *optional*): The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. instead. height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): The height in pixels of the generated image.
|
| 332 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 333 |
+
The width in pixels of the generated image.
|
| 334 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 335 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 336 |
+
expense of slower inference.
|
| 337 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 338 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
| 339 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
| 340 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
| 341 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
| 342 |
+
usually at the expense of lower image quality.
|
| 343 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 344 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 345 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 346 |
+
less than `1`).
|
| 347 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 348 |
+
The number of images to generate per prompt.
|
| 349 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 350 |
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
| 351 |
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
| 352 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 353 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 354 |
+
to make generation deterministic.
|
| 355 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 356 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
| 357 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 358 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
| 359 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 360 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 361 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 362 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 363 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 364 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 365 |
+
argument.
|
| 366 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 367 |
+
The output format of the generate image. Choose between
|
| 368 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 369 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 370 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 371 |
+
plain tuple.
|
| 372 |
+
callback (`Callable`, *optional*):
|
| 373 |
+
A function that will be called every `callback_steps` steps during inference. The function will be
|
| 374 |
+
called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 375 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 376 |
+
The frequency at which the `callback` function will be called. If not specified, the callback will be
|
| 377 |
+
called at every step.
|
| 378 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 379 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 380 |
+
`self.processor` in
|
| 381 |
+
[diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
|
| 382 |
+
guidance_rescale (`float`, *optional*, defaults to 0.7):
|
| 383 |
+
Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
|
| 384 |
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
|
| 385 |
+
[Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
|
| 386 |
+
Guidance rescale factor should fix overexposure when using zero terminal SNR.
|
| 387 |
+
|
| 388 |
+
Examples:
|
| 389 |
+
|
| 390 |
+
Returns:
|
| 391 |
+
`DDPOPipelineOutput`: The generated image, the predicted latents used to generate the image and the associated log probabilities
|
| 392 |
+
"""
|
| 393 |
+
# 0. Default height and width to unet
|
| 394 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 395 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 396 |
+
|
| 397 |
+
# 1. Check inputs. Raise error if not correct
|
| 398 |
+
self.check_inputs(
|
| 399 |
+
prompt,
|
| 400 |
+
height,
|
| 401 |
+
width,
|
| 402 |
+
callback_steps,
|
| 403 |
+
negative_prompt,
|
| 404 |
+
prompt_embeds,
|
| 405 |
+
negative_prompt_embeds,
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
# 2. Define call parameters
|
| 409 |
+
if prompt is not None and isinstance(prompt, str):
|
| 410 |
+
batch_size = 1
|
| 411 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 412 |
+
batch_size = len(prompt)
|
| 413 |
+
else:
|
| 414 |
+
batch_size = prompt_embeds.shape[0]
|
| 415 |
+
|
| 416 |
+
device = self._execution_device
|
| 417 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 418 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 419 |
+
# corresponds to doing no classifier free guidance.
|
| 420 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 421 |
+
|
| 422 |
+
# 3. Encode input prompt
|
| 423 |
+
text_encoder_lora_scale = cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
| 424 |
+
prompt_embeds = self._encode_prompt(
|
| 425 |
+
prompt,
|
| 426 |
+
device,
|
| 427 |
+
num_images_per_prompt,
|
| 428 |
+
do_classifier_free_guidance,
|
| 429 |
+
negative_prompt,
|
| 430 |
+
prompt_embeds=prompt_embeds,
|
| 431 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 432 |
+
lora_scale=text_encoder_lora_scale,
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# 4. Prepare timesteps
|
| 436 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 437 |
+
timesteps = self.scheduler.timesteps
|
| 438 |
+
|
| 439 |
+
# 5. Prepare latent variables
|
| 440 |
+
num_channels_latents = self.unet.config.in_channels
|
| 441 |
+
latents = self.prepare_latents(
|
| 442 |
+
batch_size * num_images_per_prompt,
|
| 443 |
+
num_channels_latents,
|
| 444 |
+
height,
|
| 445 |
+
width,
|
| 446 |
+
prompt_embeds.dtype,
|
| 447 |
+
device,
|
| 448 |
+
generator,
|
| 449 |
+
latents,
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
# 6. Denoising loop
|
| 453 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 454 |
+
all_latents = [latents]
|
| 455 |
+
all_log_probs = []
|
| 456 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 457 |
+
for i, t in enumerate(timesteps):
|
| 458 |
+
# expand the latents if we are doing classifier free guidance
|
| 459 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 460 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 461 |
+
|
| 462 |
+
# predict the noise residual
|
| 463 |
+
noise_pred = self.unet(
|
| 464 |
+
latent_model_input,
|
| 465 |
+
t,
|
| 466 |
+
encoder_hidden_states=prompt_embeds,
|
| 467 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
| 468 |
+
return_dict=False,
|
| 469 |
+
)[0]
|
| 470 |
+
|
| 471 |
+
# perform guidance
|
| 472 |
+
if do_classifier_free_guidance:
|
| 473 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 474 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 475 |
+
|
| 476 |
+
if do_classifier_free_guidance and guidance_rescale > 0.0:
|
| 477 |
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
| 478 |
+
noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
|
| 479 |
+
|
| 480 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 481 |
+
scheduler_output = scheduler_step(self.scheduler, noise_pred, t, latents, eta)
|
| 482 |
+
latents = scheduler_output.latents
|
| 483 |
+
log_prob = scheduler_output.log_probs
|
| 484 |
+
|
| 485 |
+
all_latents.append(latents)
|
| 486 |
+
all_log_probs.append(log_prob)
|
| 487 |
+
|
| 488 |
+
# call the callback, if provided
|
| 489 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 490 |
+
progress_bar.update()
|
| 491 |
+
if callback is not None and i % callback_steps == 0:
|
| 492 |
+
callback(i, t, latents)
|
| 493 |
+
|
| 494 |
+
if not output_type == "latent":
|
| 495 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
| 496 |
+
image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
|
| 497 |
+
else:
|
| 498 |
+
image = latents
|
| 499 |
+
has_nsfw_concept = None
|
| 500 |
+
|
| 501 |
+
if has_nsfw_concept is None:
|
| 502 |
+
do_denormalize = [True] * image.shape[0]
|
| 503 |
+
else:
|
| 504 |
+
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
| 505 |
+
|
| 506 |
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
| 507 |
+
|
| 508 |
+
# Offload last model to CPU
|
| 509 |
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
| 510 |
+
self.final_offload_hook.offload()
|
| 511 |
+
|
| 512 |
+
return DDPOPipelineOutput(image, all_latents, all_log_probs)
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
class DefaultDDPOStableDiffusionPipeline(DDPOStableDiffusionPipeline):
|
| 516 |
+
def __init__(self, pretrained_model_name: str, *, pretrained_model_revision: str = "main", use_lora: bool = True):
|
| 517 |
+
self.sd_pipeline = StableDiffusionPipeline.from_pretrained(pretrained_model_name, revision=pretrained_model_revision)
|
| 518 |
+
|
| 519 |
+
self.use_lora = use_lora
|
| 520 |
+
self.pretrained_model = pretrained_model_name
|
| 521 |
+
self.pretrained_revision = pretrained_model_revision
|
| 522 |
+
|
| 523 |
+
try:
|
| 524 |
+
self.sd_pipeline.load_lora_weights(
|
| 525 |
+
pretrained_model_name,
|
| 526 |
+
weight_name="pytorch_lora_weights.safetensors",
|
| 527 |
+
revision=pretrained_model_revision,
|
| 528 |
+
)
|
| 529 |
+
self.use_lora = True
|
| 530 |
+
except OSError:
|
| 531 |
+
if use_lora:
|
| 532 |
+
warnings.warn("If you are aware that the pretrained model has no lora weights to it, ignore this message. " "Otherwise please check the if `pytorch_lora_weights.safetensors` exists in the model folder.")
|
| 533 |
+
|
| 534 |
+
self.sd_pipeline.scheduler = DDIMScheduler.from_config(self.sd_pipeline.scheduler.config)
|
| 535 |
+
self.sd_pipeline.safety_checker = None
|
| 536 |
+
|
| 537 |
+
# memory optimization
|
| 538 |
+
self.sd_pipeline.vae.requires_grad_(False)
|
| 539 |
+
self.sd_pipeline.text_encoder.requires_grad_(False)
|
| 540 |
+
self.sd_pipeline.unet.requires_grad_(not self.use_lora)
|
| 541 |
+
|
| 542 |
+
def __call__(self, *args, **kwargs) -> DDPOPipelineOutput:
|
| 543 |
+
return pipeline_step(self.sd_pipeline, *args, **kwargs)
|
| 544 |
+
|
| 545 |
+
def scheduler_step(self, *args, **kwargs) -> DDPOSchedulerOutput:
|
| 546 |
+
return scheduler_step(self.sd_pipeline.scheduler, *args, **kwargs)
|
| 547 |
+
|
| 548 |
+
@property
|
| 549 |
+
def unet(self):
|
| 550 |
+
return self.sd_pipeline.unet
|
| 551 |
+
|
| 552 |
+
@property
|
| 553 |
+
def vae(self):
|
| 554 |
+
return self.sd_pipeline.vae
|
| 555 |
+
|
| 556 |
+
@property
|
| 557 |
+
def tokenizer(self):
|
| 558 |
+
return self.sd_pipeline.tokenizer
|
| 559 |
+
|
| 560 |
+
@property
|
| 561 |
+
def scheduler(self):
|
| 562 |
+
return self.sd_pipeline.scheduler
|
| 563 |
+
|
| 564 |
+
@property
|
| 565 |
+
def text_encoder(self):
|
| 566 |
+
return self.sd_pipeline.text_encoder
|
| 567 |
+
|
| 568 |
+
@property
|
| 569 |
+
def autocast(self):
|
| 570 |
+
return contextlib.nullcontext if self.use_lora else None
|
| 571 |
+
|
| 572 |
+
def save_pretrained(self, output_dir):
|
| 573 |
+
if self.use_lora:
|
| 574 |
+
state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(self.sd_pipeline.unet))
|
| 575 |
+
self.sd_pipeline.save_lora_weights(save_directory=output_dir, unet_lora_layers=state_dict)
|
| 576 |
+
self.sd_pipeline.save_pretrained(output_dir)
|
| 577 |
+
|
| 578 |
+
def set_progress_bar_config(self, *args, **kwargs):
|
| 579 |
+
self.sd_pipeline.set_progress_bar_config(*args, **kwargs)
|
| 580 |
+
|
| 581 |
+
def get_trainable_layers(self):
|
| 582 |
+
if self.use_lora:
|
| 583 |
+
lora_config = LoraConfig(
|
| 584 |
+
r=4,
|
| 585 |
+
lora_alpha=4,
|
| 586 |
+
init_lora_weights="gaussian",
|
| 587 |
+
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
|
| 588 |
+
)
|
| 589 |
+
self.sd_pipeline.unet.add_adapter(lora_config)
|
| 590 |
+
|
| 591 |
+
# To avoid accelerate unscaling problems in FP16.
|
| 592 |
+
for param in self.sd_pipeline.unet.parameters():
|
| 593 |
+
# only upcast trainable parameters (LoRA) into fp32
|
| 594 |
+
if param.requires_grad:
|
| 595 |
+
param.data = param.to(torch.float32)
|
| 596 |
+
return self.sd_pipeline.unet
|
| 597 |
+
else:
|
| 598 |
+
return self.sd_pipeline.unet
|
| 599 |
+
|
| 600 |
+
def save_checkpoint(self, models, weights, output_dir):
|
| 601 |
+
if len(models) != 1:
|
| 602 |
+
raise ValueError("Given how the trainable params were set, this should be of length 1")
|
| 603 |
+
if self.use_lora and hasattr(models[0], "peft_config") and getattr(models[0], "peft_config", None) is not None:
|
| 604 |
+
state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(models[0]))
|
| 605 |
+
self.sd_pipeline.save_lora_weights(save_directory=output_dir, unet_lora_layers=state_dict)
|
| 606 |
+
elif not self.use_lora and isinstance(models[0], UNet2DConditionModel):
|
| 607 |
+
models[0].save_pretrained(os.path.join(output_dir, "unet"))
|
| 608 |
+
else:
|
| 609 |
+
raise ValueError(f"Unknown model type {type(models[0])}")
|
| 610 |
+
|
| 611 |
+
def load_checkpoint(self, models, input_dir):
|
| 612 |
+
if len(models) != 1:
|
| 613 |
+
raise ValueError("Given how the trainable params were set, this should be of length 1")
|
| 614 |
+
if self.use_lora:
|
| 615 |
+
lora_state_dict, network_alphas = self.sd_pipeline.lora_state_dict(input_dir, weight_name="pytorch_lora_weights.safetensors")
|
| 616 |
+
self.sd_pipeline.load_lora_into_unet(lora_state_dict, network_alphas=network_alphas, unet=models[0])
|
| 617 |
+
|
| 618 |
+
elif not self.use_lora and isinstance(models[0], UNet2DConditionModel):
|
| 619 |
+
load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet")
|
| 620 |
+
models[0].register_to_config(**load_model.config)
|
| 621 |
+
models[0].load_state_dict(load_model.state_dict())
|
| 622 |
+
del load_model
|
| 623 |
+
else:
|
| 624 |
+
raise ValueError(f"Unknown model type {type(models[0])}")
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/models/modeling_value_head.py
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn as nn
|
| 16 |
+
from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM
|
| 17 |
+
|
| 18 |
+
from .modeling_base import PreTrainedModelWrapper
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ValueHead(nn.Module):
|
| 22 |
+
r"""
|
| 23 |
+
The ValueHead class implements a head for GPT2 that returns a scalar for each output token.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, config, **kwargs):
|
| 27 |
+
super().__init__()
|
| 28 |
+
if not hasattr(config, "summary_dropout_prob"):
|
| 29 |
+
summary_dropout_prob = kwargs.pop("summary_dropout_prob", 0.1)
|
| 30 |
+
else:
|
| 31 |
+
summary_dropout_prob = config.summary_dropout_prob
|
| 32 |
+
|
| 33 |
+
self.dropout = nn.Dropout(summary_dropout_prob) if summary_dropout_prob else nn.Identity()
|
| 34 |
+
|
| 35 |
+
# some models such as OPT have a projection layer before the word embeddings - e.g. OPT-350m
|
| 36 |
+
if hasattr(config, "hidden_size"):
|
| 37 |
+
hidden_size = config.hidden_size
|
| 38 |
+
if hasattr(config, "word_embed_proj_dim"):
|
| 39 |
+
hidden_size = config.word_embed_proj_dim
|
| 40 |
+
elif hasattr(config, "is_encoder_decoder"):
|
| 41 |
+
if config.is_encoder_decoder and hasattr(config, "decoder"):
|
| 42 |
+
if hasattr(config.decoder, "hidden_size"):
|
| 43 |
+
hidden_size = config.decoder.hidden_size
|
| 44 |
+
|
| 45 |
+
self.summary = nn.Linear(hidden_size, 1)
|
| 46 |
+
|
| 47 |
+
self.flatten = nn.Flatten()
|
| 48 |
+
|
| 49 |
+
def forward(self, hidden_states):
|
| 50 |
+
output = self.dropout(hidden_states)
|
| 51 |
+
|
| 52 |
+
# For now force upcast in fp32 if needed. Let's keep the
|
| 53 |
+
# output in fp32 for numerical stability.
|
| 54 |
+
if output.dtype != self.summary.weight.dtype:
|
| 55 |
+
output = output.to(self.summary.weight.dtype)
|
| 56 |
+
|
| 57 |
+
output = self.summary(output)
|
| 58 |
+
return output
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class AutoModelForCausalLMWithValueHead(PreTrainedModelWrapper):
|
| 62 |
+
r"""
|
| 63 |
+
An autoregressive model with a value head in addition to the language model head.
|
| 64 |
+
This class inherits from `~trl.PreTrainedModelWrapper` and wraps a
|
| 65 |
+
`transformers.PreTrainedModel` class. The wrapper class supports classic functions
|
| 66 |
+
such as `from_pretrained`, `push_to_hub` and `generate`. To call a method of the wrapped
|
| 67 |
+
model, simply manipulate the `pretrained_model` attribute of this class.
|
| 68 |
+
|
| 69 |
+
Class attributes:
|
| 70 |
+
- **transformers_parent_class** (`transformers.PreTrainedModel`) -- The parent class of the wrapped model. This
|
| 71 |
+
should be set to `transformers.AutoModelForCausalLM` for this class.
|
| 72 |
+
- **lm_head_namings** (`tuple`) -- A tuple of strings that are used to identify the language model head of the
|
| 73 |
+
wrapped model. This is set to `("lm_head", "embed_out")` for this class but can be changed for other models
|
| 74 |
+
in the future
|
| 75 |
+
- **supported_args** (`tuple`) -- A tuple of strings that are used to identify the arguments that are supported
|
| 76 |
+
by the `ValueHead` class. Currently, the supported args are:
|
| 77 |
+
- **summary_dropout_prob** (`float`, `optional`, defaults to `None`) -- The dropout probability for the
|
| 78 |
+
`ValueHead` class.
|
| 79 |
+
- **v_head_initializer_range** (`float`, `optional`, defaults to `0.2`) -- The initializer range for the
|
| 80 |
+
`ValueHead` if a specific initialization strategy is selected.
|
| 81 |
+
- **v_head_init_strategy** (`str`, `optional`, defaults to `None`) -- The initialization strategy for the
|
| 82 |
+
`ValueHead`. Currently, the supported strategies are:
|
| 83 |
+
- **`None`** -- Initializes the weights of the `ValueHead` with a random distribution. This is the default
|
| 84 |
+
strategy.
|
| 85 |
+
- **"normal"** -- Initializes the weights of the `ValueHead` with a normal distribution.
|
| 86 |
+
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
transformers_parent_class = AutoModelForCausalLM
|
| 90 |
+
lm_head_namings = ["lm_head", "embed_out"]
|
| 91 |
+
supported_args = (
|
| 92 |
+
"summary_dropout_prob",
|
| 93 |
+
"v_head_initializer_range",
|
| 94 |
+
"v_head_init_strategy",
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
def __init__(self, pretrained_model, **kwargs):
|
| 98 |
+
r"""
|
| 99 |
+
Initializes the model.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
pretrained_model (`transformers.PreTrainedModel`):
|
| 103 |
+
The model to wrap. It should be a causal language model such as GPT2.
|
| 104 |
+
or any model mapped inside the `AutoModelForCausalLM` class.
|
| 105 |
+
kwargs (`dict`, `optional`):
|
| 106 |
+
Additional keyword arguments, that are passed to the `ValueHead` class.
|
| 107 |
+
"""
|
| 108 |
+
super().__init__(pretrained_model, **kwargs)
|
| 109 |
+
v_head_kwargs, _, _ = self._split_kwargs(kwargs)
|
| 110 |
+
|
| 111 |
+
if not any(hasattr(self.pretrained_model, attribute) for attribute in self.lm_head_namings):
|
| 112 |
+
raise ValueError("The model does not have a language model head, please use a model that has one.")
|
| 113 |
+
|
| 114 |
+
self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs)
|
| 115 |
+
|
| 116 |
+
self._init_weights(**v_head_kwargs)
|
| 117 |
+
|
| 118 |
+
def _init_weights(self, **kwargs):
|
| 119 |
+
r"""
|
| 120 |
+
Initializes the weights of the value head. The default initialization strategy is random.
|
| 121 |
+
Users can pass a different initialization strategy by passing the `v_head_init_strategy` argument
|
| 122 |
+
when calling `.from_pretrained`. Supported strategies are:
|
| 123 |
+
- `normal`: initializes the weights with a normal distribution.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
**kwargs (`dict`, `optional`):
|
| 127 |
+
Additional keyword arguments, that are passed to the `ValueHead` class. These arguments
|
| 128 |
+
can contain the `v_head_init_strategy` argument as well as the `v_head_initializer_range`
|
| 129 |
+
argument.
|
| 130 |
+
"""
|
| 131 |
+
initializer_range = kwargs.pop("v_head_initializer_range", 0.2)
|
| 132 |
+
# random init by default
|
| 133 |
+
init_strategy = kwargs.pop("v_head_init_strategy", None)
|
| 134 |
+
if init_strategy is None:
|
| 135 |
+
# do nothing
|
| 136 |
+
pass
|
| 137 |
+
elif init_strategy == "normal":
|
| 138 |
+
self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range)
|
| 139 |
+
self.v_head.summary.bias.data.zero_()
|
| 140 |
+
|
| 141 |
+
def forward(
|
| 142 |
+
self,
|
| 143 |
+
input_ids=None,
|
| 144 |
+
past_key_values=None,
|
| 145 |
+
attention_mask=None,
|
| 146 |
+
**kwargs,
|
| 147 |
+
):
|
| 148 |
+
r"""
|
| 149 |
+
Applies a forward pass to the wrapped model and returns the logits of the value head.
|
| 150 |
+
|
| 151 |
+
Args:
|
| 152 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 153 |
+
Indices of input sequence tokens in the vocabulary.
|
| 154 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, `optional`):
|
| 155 |
+
Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model
|
| 156 |
+
(see `past_key_values` input) to speed up sequential decoding.
|
| 157 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, `optional`):
|
| 158 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
|
| 159 |
+
- 1 for tokens that are **not masked**,
|
| 160 |
+
- 0 for tokens that are **masked**.
|
| 161 |
+
kwargs (`dict`, `optional`):
|
| 162 |
+
Additional keyword arguments, that are passed to the wrapped model.
|
| 163 |
+
"""
|
| 164 |
+
kwargs["output_hidden_states"] = True # this had already been set in the LORA / PEFT examples
|
| 165 |
+
kwargs["past_key_values"] = past_key_values
|
| 166 |
+
|
| 167 |
+
if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING":
|
| 168 |
+
kwargs.pop("past_key_values")
|
| 169 |
+
|
| 170 |
+
base_model_output = self.pretrained_model(
|
| 171 |
+
input_ids=input_ids,
|
| 172 |
+
attention_mask=attention_mask,
|
| 173 |
+
**kwargs,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
last_hidden_state = base_model_output.hidden_states[-1]
|
| 177 |
+
lm_logits = base_model_output.logits
|
| 178 |
+
loss = base_model_output.loss
|
| 179 |
+
|
| 180 |
+
if last_hidden_state.device != self.v_head.summary.weight.device:
|
| 181 |
+
last_hidden_state = last_hidden_state.to(self.v_head.summary.weight.device)
|
| 182 |
+
|
| 183 |
+
value = self.v_head(last_hidden_state).squeeze(-1)
|
| 184 |
+
|
| 185 |
+
# force upcast in fp32 if logits are in half-precision
|
| 186 |
+
if lm_logits.dtype != torch.float32:
|
| 187 |
+
lm_logits = lm_logits.float()
|
| 188 |
+
|
| 189 |
+
return (lm_logits, loss, value)
|
| 190 |
+
|
| 191 |
+
def generate(self, *args, **kwargs):
|
| 192 |
+
r"""
|
| 193 |
+
A simple wrapper around the `generate` method of the wrapped model.
|
| 194 |
+
Please refer to the [`generate`](https://huggingface.co/docs/transformers/internal/generation_utils)
|
| 195 |
+
method of the wrapped model for more information about the supported arguments.
|
| 196 |
+
|
| 197 |
+
Args:
|
| 198 |
+
*args (`list`, *optional*):
|
| 199 |
+
Positional arguments passed to the `generate` method of the wrapped model.
|
| 200 |
+
**kwargs (`dict`, *optional*):
|
| 201 |
+
Keyword arguments passed to the `generate` method of the wrapped model.
|
| 202 |
+
"""
|
| 203 |
+
return self.pretrained_model.generate(*args, **kwargs)
|
| 204 |
+
|
| 205 |
+
def state_dict(self, *args, **kwargs):
|
| 206 |
+
r"""
|
| 207 |
+
Returns the state dictionary of the model. We add the state dictionary of the value head
|
| 208 |
+
to the state dictionary of the wrapped model by prepending the key with `v_head.`.
|
| 209 |
+
"""
|
| 210 |
+
if not self.is_peft_model:
|
| 211 |
+
pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs)
|
| 212 |
+
else:
|
| 213 |
+
# if it is a peft model, only save the v_head
|
| 214 |
+
pretrained_model_state_dict = {}
|
| 215 |
+
|
| 216 |
+
v_head_state_dict = self.v_head.state_dict(*args, **kwargs)
|
| 217 |
+
for k, v in v_head_state_dict.items():
|
| 218 |
+
pretrained_model_state_dict[f"v_head.{k}"] = v
|
| 219 |
+
return pretrained_model_state_dict
|
| 220 |
+
|
| 221 |
+
def push_to_hub(self, *args, **kwargs):
|
| 222 |
+
setattr(self.pretrained_model, "v_head", self.v_head)
|
| 223 |
+
|
| 224 |
+
return self.pretrained_model.push_to_hub(*args, **kwargs)
|
| 225 |
+
|
| 226 |
+
def post_init(self, state_dict):
|
| 227 |
+
r"""
|
| 228 |
+
We add the state dictionary of the value head to the state dictionary of the wrapped model
|
| 229 |
+
by prepending the key with `v_head.`. This function removes the `v_head.` prefix from the
|
| 230 |
+
keys of the value head state dictionary.
|
| 231 |
+
"""
|
| 232 |
+
for k in list(state_dict.keys()):
|
| 233 |
+
if "v_head." in k:
|
| 234 |
+
state_dict[k.replace("v_head.", "")] = state_dict.pop(k)
|
| 235 |
+
self.v_head.load_state_dict(state_dict, strict=False)
|
| 236 |
+
del state_dict
|
| 237 |
+
|
| 238 |
+
if hasattr(self.pretrained_model, "hf_device_map"):
|
| 239 |
+
if "cpu" in self.pretrained_model.hf_device_map.values() or "disk" in self.pretrained_model.hf_device_map.values():
|
| 240 |
+
raise ValueError("The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models.")
|
| 241 |
+
|
| 242 |
+
first_device = list(set(self.pretrained_model.hf_device_map.values()))[0]
|
| 243 |
+
|
| 244 |
+
self.v_head = self.v_head.to(first_device)
|
| 245 |
+
|
| 246 |
+
def set_device_hook(module, input, outputs):
|
| 247 |
+
new_output = ()
|
| 248 |
+
for output in outputs:
|
| 249 |
+
if isinstance(output, torch.Tensor):
|
| 250 |
+
new_output += (output.to(first_device),)
|
| 251 |
+
else:
|
| 252 |
+
new_output += (output,)
|
| 253 |
+
return new_output
|
| 254 |
+
|
| 255 |
+
self.register_forward_hook(set_device_hook)
|
| 256 |
+
|
| 257 |
+
self.is_sequential_parallel = True
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class AutoModelForSeq2SeqLMWithValueHead(PreTrainedModelWrapper):
|
| 261 |
+
r"""
|
| 262 |
+
A seq2seq model with a value head in addition to the language model head.
|
| 263 |
+
This class inherits from `~trl.PreTrainedModelWrapper` and wraps a
|
| 264 |
+
`transformers.PreTrainedModel` class. The wrapper class supports classic functions
|
| 265 |
+
such as `from_pretrained` and `push_to_hub` and also provides some additional
|
| 266 |
+
functionalities such as `generate`.
|
| 267 |
+
|
| 268 |
+
Args:
|
| 269 |
+
pretrained_model (`transformers.PreTrainedModel`):
|
| 270 |
+
The model to wrap. It should be a causal language model such as GPT2.
|
| 271 |
+
or any model mapped inside the `AutoModelForSeq2SeqLM` class.
|
| 272 |
+
kwargs:
|
| 273 |
+
Additional keyword arguments passed along to the `ValueHead` class.
|
| 274 |
+
"""
|
| 275 |
+
|
| 276 |
+
transformers_parent_class = AutoModelForSeq2SeqLM
|
| 277 |
+
lm_head_namings = ["lm_head", "embed_out", "output_projection"]
|
| 278 |
+
supported_args = (
|
| 279 |
+
"summary_dropout_prob",
|
| 280 |
+
"v_head_initializer_range",
|
| 281 |
+
"v_head_init_strategy",
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
def __init__(self, pretrained_model, **kwargs):
|
| 285 |
+
super().__init__(pretrained_model, **kwargs)
|
| 286 |
+
v_head_kwargs, _, _ = self._split_kwargs(kwargs)
|
| 287 |
+
self.is_encoder_decoder = True
|
| 288 |
+
|
| 289 |
+
if not self._has_lm_head():
|
| 290 |
+
raise ValueError("The model does not have a language model head, please use a model that has one.")
|
| 291 |
+
|
| 292 |
+
self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs)
|
| 293 |
+
|
| 294 |
+
self._init_weights(**v_head_kwargs)
|
| 295 |
+
|
| 296 |
+
def _has_lm_head(self):
|
| 297 |
+
# check module names of all modules inside `pretrained_model` to find the language model head
|
| 298 |
+
for name, module in self.pretrained_model.named_modules():
|
| 299 |
+
if any(attribute in name for attribute in self.lm_head_namings):
|
| 300 |
+
return True
|
| 301 |
+
return False
|
| 302 |
+
|
| 303 |
+
def post_init(self, state_dict):
|
| 304 |
+
r"""
|
| 305 |
+
We add the state dictionary of the value head to the state dictionary of the wrapped model
|
| 306 |
+
by prepending the key with `v_head.`. This function removes the `v_head.` prefix from the
|
| 307 |
+
keys of the value head state dictionary.
|
| 308 |
+
"""
|
| 309 |
+
for k in list(state_dict.keys()):
|
| 310 |
+
if "v_head." in k:
|
| 311 |
+
state_dict[k.replace("v_head.", "")] = state_dict.pop(k)
|
| 312 |
+
self.v_head.load_state_dict(state_dict, strict=False)
|
| 313 |
+
del state_dict
|
| 314 |
+
|
| 315 |
+
if hasattr(self.pretrained_model, "hf_device_map"):
|
| 316 |
+
if "cpu" in self.pretrained_model.hf_device_map.values() or "disk" in self.pretrained_model.hf_device_map.values():
|
| 317 |
+
raise ValueError("The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models.")
|
| 318 |
+
|
| 319 |
+
# get the lm_head device
|
| 320 |
+
for name, module in self.pretrained_model.named_modules():
|
| 321 |
+
if any(attribute in name for attribute in self.lm_head_namings):
|
| 322 |
+
lm_head_device = module.weight.device
|
| 323 |
+
break
|
| 324 |
+
|
| 325 |
+
# put v_head on the same device as the lm_head to avoid issues
|
| 326 |
+
self.v_head = self.v_head.to(lm_head_device)
|
| 327 |
+
|
| 328 |
+
def set_device_hook(module, input, outputs):
|
| 329 |
+
r"""
|
| 330 |
+
A hook that sets the device of the output of the model to the device of the first
|
| 331 |
+
parameter of the model.
|
| 332 |
+
|
| 333 |
+
Args:
|
| 334 |
+
module (`nn.Module`):
|
| 335 |
+
The module to which the hook is attached.
|
| 336 |
+
input (`tuple`):
|
| 337 |
+
The input to the module.
|
| 338 |
+
outputs (`tuple`):
|
| 339 |
+
The output of the module.
|
| 340 |
+
"""
|
| 341 |
+
new_output = ()
|
| 342 |
+
for output in outputs:
|
| 343 |
+
if isinstance(output, torch.Tensor):
|
| 344 |
+
new_output += (output.to(lm_head_device),)
|
| 345 |
+
else:
|
| 346 |
+
new_output += (output,)
|
| 347 |
+
return new_output
|
| 348 |
+
|
| 349 |
+
self.register_forward_hook(set_device_hook)
|
| 350 |
+
self.is_sequential_parallel = True
|
| 351 |
+
|
| 352 |
+
def state_dict(self, *args, **kwargs):
|
| 353 |
+
r"""
|
| 354 |
+
Returns the state dictionary of the model. We add the state dictionary of the value head
|
| 355 |
+
to the state dictionary of the wrapped model by prepending the key with `v_head.`.
|
| 356 |
+
"""
|
| 357 |
+
if not self.is_peft_model:
|
| 358 |
+
pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs)
|
| 359 |
+
else:
|
| 360 |
+
# if it is a peft model, only save the v_head
|
| 361 |
+
pretrained_model_state_dict = {}
|
| 362 |
+
|
| 363 |
+
v_head_state_dict = self.v_head.state_dict(*args, **kwargs)
|
| 364 |
+
for k, v in v_head_state_dict.items():
|
| 365 |
+
pretrained_model_state_dict[f"v_head.{k}"] = v
|
| 366 |
+
return pretrained_model_state_dict
|
| 367 |
+
|
| 368 |
+
def push_to_hub(self, *args, **kwargs):
|
| 369 |
+
setattr(self.pretrained_model, "v_head", self.v_head)
|
| 370 |
+
|
| 371 |
+
return self.pretrained_model.push_to_hub(*args, **kwargs)
|
| 372 |
+
|
| 373 |
+
def _init_weights(self, **kwargs):
|
| 374 |
+
r"""
|
| 375 |
+
We initialize the weights of the value head.
|
| 376 |
+
"""
|
| 377 |
+
initializer_range = kwargs.pop("v_head_initializer_range", 0.2)
|
| 378 |
+
# random init by default
|
| 379 |
+
init_strategy = kwargs.pop("v_head_init_strategy", None)
|
| 380 |
+
if init_strategy is None:
|
| 381 |
+
# do nothing
|
| 382 |
+
pass
|
| 383 |
+
elif init_strategy == "normal":
|
| 384 |
+
self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range)
|
| 385 |
+
self.v_head.summary.bias.data.zero_()
|
| 386 |
+
|
| 387 |
+
def forward(
|
| 388 |
+
self,
|
| 389 |
+
input_ids=None,
|
| 390 |
+
past_key_values=None,
|
| 391 |
+
attention_mask=None,
|
| 392 |
+
**kwargs,
|
| 393 |
+
):
|
| 394 |
+
kwargs["past_key_values"] = past_key_values
|
| 395 |
+
if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING":
|
| 396 |
+
kwargs.pop("past_key_values")
|
| 397 |
+
|
| 398 |
+
base_model_output = self.pretrained_model(
|
| 399 |
+
input_ids=input_ids,
|
| 400 |
+
attention_mask=attention_mask,
|
| 401 |
+
output_hidden_states=True, # We force the model to output hidden states
|
| 402 |
+
**kwargs,
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
last_hidden_state = base_model_output.decoder_hidden_states[-1]
|
| 406 |
+
lm_logits = base_model_output.logits
|
| 407 |
+
loss = base_model_output.loss
|
| 408 |
+
|
| 409 |
+
value = self.v_head(last_hidden_state).squeeze(-1)
|
| 410 |
+
|
| 411 |
+
# force upcast in fp32 if logits are in half-precision
|
| 412 |
+
if lm_logits.dtype != torch.float32:
|
| 413 |
+
lm_logits = lm_logits.float()
|
| 414 |
+
|
| 415 |
+
return (lm_logits, loss, value)
|
| 416 |
+
|
| 417 |
+
def generate(self, *args, **kwargs):
|
| 418 |
+
r"""
|
| 419 |
+
We call `generate` on the wrapped model.
|
| 420 |
+
"""
|
| 421 |
+
return self.pretrained_model.generate(*args, **kwargs)
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/models/utils.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import Literal, Optional, Tuple
|
| 3 |
+
|
| 4 |
+
from transformers import PreTrainedModel, PreTrainedTokenizer
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# TODO: Add Abstract Base Class if more formats are added
|
| 8 |
+
@dataclass
|
| 9 |
+
class ChatMlSpecialTokens:
|
| 10 |
+
"""Dataclass for special tokens used in ChatML, including system, user, assistant, bos, eos, and pad tokens."""
|
| 11 |
+
|
| 12 |
+
bos_token: str = "<|im_start|>"
|
| 13 |
+
eos_token: str = "<|im_end|>"
|
| 14 |
+
pad_token: str = "<|im_end|>"
|
| 15 |
+
|
| 16 |
+
@property
|
| 17 |
+
def system(self):
|
| 18 |
+
return f"{self.bos_token}system"
|
| 19 |
+
|
| 20 |
+
@property
|
| 21 |
+
def user(self):
|
| 22 |
+
return f"{self.bos_token}user"
|
| 23 |
+
|
| 24 |
+
@property
|
| 25 |
+
def assistant(self):
|
| 26 |
+
return f"{self.bos_token}assistant"
|
| 27 |
+
|
| 28 |
+
@property
|
| 29 |
+
def chat_template(self):
|
| 30 |
+
return (
|
| 31 |
+
"{% for message in messages %}"
|
| 32 |
+
f"{{{{'{self.bos_token}' + message['role'] + '\n' + message['content'] + '{self.eos_token}' + '\n'}}}}"
|
| 33 |
+
"{% endfor %}"
|
| 34 |
+
"{% if add_generation_prompt %}"
|
| 35 |
+
f"{{{{ '{self.assistant}\n' }}}}"
|
| 36 |
+
"{% endif %}"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
FORMAT_MAPPING = {"chatml": ChatMlSpecialTokens}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def setup_chat_format(
|
| 44 |
+
model: PreTrainedModel,
|
| 45 |
+
tokenizer: PreTrainedTokenizer,
|
| 46 |
+
format: Optional[Literal["chatml"]] = "chatml",
|
| 47 |
+
resize_to_multiple_of: Optional[int] = None,
|
| 48 |
+
) -> Tuple[PreTrainedModel, PreTrainedTokenizer]:
|
| 49 |
+
"""
|
| 50 |
+
Setup chat format by adding special tokens to the tokenizer, setting the correct format, and extending the embedding layer of the model based on the new special tokens.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
model (`~transformers.PreTrainedModel`): The model to be modified.
|
| 54 |
+
tokenizer (`~transformers.PreTrainedTokenizer`): The tokenizer to be modified.
|
| 55 |
+
format (`Optional[Literal["chatml"]]`): The format to be set. Defaults to "chatml".
|
| 56 |
+
resize_to_multiple_of (`Optional[int]`): Number to resize the embedding layer to. Defaults to None.
|
| 57 |
+
Returns:
|
| 58 |
+
model (`~transformers.PreTrainedModel`): The modified model.
|
| 59 |
+
tokenizer (`~transformers.PreTrainedTokenizer`): The modified tokenizer.
|
| 60 |
+
"""
|
| 61 |
+
# check if format available and retrieve
|
| 62 |
+
if format not in FORMAT_MAPPING:
|
| 63 |
+
raise ValueError(f"Format {format} not available. Please use one of {FORMAT_MAPPING.keys()}")
|
| 64 |
+
|
| 65 |
+
chat_format = FORMAT_MAPPING[format]()
|
| 66 |
+
|
| 67 |
+
# set special tokens and them
|
| 68 |
+
tokenizer.eos_token = chat_format.eos_token
|
| 69 |
+
tokenizer.pad_token = chat_format.pad_token
|
| 70 |
+
tokenizer.bos_token = chat_format.bos_token
|
| 71 |
+
tokenizer.add_special_tokens({"additional_special_tokens": [chat_format.bos_token, chat_format.eos_token]})
|
| 72 |
+
# set chat format for tokenizer
|
| 73 |
+
tokenizer.chat_template = chat_format.chat_template
|
| 74 |
+
|
| 75 |
+
# resize embedding layer to a multiple of 64, https://x.com/karpathy/status/1621578354024677377
|
| 76 |
+
model.resize_token_embeddings(len(tokenizer), pad_to_multiple_of=resize_to_multiple_of if resize_to_multiple_of is not None else None)
|
| 77 |
+
# Make sure to update the generation config to use the new eos & bos token
|
| 78 |
+
if getattr(model, "generation_config", None) is not None:
|
| 79 |
+
model.generation_config.bos_token_id = tokenizer.bos_token_id
|
| 80 |
+
model.generation_config.eos_token_id = tokenizer.eos_token_id
|
| 81 |
+
model.generation_config.pad_token_id = tokenizer.pad_token_id
|
| 82 |
+
|
| 83 |
+
return model, tokenizer
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa
|
| 2 |
+
|
| 3 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
# There is a circular import in the PPOTrainer if we let isort sort these
|
| 18 |
+
# isort: off
|
| 19 |
+
from .utils import (
|
| 20 |
+
AdaptiveKLController,
|
| 21 |
+
FixedKLController,
|
| 22 |
+
ConstantLengthDataset,
|
| 23 |
+
DataCollatorForCompletionOnlyLM,
|
| 24 |
+
RunningMoments,
|
| 25 |
+
disable_dropout_in_model,
|
| 26 |
+
peft_module_casting_to_bf16,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# isort: on
|
| 30 |
+
|
| 31 |
+
from ..import_utils import is_diffusers_available
|
| 32 |
+
from .base import BaseTrainer
|
| 33 |
+
from .ddpo_config import DDPOConfig
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if is_diffusers_available():
|
| 37 |
+
from .ddpo_trainer import DDPOTrainer
|
| 38 |
+
|
| 39 |
+
from .dpo_trainer import DPOTrainer
|
| 40 |
+
from .iterative_sft_trainer import IterativeSFTTrainer
|
| 41 |
+
from .model_config import ModelConfig
|
| 42 |
+
from .ppo_config import PPOConfig
|
| 43 |
+
from .ppo_trainer import PPOTrainer
|
| 44 |
+
from .reward_config import RewardConfig
|
| 45 |
+
from .reward_trainer import RewardTrainer, compute_accuracy
|
| 46 |
+
from .sft_trainer import SFTTrainer
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/base.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from huggingface_hub import PyTorchModelHubMixin
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class BaseTrainer(PyTorchModelHubMixin):
|
| 19 |
+
r"""
|
| 20 |
+
Base class for all trainers - this base class implements the basic functions that we
|
| 21 |
+
need for a trainer.
|
| 22 |
+
|
| 23 |
+
The trainer needs to have the following functions:
|
| 24 |
+
- step: takes in a batch of data and performs a step of training
|
| 25 |
+
- loss: takes in a batch of data and returns the loss
|
| 26 |
+
- compute_rewards: takes in a batch of data and returns the rewards
|
| 27 |
+
- _build_models_and_tokenizer: builds the models and tokenizer
|
| 28 |
+
- _build_dataset: builds the dataset
|
| 29 |
+
Each user is expected to implement their own trainer class that inherits from this base
|
| 30 |
+
if they want to use a new training algorithm.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, config):
|
| 34 |
+
self.config = config
|
| 35 |
+
|
| 36 |
+
def step(self, *args):
|
| 37 |
+
raise NotImplementedError("Not implemented")
|
| 38 |
+
|
| 39 |
+
def loss(self, *args):
|
| 40 |
+
raise NotImplementedError("Not implemented")
|
| 41 |
+
|
| 42 |
+
def compute_rewards(self, *args):
|
| 43 |
+
raise NotImplementedError("Not implemented")
|
| 44 |
+
|
| 45 |
+
def _save_pretrained(self, save_directory):
|
| 46 |
+
raise NotImplementedError("Not implemented")
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/ddpo_config.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import warnings
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from typing import Literal, Optional
|
| 6 |
+
|
| 7 |
+
from ..core import flatten_dict
|
| 8 |
+
from ..import_utils import is_bitsandbytes_available, is_torchvision_available
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass
|
| 12 |
+
class DDPOConfig:
|
| 13 |
+
"""
|
| 14 |
+
Configuration class for DDPOTrainer
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
# common parameters
|
| 18 |
+
exp_name: str = os.path.basename(sys.argv[0])[: -len(".py")]
|
| 19 |
+
"""the name of this experiment (by default is the file name without the extension name)"""
|
| 20 |
+
run_name: Optional[str] = ""
|
| 21 |
+
"""Run name for wandb logging and checkpoint saving."""
|
| 22 |
+
seed: int = 0
|
| 23 |
+
"""Seed value for random generations"""
|
| 24 |
+
log_with: Optional[Literal["wandb", "tensorboard"]] = None
|
| 25 |
+
"""Log with either 'wandb' or 'tensorboard', check https://huggingface.co/docs/accelerate/usage_guides/tracking for more details"""
|
| 26 |
+
tracker_kwargs: dict = field(default_factory=dict)
|
| 27 |
+
"""Keyword arguments for the tracker (e.g. wandb_project)"""
|
| 28 |
+
accelerator_kwargs: dict = field(default_factory=dict)
|
| 29 |
+
"""Keyword arguments for the accelerator"""
|
| 30 |
+
project_kwargs: dict = field(default_factory=dict)
|
| 31 |
+
"""Keyword arguments for the accelerator project config (e.g. `logging_dir`)"""
|
| 32 |
+
tracker_project_name: str = "trl"
|
| 33 |
+
"""Name of project to use for tracking"""
|
| 34 |
+
logdir: str = "logs"
|
| 35 |
+
"""Top-level logging directory for checkpoint saving."""
|
| 36 |
+
|
| 37 |
+
# hyperparameters
|
| 38 |
+
num_epochs: int = 100
|
| 39 |
+
"""Number of epochs to train."""
|
| 40 |
+
save_freq: int = 1
|
| 41 |
+
"""Number of epochs between saving model checkpoints."""
|
| 42 |
+
num_checkpoint_limit: int = 5
|
| 43 |
+
"""Number of checkpoints to keep before overwriting old ones."""
|
| 44 |
+
mixed_precision: str = "fp16"
|
| 45 |
+
"""Mixed precision training."""
|
| 46 |
+
allow_tf32: bool = True
|
| 47 |
+
"""Allow tf32 on Ampere GPUs."""
|
| 48 |
+
resume_from: Optional[str] = ""
|
| 49 |
+
"""Resume training from a checkpoint."""
|
| 50 |
+
sample_num_steps: int = 50
|
| 51 |
+
"""Number of sampler inference steps."""
|
| 52 |
+
sample_eta: float = 1.0
|
| 53 |
+
"""Eta parameter for the DDIM sampler."""
|
| 54 |
+
sample_guidance_scale: float = 5.0
|
| 55 |
+
"""Classifier-free guidance weight."""
|
| 56 |
+
sample_batch_size: int = 1
|
| 57 |
+
"""Batch size (per GPU!) to use for sampling."""
|
| 58 |
+
sample_num_batches_per_epoch: int = 2
|
| 59 |
+
"""Number of batches to sample per epoch."""
|
| 60 |
+
train_batch_size: int = 1
|
| 61 |
+
"""Batch size (per GPU!) to use for training."""
|
| 62 |
+
train_use_8bit_adam: bool = False
|
| 63 |
+
"""Whether to use the 8bit Adam optimizer from bitsandbytes."""
|
| 64 |
+
train_learning_rate: float = 3e-4
|
| 65 |
+
"""Learning rate."""
|
| 66 |
+
train_adam_beta1: float = 0.9
|
| 67 |
+
"""Adam beta1."""
|
| 68 |
+
train_adam_beta2: float = 0.999
|
| 69 |
+
"""Adam beta2."""
|
| 70 |
+
train_adam_weight_decay: float = 1e-4
|
| 71 |
+
"""Adam weight decay."""
|
| 72 |
+
train_adam_epsilon: float = 1e-8
|
| 73 |
+
"""Adam epsilon."""
|
| 74 |
+
train_gradient_accumulation_steps: int = 1
|
| 75 |
+
"""Number of gradient accumulation steps."""
|
| 76 |
+
train_max_grad_norm: float = 1.0
|
| 77 |
+
"""Maximum gradient norm for gradient clipping."""
|
| 78 |
+
train_num_inner_epochs: int = 1
|
| 79 |
+
"""Number of inner epochs per outer epoch."""
|
| 80 |
+
train_cfg: bool = True
|
| 81 |
+
"""Whether or not to use classifier-free guidance during training."""
|
| 82 |
+
train_adv_clip_max: float = 5
|
| 83 |
+
"""Clip advantages to the range."""
|
| 84 |
+
train_clip_range: float = 1e-4
|
| 85 |
+
"""The PPO clip range."""
|
| 86 |
+
train_timestep_fraction: float = 1.0
|
| 87 |
+
"""The fraction of timesteps to train on."""
|
| 88 |
+
per_prompt_stat_tracking: bool = False
|
| 89 |
+
"""Whether to track statistics for each prompt separately."""
|
| 90 |
+
per_prompt_stat_tracking_buffer_size: int = 16
|
| 91 |
+
"""Number of reward values to store in the buffer for each prompt."""
|
| 92 |
+
per_prompt_stat_tracking_min_count: int = 16
|
| 93 |
+
"""The minimum number of reward values to store in the buffer."""
|
| 94 |
+
async_reward_computation: bool = False
|
| 95 |
+
"""Whether to compute rewards asynchronously."""
|
| 96 |
+
max_workers: int = 2
|
| 97 |
+
"""The maximum number of workers to use for async reward computation."""
|
| 98 |
+
negative_prompts: Optional[str] = ""
|
| 99 |
+
"""Comma-separated list of prompts to use as negative examples."""
|
| 100 |
+
|
| 101 |
+
def to_dict(self):
|
| 102 |
+
output_dict = {}
|
| 103 |
+
for key, value in self.__dict__.items():
|
| 104 |
+
output_dict[key] = value
|
| 105 |
+
return flatten_dict(output_dict)
|
| 106 |
+
|
| 107 |
+
def __post_init__(self):
|
| 108 |
+
if self.log_with not in ["wandb", "tensorboard"]:
|
| 109 |
+
warnings.warn(("Accelerator tracking only supports image logging if `log_with` is set to 'wandb' or 'tensorboard'."))
|
| 110 |
+
|
| 111 |
+
if self.log_with == "wandb" and not is_torchvision_available():
|
| 112 |
+
warnings.warn("Wandb image logging requires torchvision to be installed")
|
| 113 |
+
|
| 114 |
+
if self.train_use_8bit_adam and not is_bitsandbytes_available():
|
| 115 |
+
raise ImportError("You need to install bitsandbytes to use 8bit Adam. " "You can install it with `pip install bitsandbytes`.")
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/ddpo_trainer.py
ADDED
|
@@ -0,0 +1,604 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import warnings
|
| 17 |
+
from collections import defaultdict
|
| 18 |
+
from concurrent import futures
|
| 19 |
+
from typing import Any, Callable, Optional, Tuple
|
| 20 |
+
from warnings import warn
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from accelerate import Accelerator
|
| 24 |
+
from accelerate.logging import get_logger
|
| 25 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 26 |
+
from huggingface_hub import whoami
|
| 27 |
+
|
| 28 |
+
from ..models import DDPOStableDiffusionPipeline
|
| 29 |
+
from . import BaseTrainer, DDPOConfig
|
| 30 |
+
from .utils import PerPromptStatTracker
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
MODEL_CARD_TEMPLATE = """---
|
| 37 |
+
license: apache-2.0
|
| 38 |
+
tags:
|
| 39 |
+
- trl
|
| 40 |
+
- ddpo
|
| 41 |
+
- diffusers
|
| 42 |
+
- reinforcement-learning
|
| 43 |
+
- text-to-image
|
| 44 |
+
- stable-diffusion
|
| 45 |
+
---
|
| 46 |
+
|
| 47 |
+
# {model_name}
|
| 48 |
+
|
| 49 |
+
This is a diffusion model that has been fine-tuned with reinforcement learning to
|
| 50 |
+
guide the model outputs according to a value, function, or human feedback. The model can be used for image generation conditioned with text.
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class DDPOTrainer(BaseTrainer):
|
| 56 |
+
"""
|
| 57 |
+
The DDPOTrainer uses Deep Diffusion Policy Optimization to optimise diffusion models.
|
| 58 |
+
Note, this trainer is heavily inspired by the work here: https://github.com/kvablack/ddpo-pytorch
|
| 59 |
+
As of now only Stable Diffusion based pipelines are supported
|
| 60 |
+
|
| 61 |
+
Attributes:
|
| 62 |
+
**config** (`DDPOConfig`) -- Configuration object for DDPOTrainer. Check the documentation of `PPOConfig` for more
|
| 63 |
+
details.
|
| 64 |
+
**reward_function** (Callable[[torch.Tensor, Tuple[str], Tuple[Any]], torch.Tensor]) -- Reward function to be used
|
| 65 |
+
**prompt_function** (Callable[[], Tuple[str, Any]]) -- Function to generate prompts to guide model
|
| 66 |
+
**sd_pipeline** (`DDPOStableDiffusionPipeline`) -- Stable Diffusion pipeline to be used for training.
|
| 67 |
+
**image_samples_hook** (Optional[Callable[[Any, Any, Any], Any]]) -- Hook to be called to log images
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
_tag_names = ["trl", "ddpo"]
|
| 71 |
+
|
| 72 |
+
def __init__(
|
| 73 |
+
self,
|
| 74 |
+
config: DDPOConfig,
|
| 75 |
+
reward_function: Callable[[torch.Tensor, Tuple[str], Tuple[Any]], torch.Tensor],
|
| 76 |
+
prompt_function: Callable[[], Tuple[str, Any]],
|
| 77 |
+
sd_pipeline: DDPOStableDiffusionPipeline,
|
| 78 |
+
image_samples_hook: Optional[Callable[[Any, Any, Any], Any]] = None,
|
| 79 |
+
):
|
| 80 |
+
if image_samples_hook is None:
|
| 81 |
+
warn("No image_samples_hook provided; no images will be logged")
|
| 82 |
+
|
| 83 |
+
self.prompt_fn = prompt_function
|
| 84 |
+
self.reward_fn = reward_function
|
| 85 |
+
self.config = config
|
| 86 |
+
self.image_samples_callback = image_samples_hook
|
| 87 |
+
|
| 88 |
+
accelerator_project_config = ProjectConfiguration(**self.config.project_kwargs)
|
| 89 |
+
|
| 90 |
+
if self.config.resume_from:
|
| 91 |
+
self.config.resume_from = os.path.normpath(os.path.expanduser(self.config.resume_from))
|
| 92 |
+
if "checkpoint_" not in os.path.basename(self.config.resume_from):
|
| 93 |
+
# get the most recent checkpoint in this directory
|
| 94 |
+
checkpoints = list(
|
| 95 |
+
filter(
|
| 96 |
+
lambda x: "checkpoint_" in x,
|
| 97 |
+
os.listdir(self.config.resume_from),
|
| 98 |
+
)
|
| 99 |
+
)
|
| 100 |
+
if len(checkpoints) == 0:
|
| 101 |
+
raise ValueError(f"No checkpoints found in {self.config.resume_from}")
|
| 102 |
+
checkpoint_numbers = sorted([int(x.split("_")[-1]) for x in checkpoints])
|
| 103 |
+
self.config.resume_from = os.path.join(
|
| 104 |
+
self.config.resume_from,
|
| 105 |
+
f"checkpoint_{checkpoint_numbers[-1]}",
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
accelerator_project_config.iteration = checkpoint_numbers[-1] + 1
|
| 109 |
+
|
| 110 |
+
# number of timesteps within each trajectory to train on
|
| 111 |
+
self.num_train_timesteps = int(self.config.sample_num_steps * self.config.train_timestep_fraction)
|
| 112 |
+
|
| 113 |
+
self.accelerator = Accelerator(
|
| 114 |
+
log_with=self.config.log_with,
|
| 115 |
+
mixed_precision=self.config.mixed_precision,
|
| 116 |
+
project_config=accelerator_project_config,
|
| 117 |
+
# we always accumulate gradients across timesteps; we want config.train.gradient_accumulation_steps to be the
|
| 118 |
+
# number of *samples* we accumulate across, so we need to multiply by the number of training timesteps to get
|
| 119 |
+
# the total number of optimizer steps to accumulate across.
|
| 120 |
+
gradient_accumulation_steps=self.config.train_gradient_accumulation_steps * self.num_train_timesteps,
|
| 121 |
+
**self.config.accelerator_kwargs,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
is_okay, message = self._config_check()
|
| 125 |
+
if not is_okay:
|
| 126 |
+
raise ValueError(message)
|
| 127 |
+
|
| 128 |
+
is_using_tensorboard = config.log_with is not None and config.log_with == "tensorboard"
|
| 129 |
+
|
| 130 |
+
if self.accelerator.is_main_process:
|
| 131 |
+
self.accelerator.init_trackers(
|
| 132 |
+
self.config.tracker_project_name,
|
| 133 |
+
config=dict(ddpo_trainer_config=config.to_dict()) if not is_using_tensorboard else config.to_dict(),
|
| 134 |
+
init_kwargs=self.config.tracker_kwargs,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
logger.info(f"\n{config}")
|
| 138 |
+
|
| 139 |
+
set_seed(self.config.seed, device_specific=True)
|
| 140 |
+
|
| 141 |
+
self.sd_pipeline = sd_pipeline
|
| 142 |
+
|
| 143 |
+
self.sd_pipeline.set_progress_bar_config(
|
| 144 |
+
position=1,
|
| 145 |
+
disable=not self.accelerator.is_local_main_process,
|
| 146 |
+
leave=False,
|
| 147 |
+
desc="Timestep",
|
| 148 |
+
dynamic_ncols=True,
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
# For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
|
| 152 |
+
# as these weights are only used for inference, keeping weights in full precision is not required.
|
| 153 |
+
if self.accelerator.mixed_precision == "fp16":
|
| 154 |
+
inference_dtype = torch.float16
|
| 155 |
+
elif self.accelerator.mixed_precision == "bf16":
|
| 156 |
+
inference_dtype = torch.bfloat16
|
| 157 |
+
else:
|
| 158 |
+
inference_dtype = torch.float32
|
| 159 |
+
|
| 160 |
+
self.sd_pipeline.vae.to(self.accelerator.device, dtype=inference_dtype)
|
| 161 |
+
self.sd_pipeline.text_encoder.to(self.accelerator.device, dtype=inference_dtype)
|
| 162 |
+
self.sd_pipeline.unet.to(self.accelerator.device, dtype=inference_dtype)
|
| 163 |
+
|
| 164 |
+
trainable_layers = self.sd_pipeline.get_trainable_layers()
|
| 165 |
+
|
| 166 |
+
self.accelerator.register_save_state_pre_hook(self._save_model_hook)
|
| 167 |
+
self.accelerator.register_load_state_pre_hook(self._load_model_hook)
|
| 168 |
+
|
| 169 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 170 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 171 |
+
if self.config.allow_tf32:
|
| 172 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 173 |
+
|
| 174 |
+
self.optimizer = self._setup_optimizer(trainable_layers.parameters() if not isinstance(trainable_layers, list) else trainable_layers)
|
| 175 |
+
|
| 176 |
+
self.neg_prompt_embed = self.sd_pipeline.text_encoder(
|
| 177 |
+
self.sd_pipeline.tokenizer(
|
| 178 |
+
[""] if self.config.negative_prompts is None else self.config.negative_prompts,
|
| 179 |
+
return_tensors="pt",
|
| 180 |
+
padding="max_length",
|
| 181 |
+
truncation=True,
|
| 182 |
+
max_length=self.sd_pipeline.tokenizer.model_max_length,
|
| 183 |
+
).input_ids.to(self.accelerator.device)
|
| 184 |
+
)[0]
|
| 185 |
+
|
| 186 |
+
if config.per_prompt_stat_tracking:
|
| 187 |
+
self.stat_tracker = PerPromptStatTracker(
|
| 188 |
+
config.per_prompt_stat_tracking_buffer_size,
|
| 189 |
+
config.per_prompt_stat_tracking_min_count,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
# NOTE: for some reason, autocast is necessary for non-lora training but for lora training it isn't necessary and it uses
|
| 193 |
+
# more memory
|
| 194 |
+
self.autocast = self.sd_pipeline.autocast or self.accelerator.autocast
|
| 195 |
+
|
| 196 |
+
if hasattr(self.sd_pipeline, "use_lora") and self.sd_pipeline.use_lora:
|
| 197 |
+
unet, self.optimizer = self.accelerator.prepare(trainable_layers, self.optimizer)
|
| 198 |
+
self.trainable_layers = list(filter(lambda p: p.requires_grad, unet.parameters()))
|
| 199 |
+
else:
|
| 200 |
+
self.trainable_layers, self.optimizer = self.accelerator.prepare(trainable_layers, self.optimizer)
|
| 201 |
+
|
| 202 |
+
if self.config.async_reward_computation:
|
| 203 |
+
self.executor = futures.ThreadPoolExecutor(max_workers=config.max_workers)
|
| 204 |
+
|
| 205 |
+
if config.resume_from:
|
| 206 |
+
logger.info(f"Resuming from {config.resume_from}")
|
| 207 |
+
self.accelerator.load_state(config.resume_from)
|
| 208 |
+
self.first_epoch = int(config.resume_from.split("_")[-1]) + 1
|
| 209 |
+
else:
|
| 210 |
+
self.first_epoch = 0
|
| 211 |
+
|
| 212 |
+
def compute_rewards(self, prompt_image_pairs, is_async=False):
|
| 213 |
+
if not is_async:
|
| 214 |
+
rewards = []
|
| 215 |
+
for images, prompts, prompt_metadata in prompt_image_pairs:
|
| 216 |
+
reward, reward_metadata = self.reward_fn(images, prompts, prompt_metadata)
|
| 217 |
+
rewards.append(
|
| 218 |
+
(
|
| 219 |
+
torch.as_tensor(reward, device=self.accelerator.device),
|
| 220 |
+
reward_metadata,
|
| 221 |
+
)
|
| 222 |
+
)
|
| 223 |
+
else:
|
| 224 |
+
rewards = self.executor.map(lambda x: self.reward_fn(*x), prompt_image_pairs)
|
| 225 |
+
rewards = [(torch.as_tensor(reward.result(), device=self.accelerator.device), reward_metadata.result()) for reward, reward_metadata in rewards]
|
| 226 |
+
|
| 227 |
+
return zip(*rewards)
|
| 228 |
+
|
| 229 |
+
def step(self, epoch: int, global_step: int):
|
| 230 |
+
"""
|
| 231 |
+
Perform a single step of training.
|
| 232 |
+
|
| 233 |
+
Args:
|
| 234 |
+
epoch (int): The current epoch.
|
| 235 |
+
global_step (int): The current global step.
|
| 236 |
+
|
| 237 |
+
Side Effects:
|
| 238 |
+
- Model weights are updated
|
| 239 |
+
- Logs the statistics to the accelerator trackers.
|
| 240 |
+
- If `self.image_samples_callback` is not None, it will be called with the prompt_image_pairs, global_step, and the accelerator tracker.
|
| 241 |
+
|
| 242 |
+
Returns:
|
| 243 |
+
global_step (int): The updated global step.
|
| 244 |
+
|
| 245 |
+
"""
|
| 246 |
+
samples, prompt_image_data = self._generate_samples(
|
| 247 |
+
iterations=self.config.sample_num_batches_per_epoch,
|
| 248 |
+
batch_size=self.config.sample_batch_size,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
# collate samples into dict where each entry has shape (num_batches_per_epoch * sample.batch_size, ...)
|
| 252 |
+
samples = {k: torch.cat([s[k] for s in samples]) for k in samples[0].keys()}
|
| 253 |
+
rewards, rewards_metadata = self.compute_rewards(prompt_image_data, is_async=self.config.async_reward_computation)
|
| 254 |
+
|
| 255 |
+
for i, image_data in enumerate(prompt_image_data):
|
| 256 |
+
image_data.extend([rewards[i], rewards_metadata[i]])
|
| 257 |
+
|
| 258 |
+
if self.image_samples_callback is not None:
|
| 259 |
+
self.image_samples_callback(prompt_image_data, global_step, self.accelerator.trackers[0])
|
| 260 |
+
|
| 261 |
+
rewards = torch.cat(rewards)
|
| 262 |
+
rewards = self.accelerator.gather(rewards).cpu().numpy()
|
| 263 |
+
|
| 264 |
+
self.accelerator.log(
|
| 265 |
+
{
|
| 266 |
+
"reward": rewards,
|
| 267 |
+
"epoch": epoch,
|
| 268 |
+
"reward_mean": rewards.mean(),
|
| 269 |
+
"reward_std": rewards.std(),
|
| 270 |
+
},
|
| 271 |
+
step=global_step,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
if self.config.per_prompt_stat_tracking:
|
| 275 |
+
# gather the prompts across processes
|
| 276 |
+
prompt_ids = self.accelerator.gather(samples["prompt_ids"]).cpu().numpy()
|
| 277 |
+
prompts = self.sd_pipeline.tokenizer.batch_decode(prompt_ids, skip_special_tokens=True)
|
| 278 |
+
advantages = self.stat_tracker.update(prompts, rewards)
|
| 279 |
+
else:
|
| 280 |
+
advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-8)
|
| 281 |
+
|
| 282 |
+
# ungather advantages; keep the entries corresponding to the samples on this process
|
| 283 |
+
samples["advantages"] = torch.as_tensor(advantages).reshape(self.accelerator.num_processes, -1)[self.accelerator.process_index].to(self.accelerator.device)
|
| 284 |
+
|
| 285 |
+
del samples["prompt_ids"]
|
| 286 |
+
|
| 287 |
+
total_batch_size, num_timesteps = samples["timesteps"].shape
|
| 288 |
+
|
| 289 |
+
for inner_epoch in range(self.config.train_num_inner_epochs):
|
| 290 |
+
# shuffle samples along batch dimension
|
| 291 |
+
perm = torch.randperm(total_batch_size, device=self.accelerator.device)
|
| 292 |
+
samples = {k: v[perm] for k, v in samples.items()}
|
| 293 |
+
|
| 294 |
+
# shuffle along time dimension independently for each sample
|
| 295 |
+
# still trying to understand the code below
|
| 296 |
+
perms = torch.stack([torch.randperm(num_timesteps, device=self.accelerator.device) for _ in range(total_batch_size)])
|
| 297 |
+
|
| 298 |
+
for key in ["timesteps", "latents", "next_latents", "log_probs"]:
|
| 299 |
+
samples[key] = samples[key][
|
| 300 |
+
torch.arange(total_batch_size, device=self.accelerator.device)[:, None],
|
| 301 |
+
perms,
|
| 302 |
+
]
|
| 303 |
+
|
| 304 |
+
original_keys = samples.keys()
|
| 305 |
+
original_values = samples.values()
|
| 306 |
+
# rebatch them as user defined train_batch_size is different from sample_batch_size
|
| 307 |
+
reshaped_values = [v.reshape(-1, self.config.train_batch_size, *v.shape[1:]) for v in original_values]
|
| 308 |
+
|
| 309 |
+
# Transpose the list of original values
|
| 310 |
+
transposed_values = zip(*reshaped_values)
|
| 311 |
+
# Create new dictionaries for each row of transposed values
|
| 312 |
+
samples_batched = [dict(zip(original_keys, row_values)) for row_values in transposed_values]
|
| 313 |
+
|
| 314 |
+
self.sd_pipeline.unet.train()
|
| 315 |
+
global_step = self._train_batched_samples(inner_epoch, epoch, global_step, samples_batched)
|
| 316 |
+
# ensure optimization step at the end of the inner epoch
|
| 317 |
+
if not self.accelerator.sync_gradients:
|
| 318 |
+
raise ValueError("Optimization step should have been performed by this point. Please check calculated gradient accumulation settings.")
|
| 319 |
+
|
| 320 |
+
if epoch != 0 and epoch % self.config.save_freq == 0 and self.accelerator.is_main_process:
|
| 321 |
+
self.accelerator.save_state()
|
| 322 |
+
|
| 323 |
+
return global_step
|
| 324 |
+
|
| 325 |
+
def calculate_loss(self, latents, timesteps, next_latents, log_probs, advantages, embeds):
|
| 326 |
+
"""
|
| 327 |
+
Calculate the loss for a batch of an unpacked sample
|
| 328 |
+
|
| 329 |
+
Args:
|
| 330 |
+
latents (torch.Tensor):
|
| 331 |
+
The latents sampled from the diffusion model, shape: [batch_size, num_channels_latents, height, width]
|
| 332 |
+
timesteps (torch.Tensor):
|
| 333 |
+
The timesteps sampled from the diffusion model, shape: [batch_size]
|
| 334 |
+
next_latents (torch.Tensor):
|
| 335 |
+
The next latents sampled from the diffusion model, shape: [batch_size, num_channels_latents, height, width]
|
| 336 |
+
log_probs (torch.Tensor):
|
| 337 |
+
The log probabilities of the latents, shape: [batch_size]
|
| 338 |
+
advantages (torch.Tensor):
|
| 339 |
+
The advantages of the latents, shape: [batch_size]
|
| 340 |
+
embeds (torch.Tensor):
|
| 341 |
+
The embeddings of the prompts, shape: [2*batch_size or batch_size, ...]
|
| 342 |
+
Note: the "or" is because if train_cfg is True, the expectation is that negative prompts are concatenated to the embeds
|
| 343 |
+
|
| 344 |
+
Returns:
|
| 345 |
+
loss (torch.Tensor), approx_kl (torch.Tensor), clipfrac (torch.Tensor)
|
| 346 |
+
(all of these are of shape (1,))
|
| 347 |
+
"""
|
| 348 |
+
with self.autocast():
|
| 349 |
+
if self.config.train_cfg:
|
| 350 |
+
noise_pred = self.sd_pipeline.unet(
|
| 351 |
+
torch.cat([latents] * 2),
|
| 352 |
+
torch.cat([timesteps] * 2),
|
| 353 |
+
embeds,
|
| 354 |
+
).sample
|
| 355 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 356 |
+
noise_pred = noise_pred_uncond + self.config.sample_guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 357 |
+
else:
|
| 358 |
+
noise_pred = self.sd_pipeline.unet(
|
| 359 |
+
latents,
|
| 360 |
+
timesteps,
|
| 361 |
+
embeds,
|
| 362 |
+
).sample
|
| 363 |
+
# compute the log prob of next_latents given latents under the current model
|
| 364 |
+
|
| 365 |
+
scheduler_step_output = self.sd_pipeline.scheduler_step(
|
| 366 |
+
noise_pred,
|
| 367 |
+
timesteps,
|
| 368 |
+
latents,
|
| 369 |
+
eta=self.config.sample_eta,
|
| 370 |
+
prev_sample=next_latents,
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
log_prob = scheduler_step_output.log_probs
|
| 374 |
+
|
| 375 |
+
advantages = torch.clamp(
|
| 376 |
+
advantages,
|
| 377 |
+
-self.config.train_adv_clip_max,
|
| 378 |
+
self.config.train_adv_clip_max,
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
ratio = torch.exp(log_prob - log_probs)
|
| 382 |
+
|
| 383 |
+
loss = self.loss(advantages, self.config.train_clip_range, ratio)
|
| 384 |
+
|
| 385 |
+
approx_kl = 0.5 * torch.mean((log_prob - log_probs) ** 2)
|
| 386 |
+
|
| 387 |
+
clipfrac = torch.mean((torch.abs(ratio - 1.0) > self.config.train_clip_range).float())
|
| 388 |
+
|
| 389 |
+
return loss, approx_kl, clipfrac
|
| 390 |
+
|
| 391 |
+
def loss(
|
| 392 |
+
self,
|
| 393 |
+
advantages: torch.Tensor,
|
| 394 |
+
clip_range: float,
|
| 395 |
+
ratio: torch.Tensor,
|
| 396 |
+
):
|
| 397 |
+
unclipped_loss = -advantages * ratio
|
| 398 |
+
clipped_loss = -advantages * torch.clamp(
|
| 399 |
+
ratio,
|
| 400 |
+
1.0 - clip_range,
|
| 401 |
+
1.0 + clip_range,
|
| 402 |
+
)
|
| 403 |
+
return torch.mean(torch.maximum(unclipped_loss, clipped_loss))
|
| 404 |
+
|
| 405 |
+
def _setup_optimizer(self, trainable_layers_parameters):
|
| 406 |
+
if self.config.train_use_8bit_adam:
|
| 407 |
+
import bitsandbytes
|
| 408 |
+
|
| 409 |
+
optimizer_cls = bitsandbytes.optim.AdamW8bit
|
| 410 |
+
else:
|
| 411 |
+
optimizer_cls = torch.optim.AdamW
|
| 412 |
+
|
| 413 |
+
return optimizer_cls(
|
| 414 |
+
trainable_layers_parameters,
|
| 415 |
+
lr=self.config.train_learning_rate,
|
| 416 |
+
betas=(self.config.train_adam_beta1, self.config.train_adam_beta2),
|
| 417 |
+
weight_decay=self.config.train_adam_weight_decay,
|
| 418 |
+
eps=self.config.train_adam_epsilon,
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
def _save_model_hook(self, models, weights, output_dir):
|
| 422 |
+
self.sd_pipeline.save_checkpoint(models, weights, output_dir)
|
| 423 |
+
weights.pop() # ensures that accelerate doesn't try to handle saving of the model
|
| 424 |
+
|
| 425 |
+
def _load_model_hook(self, models, input_dir):
|
| 426 |
+
self.sd_pipeline.load_checkpoint(models, input_dir)
|
| 427 |
+
models.pop() # ensures that accelerate doesn't try to handle loading of the model
|
| 428 |
+
|
| 429 |
+
def _generate_samples(self, iterations, batch_size):
|
| 430 |
+
"""
|
| 431 |
+
Generate samples from the model
|
| 432 |
+
|
| 433 |
+
Args:
|
| 434 |
+
iterations (int): Number of iterations to generate samples for
|
| 435 |
+
batch_size (int): Batch size to use for sampling
|
| 436 |
+
|
| 437 |
+
Returns:
|
| 438 |
+
samples (List[Dict[str, torch.Tensor]]), prompt_image_pairs (List[List[Any]])
|
| 439 |
+
"""
|
| 440 |
+
samples = []
|
| 441 |
+
prompt_image_pairs = []
|
| 442 |
+
self.sd_pipeline.unet.eval()
|
| 443 |
+
|
| 444 |
+
sample_neg_prompt_embeds = self.neg_prompt_embed.repeat(batch_size, 1, 1)
|
| 445 |
+
|
| 446 |
+
for _ in range(iterations):
|
| 447 |
+
prompts, prompt_metadata = zip(*[self.prompt_fn() for _ in range(batch_size)])
|
| 448 |
+
|
| 449 |
+
prompt_ids = self.sd_pipeline.tokenizer(
|
| 450 |
+
prompts,
|
| 451 |
+
return_tensors="pt",
|
| 452 |
+
padding="max_length",
|
| 453 |
+
truncation=True,
|
| 454 |
+
max_length=self.sd_pipeline.tokenizer.model_max_length,
|
| 455 |
+
).input_ids.to(self.accelerator.device)
|
| 456 |
+
prompt_embeds = self.sd_pipeline.text_encoder(prompt_ids)[0]
|
| 457 |
+
|
| 458 |
+
with self.autocast():
|
| 459 |
+
sd_output = self.sd_pipeline(
|
| 460 |
+
prompt_embeds=prompt_embeds,
|
| 461 |
+
negative_prompt_embeds=sample_neg_prompt_embeds,
|
| 462 |
+
num_inference_steps=self.config.sample_num_steps,
|
| 463 |
+
guidance_scale=self.config.sample_guidance_scale,
|
| 464 |
+
eta=self.config.sample_eta,
|
| 465 |
+
output_type="pt",
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
images = sd_output.images
|
| 469 |
+
latents = sd_output.latents
|
| 470 |
+
log_probs = sd_output.log_probs
|
| 471 |
+
|
| 472 |
+
latents = torch.stack(latents, dim=1) # (batch_size, num_steps + 1, ...)
|
| 473 |
+
log_probs = torch.stack(log_probs, dim=1) # (batch_size, num_steps, 1)
|
| 474 |
+
timesteps = self.sd_pipeline.scheduler.timesteps.repeat(batch_size, 1) # (batch_size, num_steps)
|
| 475 |
+
|
| 476 |
+
samples.append(
|
| 477 |
+
{
|
| 478 |
+
"prompt_ids": prompt_ids,
|
| 479 |
+
"prompt_embeds": prompt_embeds,
|
| 480 |
+
"timesteps": timesteps,
|
| 481 |
+
"latents": latents[:, :-1], # each entry is the latent before timestep t
|
| 482 |
+
"next_latents": latents[:, 1:], # each entry is the latent after timestep t
|
| 483 |
+
"log_probs": log_probs,
|
| 484 |
+
"negative_prompt_embeds": sample_neg_prompt_embeds,
|
| 485 |
+
}
|
| 486 |
+
)
|
| 487 |
+
prompt_image_pairs.append([images, prompts, prompt_metadata])
|
| 488 |
+
|
| 489 |
+
return samples, prompt_image_pairs
|
| 490 |
+
|
| 491 |
+
def _train_batched_samples(self, inner_epoch, epoch, global_step, batched_samples):
|
| 492 |
+
"""
|
| 493 |
+
Train on a batch of samples. Main training segment
|
| 494 |
+
|
| 495 |
+
Args:
|
| 496 |
+
inner_epoch (int): The current inner epoch
|
| 497 |
+
epoch (int): The current epoch
|
| 498 |
+
global_step (int): The current global step
|
| 499 |
+
batched_samples (List[Dict[str, torch.Tensor]]): The batched samples to train on
|
| 500 |
+
|
| 501 |
+
Side Effects:
|
| 502 |
+
- Model weights are updated
|
| 503 |
+
- Logs the statistics to the accelerator trackers.
|
| 504 |
+
|
| 505 |
+
Returns:
|
| 506 |
+
global_step (int): The updated global step
|
| 507 |
+
"""
|
| 508 |
+
info = defaultdict(list)
|
| 509 |
+
for i, sample in enumerate(batched_samples):
|
| 510 |
+
if self.config.train_cfg:
|
| 511 |
+
# concat negative prompts to sample prompts to avoid two forward passes
|
| 512 |
+
embeds = torch.cat([sample["negative_prompt_embeds"], sample["prompt_embeds"]])
|
| 513 |
+
else:
|
| 514 |
+
embeds = sample["prompt_embeds"]
|
| 515 |
+
|
| 516 |
+
for j in range(self.num_train_timesteps):
|
| 517 |
+
with self.accelerator.accumulate(self.sd_pipeline.unet):
|
| 518 |
+
loss, approx_kl, clipfrac = self.calculate_loss(
|
| 519 |
+
sample["latents"][:, j],
|
| 520 |
+
sample["timesteps"][:, j],
|
| 521 |
+
sample["next_latents"][:, j],
|
| 522 |
+
sample["log_probs"][:, j],
|
| 523 |
+
sample["advantages"],
|
| 524 |
+
embeds,
|
| 525 |
+
)
|
| 526 |
+
info["approx_kl"].append(approx_kl)
|
| 527 |
+
info["clipfrac"].append(clipfrac)
|
| 528 |
+
info["loss"].append(loss)
|
| 529 |
+
|
| 530 |
+
self.accelerator.backward(loss)
|
| 531 |
+
if self.accelerator.sync_gradients:
|
| 532 |
+
self.accelerator.clip_grad_norm_(
|
| 533 |
+
self.trainable_layers.parameters() if not isinstance(self.trainable_layers, list) else self.trainable_layers,
|
| 534 |
+
self.config.train_max_grad_norm,
|
| 535 |
+
)
|
| 536 |
+
self.optimizer.step()
|
| 537 |
+
self.optimizer.zero_grad()
|
| 538 |
+
|
| 539 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 540 |
+
if self.accelerator.sync_gradients:
|
| 541 |
+
# log training-related stuff
|
| 542 |
+
info = {k: torch.mean(torch.stack(v)) for k, v in info.items()}
|
| 543 |
+
info = self.accelerator.reduce(info, reduction="mean")
|
| 544 |
+
info.update({"epoch": epoch, "inner_epoch": inner_epoch})
|
| 545 |
+
self.accelerator.log(info, step=global_step)
|
| 546 |
+
global_step += 1
|
| 547 |
+
info = defaultdict(list)
|
| 548 |
+
return global_step
|
| 549 |
+
|
| 550 |
+
def _config_check(self) -> Tuple[bool, str]:
|
| 551 |
+
samples_per_epoch = self.config.sample_batch_size * self.accelerator.num_processes * self.config.sample_num_batches_per_epoch
|
| 552 |
+
total_train_batch_size = self.config.train_batch_size * self.accelerator.num_processes * self.config.train_gradient_accumulation_steps
|
| 553 |
+
|
| 554 |
+
if not self.config.sample_batch_size >= self.config.train_batch_size:
|
| 555 |
+
return (
|
| 556 |
+
False,
|
| 557 |
+
f"Sample batch size ({self.config.sample_batch_size}) must be greater than or equal to the train batch size ({self.config.train_batch_size})",
|
| 558 |
+
)
|
| 559 |
+
if not self.config.sample_batch_size % self.config.train_batch_size == 0:
|
| 560 |
+
return (
|
| 561 |
+
False,
|
| 562 |
+
f"Sample batch size ({self.config.sample_batch_size}) must be divisible by the train batch size ({self.config.train_batch_size})",
|
| 563 |
+
)
|
| 564 |
+
if not samples_per_epoch % total_train_batch_size == 0:
|
| 565 |
+
return (
|
| 566 |
+
False,
|
| 567 |
+
f"Number of samples per epoch ({samples_per_epoch}) must be divisible by the total train batch size ({total_train_batch_size})",
|
| 568 |
+
)
|
| 569 |
+
return True, ""
|
| 570 |
+
|
| 571 |
+
def train(self, epochs: Optional[int] = None):
|
| 572 |
+
"""
|
| 573 |
+
Train the model for a given number of epochs
|
| 574 |
+
"""
|
| 575 |
+
global_step = 0
|
| 576 |
+
if epochs is None:
|
| 577 |
+
epochs = self.config.num_epochs
|
| 578 |
+
for epoch in range(self.first_epoch, epochs):
|
| 579 |
+
global_step = self.step(epoch, global_step)
|
| 580 |
+
|
| 581 |
+
def create_model_card(self, path: str, model_name: Optional[str] = "TRL DDPO Model") -> None:
|
| 582 |
+
"""Creates and saves a model card for a TRL model.
|
| 583 |
+
|
| 584 |
+
Args:
|
| 585 |
+
path (`str`): The path to save the model card to.
|
| 586 |
+
model_name (`str`, *optional*): The name of the model, defaults to `TRL DDPO Model`.
|
| 587 |
+
"""
|
| 588 |
+
try:
|
| 589 |
+
user = whoami()["name"]
|
| 590 |
+
# handle the offline case
|
| 591 |
+
except: # noqa
|
| 592 |
+
warnings.warn("Cannot retrieve user information assuming you are running in offline mode.")
|
| 593 |
+
return
|
| 594 |
+
|
| 595 |
+
if not os.path.exists(path):
|
| 596 |
+
os.makedirs(path)
|
| 597 |
+
|
| 598 |
+
model_card_content = MODEL_CARD_TEMPLATE.format(model_name=model_name, model_id=f"{user}/{path}")
|
| 599 |
+
with open(os.path.join(path, "README.md"), "w", encoding="utf-8") as f:
|
| 600 |
+
f.write(model_card_content)
|
| 601 |
+
|
| 602 |
+
def _save_pretrained(self, save_directory):
|
| 603 |
+
self.sd_pipeline.save_pretrained(save_directory)
|
| 604 |
+
self.create_model_card(save_directory)
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/dpo_trainer.py
ADDED
|
@@ -0,0 +1,1186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DPO Authors: Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D. Manning, and Chelsea Finn 2023
|
| 2 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
import inspect
|
| 16 |
+
import random
|
| 17 |
+
import warnings
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
from contextlib import contextmanager, nullcontext
|
| 20 |
+
from copy import deepcopy
|
| 21 |
+
from functools import wraps
|
| 22 |
+
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from accelerate import PartialState
|
| 29 |
+
from accelerate.utils import is_deepspeed_available, tqdm
|
| 30 |
+
from datasets import Dataset
|
| 31 |
+
from torch.utils.data import DataLoader
|
| 32 |
+
from transformers import (
|
| 33 |
+
AutoModelForCausalLM,
|
| 34 |
+
DataCollator,
|
| 35 |
+
PreTrainedModel,
|
| 36 |
+
PreTrainedTokenizerBase,
|
| 37 |
+
Trainer,
|
| 38 |
+
TrainingArguments,
|
| 39 |
+
)
|
| 40 |
+
from transformers.trainer_callback import TrainerCallback
|
| 41 |
+
from transformers.trainer_utils import EvalLoopOutput
|
| 42 |
+
|
| 43 |
+
from ..import_utils import is_peft_available, is_wandb_available
|
| 44 |
+
from ..models import PreTrainedModelWrapper, create_reference_model
|
| 45 |
+
from .utils import (
|
| 46 |
+
DPODataCollatorWithPadding,
|
| 47 |
+
disable_dropout_in_model,
|
| 48 |
+
pad_to_length,
|
| 49 |
+
peft_module_casting_to_bf16,
|
| 50 |
+
trl_sanitze_kwargs_for_tagging,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
if is_peft_available():
|
| 55 |
+
from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
if is_wandb_available():
|
| 59 |
+
import wandb
|
| 60 |
+
|
| 61 |
+
if is_deepspeed_available():
|
| 62 |
+
import deepspeed
|
| 63 |
+
|
| 64 |
+
from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class DPOTrainer(Trainer):
|
| 68 |
+
r"""
|
| 69 |
+
Initialize DPOTrainer.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
model (`transformers.PreTrainedModel`):
|
| 73 |
+
The model to train, preferably an `AutoModelForSequenceClassification`.
|
| 74 |
+
ref_model (`PreTrainedModelWrapper`):
|
| 75 |
+
Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no
|
| 76 |
+
reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized.
|
| 77 |
+
beta (`float`, defaults to 0.1):
|
| 78 |
+
The beta factor in DPO loss. Higher beta means less divergence from the initial policy. For the IPO loss, beta is the regularization parameter denoted by tau in the paper.
|
| 79 |
+
label_smoothing (`float`, defaults to 0):
|
| 80 |
+
The robust DPO label smoothing parameter from the [cDPO](https://ericmitchell.ai/cdpo.pdf) report that should be between 0 and 0.5.
|
| 81 |
+
loss_type (`str`, defaults to `"sigmoid"`):
|
| 82 |
+
The type of DPO loss to use. Either `"sigmoid"` the default DPO loss,`"hinge"` loss from [SLiC](https://arxiv.org/abs/2305.10425) paper, `"ipo"` from [IPO](https://arxiv.org/abs/2310.12036) paper, or `"kto"` from the HALOs [report](https://github.com/ContextualAI/HALOs/blob/main/assets/report.pdf).
|
| 83 |
+
args (`transformers.TrainingArguments`):
|
| 84 |
+
The arguments to use for training.
|
| 85 |
+
data_collator (`transformers.DataCollator`):
|
| 86 |
+
The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used
|
| 87 |
+
which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences.
|
| 88 |
+
label_pad_token_id (`int`, defaults to `-100`):
|
| 89 |
+
The label pad token id. This argument is required if you want to use the default data collator.
|
| 90 |
+
padding_value (`int`, defaults to `0`):
|
| 91 |
+
The padding value if it is different to the tokenizer's pad_token_id.
|
| 92 |
+
truncation_mode (`str`, defaults to `keep_end`):
|
| 93 |
+
The truncation mode to use, either `keep_end` or `keep_start`. This argument is required if you want to use the default data collator.
|
| 94 |
+
train_dataset (`datasets.Dataset`):
|
| 95 |
+
The dataset to use for training.
|
| 96 |
+
eval_dataset (`datasets.Dataset`):
|
| 97 |
+
The dataset to use for evaluation.
|
| 98 |
+
tokenizer (`transformers.PreTrainedTokenizerBase`):
|
| 99 |
+
The tokenizer to use for training. This argument is required if you want to use the default data collator.
|
| 100 |
+
model_init (`Callable[[], transformers.PreTrainedModel]`):
|
| 101 |
+
The model initializer to use for training. If None is specified, the default model initializer will be used.
|
| 102 |
+
callbacks (`List[transformers.TrainerCallback]`):
|
| 103 |
+
The callbacks to use for training.
|
| 104 |
+
optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
|
| 105 |
+
The optimizer and scheduler to use for training.
|
| 106 |
+
preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
|
| 107 |
+
The function to use to preprocess the logits before computing the metrics.
|
| 108 |
+
max_length (`int`, defaults to `None`):
|
| 109 |
+
The maximum length of the sequences in the batch. This argument is required if you want to use the default data collator.
|
| 110 |
+
max_prompt_length (`int`, defaults to `None`):
|
| 111 |
+
The maximum length of the prompt. This argument is required if you want to use the default data collator.
|
| 112 |
+
max_target_length (`int`, defaults to `None`):
|
| 113 |
+
The maximum length of the target. This argument is required if you want to use the default data collator and your model is an encoder-decoder.
|
| 114 |
+
peft_config (`Dict`, defaults to `None`):
|
| 115 |
+
The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model.
|
| 116 |
+
is_encoder_decoder (`Optional[bool]`, `optional`, defaults to `None`):
|
| 117 |
+
If no model is provided, we need to know if the model_init returns an encoder-decoder.
|
| 118 |
+
disable_dropout (`bool`, defaults to `True`):
|
| 119 |
+
Whether or not to disable dropouts in `model` and `ref_model`.
|
| 120 |
+
generate_during_eval (`bool`, defaults to `False`):
|
| 121 |
+
Whether to sample and log generations during evaluation step.
|
| 122 |
+
compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*):
|
| 123 |
+
The function to use to compute the metrics. Must take a `EvalPrediction` and return
|
| 124 |
+
a dictionary string to metric values.
|
| 125 |
+
precompute_ref_log_probs (`bool`, defaults to `False`):
|
| 126 |
+
Flag to precompute reference model log probabilities and evaluation datasets. This is useful if you want to train
|
| 127 |
+
without the reference model and reduce the total GPU memory needed.
|
| 128 |
+
dataset_num_proc (`Optional[int]`, *optional*):
|
| 129 |
+
The number of workers to use to tokenize the data. Defaults to None.
|
| 130 |
+
model_init_kwargs (`Optional[Dict]`, *optional*):
|
| 131 |
+
Dict of Optional kwargs to pass when instantiating the model from a string
|
| 132 |
+
ref_model_init_kwargs (`Optional[Dict]`, *optional*):
|
| 133 |
+
Dict of Optional kwargs to pass when instantiating the ref model from a string
|
| 134 |
+
model_adapter_name (`str`, defaults to `None`):
|
| 135 |
+
Name of the train target PEFT adapter, when using LoRA with multiple adapters.
|
| 136 |
+
ref_adapter_name (`str`, defaults to `None`):
|
| 137 |
+
Name of the reference PEFT adapter, when using LoRA with multiple adapters.
|
| 138 |
+
reference_free (`bool`):
|
| 139 |
+
If True, we ignore the _provided_ reference model and implicitly use a reference model that assigns equal probability to all responses.
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
_tag_names = ["trl", "dpo"]
|
| 143 |
+
|
| 144 |
+
def __init__(
|
| 145 |
+
self,
|
| 146 |
+
model: Optional[Union[PreTrainedModel, nn.Module, str]] = None,
|
| 147 |
+
ref_model: Optional[Union[PreTrainedModel, nn.Module, str]] = None,
|
| 148 |
+
dpo_alpha: float = 1.0,
|
| 149 |
+
beta: float = 0.1,
|
| 150 |
+
gamma: float = 0.1,
|
| 151 |
+
label_smoothing: float = 0,
|
| 152 |
+
loss_type: Literal["sigmoid", "hinge", "ipo", "kto_pair"] = "sigmoid",
|
| 153 |
+
args: Optional[TrainingArguments] = None,
|
| 154 |
+
data_collator: Optional[DataCollator] = None,
|
| 155 |
+
label_pad_token_id: int = -100,
|
| 156 |
+
padding_value: Optional[int] = None,
|
| 157 |
+
truncation_mode: str = "keep_end",
|
| 158 |
+
train_dataset: Optional[Dataset] = None,
|
| 159 |
+
eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None,
|
| 160 |
+
tokenizer: Optional[PreTrainedTokenizerBase] = None,
|
| 161 |
+
model_init: Optional[Callable[[], PreTrainedModel]] = None,
|
| 162 |
+
callbacks: Optional[List[TrainerCallback]] = None,
|
| 163 |
+
optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
|
| 164 |
+
preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
|
| 165 |
+
max_length: Optional[int] = None,
|
| 166 |
+
max_prompt_length: Optional[int] = None,
|
| 167 |
+
max_target_length: Optional[int] = None,
|
| 168 |
+
peft_config: Optional[Dict] = None,
|
| 169 |
+
is_encoder_decoder: Optional[bool] = None,
|
| 170 |
+
disable_dropout: bool = True,
|
| 171 |
+
generate_during_eval: bool = False,
|
| 172 |
+
compute_metrics: Optional[Callable[[EvalLoopOutput], Dict]] = None,
|
| 173 |
+
precompute_ref_log_probs: bool = False,
|
| 174 |
+
dataset_num_proc: Optional[int] = None,
|
| 175 |
+
model_init_kwargs: Optional[Dict] = None,
|
| 176 |
+
ref_model_init_kwargs: Optional[Dict] = None,
|
| 177 |
+
model_adapter_name: Optional[str] = None,
|
| 178 |
+
ref_adapter_name: Optional[str] = None,
|
| 179 |
+
reference_free: bool = False,
|
| 180 |
+
):
|
| 181 |
+
# import pdb;pdb.set_trace()
|
| 182 |
+
if model_init_kwargs is None:
|
| 183 |
+
model_init_kwargs = {}
|
| 184 |
+
elif not isinstance(model, str):
|
| 185 |
+
raise ValueError("You passed model_kwargs to the DPOTrainer. But your model is already instantiated.")
|
| 186 |
+
|
| 187 |
+
if ref_model_init_kwargs is None:
|
| 188 |
+
ref_model_init_kwargs = {}
|
| 189 |
+
elif not isinstance(ref_model, str):
|
| 190 |
+
raise ValueError("You passed ref_model_kwargs to the DPOTrainer. But your ref_model is already instantiated.")
|
| 191 |
+
|
| 192 |
+
if isinstance(model, str):
|
| 193 |
+
warnings.warn("You passed a model_id to the DPOTrainer. This will automatically create an " "`AutoModelForCausalLM` or a `PeftModel` (if you passed a `peft_config`) for you.")
|
| 194 |
+
model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs)
|
| 195 |
+
|
| 196 |
+
if isinstance(ref_model, str):
|
| 197 |
+
warnings.warn("You passed a ref model_id to the DPOTrainer. This will automatically create an " "`AutoModelForCausalLM`")
|
| 198 |
+
ref_model = AutoModelForCausalLM.from_pretrained(ref_model, **ref_model_init_kwargs)
|
| 199 |
+
|
| 200 |
+
# Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16`
|
| 201 |
+
# has been called in order to properly call autocast if needed.
|
| 202 |
+
self._peft_has_been_casted_to_bf16 = False
|
| 203 |
+
|
| 204 |
+
if generate_during_eval and not is_wandb_available():
|
| 205 |
+
raise ValueError("`generate_during_eval=True` requires Weights and Biases to be installed." " Please install `wandb` to resolve.")
|
| 206 |
+
|
| 207 |
+
if model is not None:
|
| 208 |
+
self.is_encoder_decoder = model.config.is_encoder_decoder
|
| 209 |
+
elif is_encoder_decoder is None:
|
| 210 |
+
raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.")
|
| 211 |
+
else:
|
| 212 |
+
self.is_encoder_decoder = is_encoder_decoder
|
| 213 |
+
|
| 214 |
+
self.is_peft_model = is_peft_available() and isinstance(model, PeftModel)
|
| 215 |
+
self.model_adapter_name = model_adapter_name
|
| 216 |
+
self.ref_adapter_name = ref_adapter_name
|
| 217 |
+
self.reference_free = reference_free
|
| 218 |
+
|
| 219 |
+
if ref_model:
|
| 220 |
+
self.ref_model = ref_model
|
| 221 |
+
elif self.is_peft_model or precompute_ref_log_probs:
|
| 222 |
+
# The `model` with adapters turned off will be used as the reference model
|
| 223 |
+
self.ref_model = None
|
| 224 |
+
else:
|
| 225 |
+
if is_deepspeed_zero3_enabled():
|
| 226 |
+
self.ref_model = AutoModelForCausalLM.from_pretrained(model)
|
| 227 |
+
else:
|
| 228 |
+
self.ref_model = create_reference_model(model)
|
| 229 |
+
|
| 230 |
+
if tokenizer is None:
|
| 231 |
+
raise ValueError("tokenizer must be specified to tokenize a DPO dataset.")
|
| 232 |
+
if max_length is None:
|
| 233 |
+
warnings.warn(
|
| 234 |
+
"`max_length` is not set in the DPOTrainer's init" " it will default to `512` by default, but you should do it yourself in the future.",
|
| 235 |
+
UserWarning,
|
| 236 |
+
)
|
| 237 |
+
max_length = 512
|
| 238 |
+
if max_prompt_length is None:
|
| 239 |
+
warnings.warn(
|
| 240 |
+
"`max_prompt_length` is not set in the DPOTrainer's init" " it will default to `128` by default, but you should do it yourself in the future.",
|
| 241 |
+
UserWarning,
|
| 242 |
+
)
|
| 243 |
+
max_prompt_length = 128
|
| 244 |
+
|
| 245 |
+
if max_target_length is None and self.is_encoder_decoder:
|
| 246 |
+
warnings.warn(
|
| 247 |
+
"When using an encoder decoder architecture, you should set `max_target_length` in the DPOTrainer's init" " it will default to `128` by default, but you should do it yourself in the future.",
|
| 248 |
+
UserWarning,
|
| 249 |
+
)
|
| 250 |
+
max_target_length = 128
|
| 251 |
+
|
| 252 |
+
if data_collator is None:
|
| 253 |
+
data_collator = DPODataCollatorWithPadding(
|
| 254 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 255 |
+
label_pad_token_id=label_pad_token_id,
|
| 256 |
+
is_encoder_decoder=self.is_encoder_decoder,
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
if args.remove_unused_columns:
|
| 260 |
+
args.remove_unused_columns = False
|
| 261 |
+
# warn users
|
| 262 |
+
warnings.warn(
|
| 263 |
+
"When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments" " we have set it for you, but you should do it yourself in the future.",
|
| 264 |
+
UserWarning,
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
self.use_dpo_data_collator = True
|
| 268 |
+
else:
|
| 269 |
+
self.use_dpo_data_collator = False
|
| 270 |
+
|
| 271 |
+
if disable_dropout:
|
| 272 |
+
disable_dropout_in_model(model)
|
| 273 |
+
if self.ref_model is not None:
|
| 274 |
+
disable_dropout_in_model(self.ref_model)
|
| 275 |
+
|
| 276 |
+
self.max_length = max_length
|
| 277 |
+
self.generate_during_eval = generate_during_eval
|
| 278 |
+
self.label_pad_token_id = label_pad_token_id
|
| 279 |
+
self.padding_value = padding_value if padding_value is not None else tokenizer.pad_token_id
|
| 280 |
+
self.max_prompt_length = max_prompt_length
|
| 281 |
+
self.truncation_mode = truncation_mode
|
| 282 |
+
self.max_target_length = max_target_length
|
| 283 |
+
self.tokenizer = tokenizer
|
| 284 |
+
self.precompute_ref_log_probs = precompute_ref_log_probs
|
| 285 |
+
|
| 286 |
+
# Since ref_logs are precomputed on the first call to get_train/eval_dataloader
|
| 287 |
+
# keep track of first called to avoid computation of future calls
|
| 288 |
+
self._precomputed_train_ref_log_probs = False
|
| 289 |
+
self._precomputed_eval_ref_log_probs = False
|
| 290 |
+
|
| 291 |
+
if loss_type in ["hinge", "ipo", "kto_pair"] and label_smoothing > 0:
|
| 292 |
+
warnings.warn("You are using a loss type that does not support label smoothing. Ignoring label_smoothing parameter.")
|
| 293 |
+
|
| 294 |
+
self.dpo_alpha = dpo_alpha
|
| 295 |
+
self.beta = beta
|
| 296 |
+
self.gamma = gamma
|
| 297 |
+
self.label_smoothing = label_smoothing
|
| 298 |
+
self.loss_type = loss_type
|
| 299 |
+
|
| 300 |
+
self._stored_metrics = defaultdict(lambda: defaultdict(list))
|
| 301 |
+
|
| 302 |
+
self.dataset_num_proc = dataset_num_proc
|
| 303 |
+
|
| 304 |
+
# Compute that only on the main process for faster data processing.
|
| 305 |
+
# see: https://github.com/huggingface/trl/pull/1255
|
| 306 |
+
# with PartialState().local_main_process_first():
|
| 307 |
+
# # tokenize the dataset
|
| 308 |
+
# train_dataset = train_dataset.map(self.tokenize_row, num_proc=self.dataset_num_proc)
|
| 309 |
+
# if eval_dataset is not None:
|
| 310 |
+
# eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=self.dataset_num_proc)
|
| 311 |
+
|
| 312 |
+
super().__init__(
|
| 313 |
+
model=model,
|
| 314 |
+
args=args,
|
| 315 |
+
data_collator=data_collator,
|
| 316 |
+
train_dataset=train_dataset,
|
| 317 |
+
eval_dataset=eval_dataset,
|
| 318 |
+
tokenizer=tokenizer,
|
| 319 |
+
model_init=model_init,
|
| 320 |
+
compute_metrics=compute_metrics,
|
| 321 |
+
callbacks=callbacks,
|
| 322 |
+
optimizers=optimizers,
|
| 323 |
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
if not hasattr(self, "accelerator"):
|
| 327 |
+
raise AttributeError("Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`.")
|
| 328 |
+
|
| 329 |
+
# Deepspeed Zero-3 does not support precompute_ref_log_probs
|
| 330 |
+
if self.is_deepspeed_enabled:
|
| 331 |
+
if self.accelerator.state.deepspeed_plugin.zero_stage == 3 and self.precompute_ref_log_probs:
|
| 332 |
+
raise ValueError("You cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`.")
|
| 333 |
+
|
| 334 |
+
if self.ref_model is None:
|
| 335 |
+
if not (self.is_peft_model or self.precompute_ref_log_probs):
|
| 336 |
+
raise ValueError("No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`")
|
| 337 |
+
else:
|
| 338 |
+
if self.is_deepspeed_enabled:
|
| 339 |
+
self.ref_model = self._prepare_deepspeed(self.ref_model)
|
| 340 |
+
else:
|
| 341 |
+
self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
|
| 342 |
+
|
| 343 |
+
def _prepare_deepspeed(self, model: PreTrainedModelWrapper):
|
| 344 |
+
# Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473
|
| 345 |
+
deepspeed_plugin = self.accelerator.state.deepspeed_plugin
|
| 346 |
+
config_kwargs = deepcopy(deepspeed_plugin.deepspeed_config)
|
| 347 |
+
|
| 348 |
+
if model is not None:
|
| 349 |
+
if hasattr(model, "config"):
|
| 350 |
+
hidden_size = max(model.config.hidden_sizes) if getattr(model.config, "hidden_sizes", None) else getattr(model.config, "hidden_size", None)
|
| 351 |
+
if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3:
|
| 352 |
+
# Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0`
|
| 353 |
+
# This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081
|
| 354 |
+
config_kwargs.update(
|
| 355 |
+
{
|
| 356 |
+
"zero_optimization.reduce_bucket_size": hidden_size * hidden_size,
|
| 357 |
+
"zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size,
|
| 358 |
+
"zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size,
|
| 359 |
+
}
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
# If ZeRO-3 is used, we shard both the active and reference model.
|
| 363 |
+
# Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO disabled (stage 0)
|
| 364 |
+
if config_kwargs["zero_optimization"]["stage"] != 3:
|
| 365 |
+
config_kwargs["zero_optimization"]["stage"] = 0
|
| 366 |
+
model, *_ = deepspeed.initialize(model=model, config=config_kwargs)
|
| 367 |
+
model.eval()
|
| 368 |
+
return model
|
| 369 |
+
|
| 370 |
+
def get_train_dataloader(self) -> DataLoader:
|
| 371 |
+
"""
|
| 372 |
+
Returns the training [`~torch.utils.data.DataLoader`].
|
| 373 |
+
|
| 374 |
+
Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`.
|
| 375 |
+
"""
|
| 376 |
+
|
| 377 |
+
if self.precompute_ref_log_probs and not self._precomputed_train_ref_log_probs:
|
| 378 |
+
dataloader_params = {
|
| 379 |
+
"batch_size": self.args.per_device_train_batch_size,
|
| 380 |
+
"collate_fn": self.data_collator,
|
| 381 |
+
"num_workers": self.args.dataloader_num_workers,
|
| 382 |
+
"pin_memory": self.args.dataloader_pin_memory,
|
| 383 |
+
"shuffle": False,
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
# prepare dataloader
|
| 387 |
+
data_loader = self.accelerator.prepare(DataLoader(self.train_dataset, **dataloader_params))
|
| 388 |
+
|
| 389 |
+
reference_chosen_logps = []
|
| 390 |
+
reference_rejected_logps = []
|
| 391 |
+
for padded_batch in tqdm(iterable=data_loader, desc="Train dataset reference log probs"):
|
| 392 |
+
reference_chosen_logp, reference_rejected_logp = self.compute_reference_log_probs(padded_batch)
|
| 393 |
+
reference_chosen_logp, reference_rejected_logp = self.accelerator.gather_for_metrics((reference_chosen_logp, reference_rejected_logp))
|
| 394 |
+
reference_chosen_logps.append(reference_chosen_logp.cpu())
|
| 395 |
+
reference_rejected_logps.append(reference_rejected_logp.cpu())
|
| 396 |
+
|
| 397 |
+
all_reference_chosen_logps = torch.cat(reference_chosen_logps).float().numpy()
|
| 398 |
+
all_reference_rejected_logps = torch.cat(reference_rejected_logps).float().numpy()
|
| 399 |
+
|
| 400 |
+
self.train_dataset = self.train_dataset.add_column(name="reference_chosen_logps", column=all_reference_chosen_logps)
|
| 401 |
+
self.train_dataset = self.train_dataset.add_column(name="reference_rejected_logps", column=all_reference_rejected_logps)
|
| 402 |
+
|
| 403 |
+
self._precomputed_train_ref_log_probs = True
|
| 404 |
+
|
| 405 |
+
return super().get_train_dataloader()
|
| 406 |
+
|
| 407 |
+
def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader:
|
| 408 |
+
"""
|
| 409 |
+
Returns the evaluation [`~torch.utils.data.DataLoader`].
|
| 410 |
+
|
| 411 |
+
Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`.
|
| 412 |
+
|
| 413 |
+
Args:
|
| 414 |
+
eval_dataset (`torch.utils.data.Dataset`, *optional*):
|
| 415 |
+
If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted
|
| 416 |
+
by the `model.forward()` method are automatically removed. It must implement `__len__`.
|
| 417 |
+
"""
|
| 418 |
+
if eval_dataset is None and self.eval_dataset is None:
|
| 419 |
+
raise ValueError("Trainer: evaluation requires an eval_dataset.")
|
| 420 |
+
eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset
|
| 421 |
+
|
| 422 |
+
if self.precompute_ref_log_probs and not self._precomputed_eval_ref_log_probs:
|
| 423 |
+
dataloader_params = {
|
| 424 |
+
"batch_size": self.args.per_device_eval_batch_size,
|
| 425 |
+
"collate_fn": self.data_collator,
|
| 426 |
+
"num_workers": self.args.dataloader_num_workers,
|
| 427 |
+
"pin_memory": self.args.dataloader_pin_memory,
|
| 428 |
+
"shuffle": False,
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
# prepare dataloader
|
| 432 |
+
data_loader = self.accelerator.prepare(DataLoader(eval_dataset, **dataloader_params))
|
| 433 |
+
|
| 434 |
+
reference_chosen_logps = []
|
| 435 |
+
reference_rejected_logps = []
|
| 436 |
+
for padded_batch in tqdm(iterable=data_loader, desc="Eval dataset reference log probs"):
|
| 437 |
+
reference_chosen_logp, reference_rejected_logp = self.compute_reference_log_probs(padded_batch)
|
| 438 |
+
reference_chosen_logp, reference_rejected_logp = self.accelerator.gather_for_metrics((reference_chosen_logp, reference_rejected_logp))
|
| 439 |
+
reference_chosen_logps.append(reference_chosen_logp.cpu())
|
| 440 |
+
reference_rejected_logps.append(reference_rejected_logp.cpu())
|
| 441 |
+
|
| 442 |
+
all_reference_chosen_logps = torch.cat(reference_chosen_logps).float().numpy()
|
| 443 |
+
all_reference_rejected_logps = torch.cat(reference_rejected_logps).float().numpy()
|
| 444 |
+
|
| 445 |
+
eval_dataset = eval_dataset.add_column(name="reference_chosen_logps", column=all_reference_chosen_logps)
|
| 446 |
+
eval_dataset = eval_dataset.add_column(name="reference_rejected_logps", column=all_reference_rejected_logps)
|
| 447 |
+
|
| 448 |
+
# Save calculated reference_chosen_logps and reference_rejected_logps to the eval_dataset for subsequent runs
|
| 449 |
+
if self.eval_dataset is not None:
|
| 450 |
+
self.eval_dataset = eval_dataset
|
| 451 |
+
self._precomputed_eval_ref_log_probs = True
|
| 452 |
+
|
| 453 |
+
return super().get_eval_dataloader(eval_dataset=eval_dataset)
|
| 454 |
+
|
| 455 |
+
def build_tokenized_answer(self, prompt, answer):
|
| 456 |
+
"""
|
| 457 |
+
Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`.
|
| 458 |
+
It does ensure `enc(a + b) = enc(a) + enc(a + b)[len(enc(a)):]`.
|
| 459 |
+
Reference:
|
| 460 |
+
https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
|
| 461 |
+
"""
|
| 462 |
+
|
| 463 |
+
full_tokenized = self.tokenizer(prompt + answer, add_special_tokens=False)
|
| 464 |
+
prompt_input_ids = self.tokenizer(prompt, add_special_tokens=False)["input_ids"]
|
| 465 |
+
|
| 466 |
+
answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :]
|
| 467 |
+
answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :]
|
| 468 |
+
|
| 469 |
+
# Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]`
|
| 470 |
+
full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids])
|
| 471 |
+
|
| 472 |
+
# Prepare input tokens for token by token comparison
|
| 473 |
+
full_input_ids = np.array(full_tokenized["input_ids"])
|
| 474 |
+
|
| 475 |
+
if len(full_input_ids) != len(full_concat_input_ids):
|
| 476 |
+
raise ValueError("Prompt input ids and answer input ids should have the same length.")
|
| 477 |
+
|
| 478 |
+
# On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens
|
| 479 |
+
# can be merged together when tokenizing prompt+answer. This could result
|
| 480 |
+
# on the last token from the prompt being different when tokenized on its own
|
| 481 |
+
# vs when done as prompt+answer.
|
| 482 |
+
response_token_ids_start_idx = len(prompt_input_ids)
|
| 483 |
+
|
| 484 |
+
# If tokenized prompt is different than both prompt+answer, then it means the
|
| 485 |
+
# last token has changed due to merging.
|
| 486 |
+
if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]:
|
| 487 |
+
response_token_ids_start_idx -= 1
|
| 488 |
+
|
| 489 |
+
prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx]
|
| 490 |
+
prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx]
|
| 491 |
+
|
| 492 |
+
if len(prompt_input_ids) != len(prompt_attention_mask):
|
| 493 |
+
raise ValueError("Prompt input ids and attention mask should have the same length.")
|
| 494 |
+
|
| 495 |
+
answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:]
|
| 496 |
+
answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:]
|
| 497 |
+
|
| 498 |
+
return dict(
|
| 499 |
+
prompt_input_ids=prompt_input_ids,
|
| 500 |
+
prompt_attention_mask=prompt_attention_mask,
|
| 501 |
+
input_ids=answer_input_ids,
|
| 502 |
+
attention_mask=answer_attention_mask,
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
def tokenize_row(self, feature, model: Optional[Union[PreTrainedModel, nn.Module]] = None) -> Dict:
|
| 506 |
+
"""Tokenize a single row from a DPO specific dataset.
|
| 507 |
+
|
| 508 |
+
At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation
|
| 509 |
+
in case the prompt + chosen or prompt + rejected responses is/are too long. First
|
| 510 |
+
we truncate the prompt; if we're still too long, we truncate the chosen/rejected.
|
| 511 |
+
|
| 512 |
+
We also create the labels for the chosen/rejected responses, which are of length equal to
|
| 513 |
+
the sum of the length of the prompt and the chosen/rejected response, with
|
| 514 |
+
label_pad_token_id for the prompt tokens.
|
| 515 |
+
"""
|
| 516 |
+
batch = {}
|
| 517 |
+
prompt = feature["prompt"]
|
| 518 |
+
chosen = feature["chosen"]
|
| 519 |
+
rejected = feature["rejected"]
|
| 520 |
+
|
| 521 |
+
if not self.is_encoder_decoder:
|
| 522 |
+
# Check issues below for more details
|
| 523 |
+
# 1. https://github.com/huggingface/trl/issues/907
|
| 524 |
+
# 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
|
| 525 |
+
# 3. https://github.com/LianjiaTech/BELLE/issues/337
|
| 526 |
+
|
| 527 |
+
if not isinstance(prompt, str):
|
| 528 |
+
raise ValueError(f"prompt should be an str but got {type(prompt)}")
|
| 529 |
+
prompt_tokens = self.tokenizer(prompt, add_special_tokens=False)
|
| 530 |
+
prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()}
|
| 531 |
+
|
| 532 |
+
if not isinstance(chosen, str):
|
| 533 |
+
raise ValueError(f"chosen should be an str but got {type(chosen)}")
|
| 534 |
+
chosen_tokens = self.build_tokenized_answer(prompt, chosen)
|
| 535 |
+
|
| 536 |
+
if not isinstance(rejected, str):
|
| 537 |
+
raise ValueError(f"rejected should be an str but got {type(rejected)}")
|
| 538 |
+
rejected_tokens = self.build_tokenized_answer(prompt, rejected)
|
| 539 |
+
|
| 540 |
+
# Last prompt token might get merged by tokenizer and
|
| 541 |
+
# it should not be included for generation if that happens
|
| 542 |
+
prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"])
|
| 543 |
+
|
| 544 |
+
chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"])
|
| 545 |
+
rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"])
|
| 546 |
+
prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids)
|
| 547 |
+
|
| 548 |
+
for k, v in prompt_tokens.items():
|
| 549 |
+
prompt_tokens[k] = v[:prompt_len_input_ids]
|
| 550 |
+
|
| 551 |
+
# Make sure prompts only have one different token at most an
|
| 552 |
+
# and length only differs by 1 at most
|
| 553 |
+
num_diff_tokens = sum([a != b for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"])])
|
| 554 |
+
num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids)
|
| 555 |
+
if num_diff_tokens > 1 or num_diff_len > 1:
|
| 556 |
+
raise ValueError("Chosen and rejected prompt_input_ids might only differ on the " "last token due to tokenizer merge ops.")
|
| 557 |
+
|
| 558 |
+
# add BOS token to head of prompt
|
| 559 |
+
prompt_tokens["prompt_input_ids"] = [self.tokenizer.bos_token_id] + prompt_tokens["prompt_input_ids"]
|
| 560 |
+
chosen_tokens["prompt_input_ids"] = [self.tokenizer.bos_token_id] + chosen_tokens["prompt_input_ids"]
|
| 561 |
+
rejected_tokens["prompt_input_ids"] = [self.tokenizer.bos_token_id] + rejected_tokens["prompt_input_ids"]
|
| 562 |
+
|
| 563 |
+
prompt_tokens["prompt_attention_mask"] = [1] + prompt_tokens["prompt_attention_mask"]
|
| 564 |
+
chosen_tokens["prompt_attention_mask"] = [1] + chosen_tokens["prompt_attention_mask"]
|
| 565 |
+
rejected_tokens["prompt_attention_mask"] = [1] + rejected_tokens["prompt_attention_mask"]
|
| 566 |
+
|
| 567 |
+
# add EOS token to end of answer
|
| 568 |
+
chosen_tokens["input_ids"].append(self.tokenizer.eos_token_id)
|
| 569 |
+
chosen_tokens["attention_mask"].append(1)
|
| 570 |
+
|
| 571 |
+
rejected_tokens["input_ids"].append(self.tokenizer.eos_token_id)
|
| 572 |
+
rejected_tokens["attention_mask"].append(1)
|
| 573 |
+
|
| 574 |
+
longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"]))
|
| 575 |
+
|
| 576 |
+
# if combined sequence is too long, truncate the prompt
|
| 577 |
+
for answer_tokens in [chosen_tokens, rejected_tokens, prompt_tokens]:
|
| 578 |
+
if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length:
|
| 579 |
+
if self.truncation_mode == "keep_start":
|
| 580 |
+
for k in ["prompt_input_ids", "prompt_attention_mask"]:
|
| 581 |
+
answer_tokens[k] = answer_tokens[k][: self.max_prompt_length]
|
| 582 |
+
elif self.truncation_mode == "keep_end":
|
| 583 |
+
for k in ["prompt_input_ids", "prompt_attention_mask"]:
|
| 584 |
+
answer_tokens[k] = answer_tokens[k][-self.max_prompt_length :]
|
| 585 |
+
else:
|
| 586 |
+
raise ValueError(f"Unknown truncation mode: {self.truncation_mode}")
|
| 587 |
+
|
| 588 |
+
# if that's still too long, truncate the response
|
| 589 |
+
for answer_tokens in [chosen_tokens, rejected_tokens]:
|
| 590 |
+
if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length:
|
| 591 |
+
for k in ["input_ids", "attention_mask"]:
|
| 592 |
+
answer_tokens[k] = answer_tokens[k][: self.max_length - self.max_prompt_length]
|
| 593 |
+
|
| 594 |
+
# Create labels
|
| 595 |
+
chosen_sequence_tokens = {k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"]}
|
| 596 |
+
rejected_sequence_tokens = {k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"]}
|
| 597 |
+
chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:]
|
| 598 |
+
chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [self.label_pad_token_id] * len(chosen_tokens["prompt_input_ids"])
|
| 599 |
+
rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:]
|
| 600 |
+
rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [self.label_pad_token_id] * len(rejected_tokens["prompt_input_ids"])
|
| 601 |
+
|
| 602 |
+
for k, toks in {
|
| 603 |
+
"chosen_": chosen_sequence_tokens,
|
| 604 |
+
"rejected_": rejected_sequence_tokens,
|
| 605 |
+
"": prompt_tokens,
|
| 606 |
+
}.items():
|
| 607 |
+
for type_key, tokens in toks.items():
|
| 608 |
+
if type_key == "token_type_ids":
|
| 609 |
+
continue
|
| 610 |
+
batch[f"{k}{type_key}"] = tokens
|
| 611 |
+
|
| 612 |
+
else:
|
| 613 |
+
chosen_tokens = self.tokenizer(chosen, truncation=True, max_length=self.max_target_length, add_special_tokens=True)
|
| 614 |
+
rejected_tokens = self.tokenizer(rejected, truncation=True, max_length=self.max_target_length, add_special_tokens=True)
|
| 615 |
+
prompt_tokens = self.tokenizer(prompt, truncation=True, max_length=self.max_prompt_length, add_special_tokens=True)
|
| 616 |
+
|
| 617 |
+
batch["chosen_labels"] = chosen_tokens["input_ids"]
|
| 618 |
+
batch["rejected_labels"] = rejected_tokens["input_ids"]
|
| 619 |
+
batch["prompt_input_ids"] = prompt_tokens["input_ids"]
|
| 620 |
+
batch["prompt_attention_mask"] = prompt_tokens["attention_mask"]
|
| 621 |
+
|
| 622 |
+
if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"):
|
| 623 |
+
batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(labels=batch["rejected_labels"])
|
| 624 |
+
batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(labels=batch["chosen_labels"])
|
| 625 |
+
|
| 626 |
+
return batch
|
| 627 |
+
|
| 628 |
+
@contextmanager
|
| 629 |
+
def null_ref_context(self):
|
| 630 |
+
"""Context manager for handling null reference model (that is, peft adapter manipulation)."""
|
| 631 |
+
with self.accelerator.unwrap_model(self.model).disable_adapter() if self.is_peft_model and not self.ref_adapter_name else nullcontext():
|
| 632 |
+
if self.ref_adapter_name:
|
| 633 |
+
self.model.set_adapter(self.ref_adapter_name)
|
| 634 |
+
yield
|
| 635 |
+
if self.ref_adapter_name:
|
| 636 |
+
self.model.set_adapter(self.model_adapter_name or "default")
|
| 637 |
+
|
| 638 |
+
def compute_reference_log_probs(self, padded_batch: Dict) -> Dict:
|
| 639 |
+
"""Computes log probabilities of the reference model for a single padded batch of a DPO specific dataset."""
|
| 640 |
+
compte_ref_context_manager = torch.cuda.amp.autocast if self._peft_has_been_casted_to_bf16 else nullcontext
|
| 641 |
+
|
| 642 |
+
# compute reference logps
|
| 643 |
+
with torch.no_grad(), compte_ref_context_manager():
|
| 644 |
+
if self.ref_model is None:
|
| 645 |
+
with self.null_ref_context():
|
| 646 |
+
(
|
| 647 |
+
reference_chosen_logps,
|
| 648 |
+
reference_rejected_logps,
|
| 649 |
+
_,
|
| 650 |
+
_,
|
| 651 |
+
) = self.concatenated_forward(self.model, padded_batch)
|
| 652 |
+
else:
|
| 653 |
+
(
|
| 654 |
+
reference_chosen_logps,
|
| 655 |
+
reference_rejected_logps,
|
| 656 |
+
_,
|
| 657 |
+
_,
|
| 658 |
+
) = self.concatenated_forward(self.ref_model, padded_batch)
|
| 659 |
+
|
| 660 |
+
return reference_chosen_logps, reference_rejected_logps
|
| 661 |
+
|
| 662 |
+
@staticmethod
|
| 663 |
+
def concatenated_inputs(
|
| 664 |
+
batch: Dict[str, Union[List, torch.LongTensor]],
|
| 665 |
+
is_encoder_decoder: bool = False,
|
| 666 |
+
label_pad_token_id: int = -100,
|
| 667 |
+
padding_value: int = 0,
|
| 668 |
+
device: Optional[torch.device] = None,
|
| 669 |
+
) -> Dict[str, torch.LongTensor]:
|
| 670 |
+
"""Concatenate the chosen and rejected inputs into a single tensor.
|
| 671 |
+
|
| 672 |
+
Args:
|
| 673 |
+
batch: A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors of shape (batch_size, sequence_length).
|
| 674 |
+
is_encoder_decoder: Whether the model is an encoder-decoder model.
|
| 675 |
+
label_pad_token_id: The label pad token id.
|
| 676 |
+
padding_value: The padding value to use for the concatenated inputs_ids.
|
| 677 |
+
device: The device for the concatenated inputs.
|
| 678 |
+
|
| 679 |
+
Returns:
|
| 680 |
+
A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'.
|
| 681 |
+
"""
|
| 682 |
+
concatenated_batch = {}
|
| 683 |
+
|
| 684 |
+
if is_encoder_decoder:
|
| 685 |
+
max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1])
|
| 686 |
+
else:
|
| 687 |
+
max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1])
|
| 688 |
+
|
| 689 |
+
for k in batch:
|
| 690 |
+
# import pdb; pdb.set_trace()
|
| 691 |
+
if k.startswith("chosen") and isinstance(batch[k], torch.Tensor):
|
| 692 |
+
if "labels" in k or is_encoder_decoder:
|
| 693 |
+
pad_value = label_pad_token_id
|
| 694 |
+
elif k.endswith("_input_ids"):
|
| 695 |
+
pad_value = padding_value
|
| 696 |
+
elif k.endswith("_attention_mask"):
|
| 697 |
+
pad_value = 0
|
| 698 |
+
concatenated_key = k.replace("chosen", "concatenated")
|
| 699 |
+
concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value)
|
| 700 |
+
for k in batch:
|
| 701 |
+
if k.startswith("rejected") and isinstance(batch[k], torch.Tensor):
|
| 702 |
+
if "labels" in k or is_encoder_decoder:
|
| 703 |
+
pad_value = label_pad_token_id
|
| 704 |
+
elif k.endswith("_input_ids"):
|
| 705 |
+
pad_value = padding_value
|
| 706 |
+
elif k.endswith("_attention_mask"):
|
| 707 |
+
pad_value = 0
|
| 708 |
+
concatenated_key = k.replace("rejected", "concatenated")
|
| 709 |
+
concatenated_batch[concatenated_key] = torch.cat(
|
| 710 |
+
(
|
| 711 |
+
concatenated_batch[concatenated_key],
|
| 712 |
+
pad_to_length(batch[k], max_length, pad_value=pad_value),
|
| 713 |
+
),
|
| 714 |
+
dim=0,
|
| 715 |
+
).to(device=device)
|
| 716 |
+
|
| 717 |
+
if is_encoder_decoder:
|
| 718 |
+
concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device)
|
| 719 |
+
concatenated_batch["concatenated_attention_mask"] = batch["prompt_attention_mask"].repeat(2, 1).to(device=device)
|
| 720 |
+
# import pdb; pdb.set_trace()
|
| 721 |
+
# repeated_list = [
|
| 722 |
+
# batch['images'][0] * 2,
|
| 723 |
+
# batch['images'][1] * 2
|
| 724 |
+
# ]
|
| 725 |
+
concatenated_batch["concatenated_images"] = batch["images"] * 2
|
| 726 |
+
concatenated_batch["image_sizes"] = batch["image_sizes"] * 2
|
| 727 |
+
concatenated_batch["modalities"] = batch["modalities"] * 2
|
| 728 |
+
return concatenated_batch
|
| 729 |
+
|
| 730 |
+
def dpo_loss(
|
| 731 |
+
self,
|
| 732 |
+
policy_chosen_logps: torch.FloatTensor,
|
| 733 |
+
policy_rejected_logps: torch.FloatTensor,
|
| 734 |
+
reference_chosen_logps: torch.FloatTensor,
|
| 735 |
+
reference_rejected_logps: torch.FloatTensor,
|
| 736 |
+
) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
|
| 737 |
+
"""Compute the DPO loss for a batch of policy and reference model log probabilities.
|
| 738 |
+
|
| 739 |
+
Args:
|
| 740 |
+
policy_chosen_logps: Log probabilities of the policy model for the chosen responses. Shape: (batch_size,)
|
| 741 |
+
policy_rejected_logps: Log probabilities of the policy model for the rejected responses. Shape: (batch_size,)
|
| 742 |
+
reference_chosen_logps: Log probabilities of the reference model for the chosen responses. Shape: (batch_size,)
|
| 743 |
+
reference_rejected_logps: Log probabilities of the reference model for the rejected responses. Shape: (batch_size,)
|
| 744 |
+
|
| 745 |
+
Returns:
|
| 746 |
+
A tuple of three tensors: (losses, chosen_rewards, rejected_rewards).
|
| 747 |
+
The losses tensor contains the DPO loss for each example in the batch.
|
| 748 |
+
The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively.
|
| 749 |
+
"""
|
| 750 |
+
pi_logratios = policy_chosen_logps - policy_rejected_logps
|
| 751 |
+
if self.reference_free:
|
| 752 |
+
ref_logratios = torch.tensor([0], dtype=pi_logratios.dtype, device=pi_logratios.device)
|
| 753 |
+
else:
|
| 754 |
+
ref_logratios = reference_chosen_logps - reference_rejected_logps
|
| 755 |
+
|
| 756 |
+
pi_logratios = pi_logratios.to(self.accelerator.device)
|
| 757 |
+
ref_logratios = ref_logratios.to(self.accelerator.device)
|
| 758 |
+
logits = pi_logratios - ref_logratios
|
| 759 |
+
# print(f"pi log ratios: {pi_logratios}")
|
| 760 |
+
# print(f"ref log ratios: {ref_logratios}")
|
| 761 |
+
# print(f"logits: {logits}")
|
| 762 |
+
# The beta is a temperature parameter for the DPO loss, typically something in the range of 0.1 to 0.5.
|
| 763 |
+
# We ignore the reference model as beta -> 0. The label_smoothing parameter encodes our uncertainty about the labels and
|
| 764 |
+
# calculates a conservative DPO loss.
|
| 765 |
+
if self.loss_type == "sigmoid":
|
| 766 |
+
losses = -F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing) - F.logsigmoid(-self.beta * logits) * self.label_smoothing
|
| 767 |
+
elif self.loss_type == "hinge":
|
| 768 |
+
losses = torch.relu(1 - self.beta * logits)
|
| 769 |
+
elif self.loss_type == "ipo":
|
| 770 |
+
# eqn (17) of the paper where beta is the regularization parameter for the IPO loss, denoted by tau in the paper.
|
| 771 |
+
losses = (logits - 1 / (2 * self.beta)) ** 2
|
| 772 |
+
elif self.loss_type == "kto_pair":
|
| 773 |
+
# eqn (7) of the HALOs paper
|
| 774 |
+
chosen_KL = (policy_chosen_logps - reference_chosen_logps).mean().clamp(min=0)
|
| 775 |
+
rejected_KL = (policy_rejected_logps - reference_rejected_logps).mean().clamp(min=0)
|
| 776 |
+
|
| 777 |
+
chosen_logratios = policy_chosen_logps - reference_chosen_logps
|
| 778 |
+
rejected_logratios = policy_rejected_logps - reference_rejected_logps
|
| 779 |
+
# As described in the KTO report, the KL term for chosen (rejected) is estimated using the rejected (chosen) half.
|
| 780 |
+
losses = torch.cat(
|
| 781 |
+
(
|
| 782 |
+
1 - F.sigmoid(self.beta * (chosen_logratios - rejected_KL)),
|
| 783 |
+
1 - F.sigmoid(self.beta * (chosen_KL - rejected_logratios)),
|
| 784 |
+
),
|
| 785 |
+
0,
|
| 786 |
+
)
|
| 787 |
+
else:
|
| 788 |
+
raise ValueError(f"Unknown loss type: {self.loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'kto_pair']")
|
| 789 |
+
|
| 790 |
+
chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device) - reference_chosen_logps.to(self.accelerator.device)).detach()
|
| 791 |
+
rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device) - reference_rejected_logps.to(self.accelerator.device)).detach()
|
| 792 |
+
|
| 793 |
+
return losses, chosen_rewards, rejected_rewards
|
| 794 |
+
|
| 795 |
+
@staticmethod
|
| 796 |
+
def get_batch_logps(
|
| 797 |
+
logits: torch.FloatTensor,
|
| 798 |
+
labels: torch.LongTensor,
|
| 799 |
+
average_log_prob: bool = False,
|
| 800 |
+
label_pad_token_id: int = -100,
|
| 801 |
+
is_encoder_decoder: bool = False,
|
| 802 |
+
) -> torch.FloatTensor:
|
| 803 |
+
"""Compute the log probabilities of the given labels under the given logits.
|
| 804 |
+
|
| 805 |
+
Args:
|
| 806 |
+
logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size)
|
| 807 |
+
labels: Labels for which to compute the log probabilities. Label tokens with a value of label_pad_token_id are ignored. Shape: (batch_size, sequence_length)
|
| 808 |
+
average_log_prob: If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the log probabilities of the (non-masked) tokens.
|
| 809 |
+
label_pad_token_id: The label pad token id.
|
| 810 |
+
is_encoder_decoder: Whether the model is an encoder-decoder model.
|
| 811 |
+
|
| 812 |
+
Returns:
|
| 813 |
+
A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the given logits.
|
| 814 |
+
"""
|
| 815 |
+
if logits.shape[:-1] != labels.shape:
|
| 816 |
+
raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.")
|
| 817 |
+
|
| 818 |
+
if not is_encoder_decoder:
|
| 819 |
+
labels = labels[:, 1:].clone()
|
| 820 |
+
logits = logits[:, :-1, :]
|
| 821 |
+
loss_mask = labels != label_pad_token_id
|
| 822 |
+
|
| 823 |
+
# dummy token; we'll ignore the losses on these tokens later
|
| 824 |
+
labels[labels == label_pad_token_id] = 0
|
| 825 |
+
|
| 826 |
+
per_token_logps = torch.gather(logits.log_softmax(-1), dim=2, index=labels.unsqueeze(2)).squeeze(2)
|
| 827 |
+
|
| 828 |
+
if average_log_prob:
|
| 829 |
+
return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1)
|
| 830 |
+
else:
|
| 831 |
+
return (per_token_logps * loss_mask).sum(-1)
|
| 832 |
+
|
| 833 |
+
def get_sft_loss(self, logits, labels):
|
| 834 |
+
# Shift so that tokens < n predict n
|
| 835 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 836 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 837 |
+
# Flatten the tokens
|
| 838 |
+
loss_fct = nn.CrossEntropyLoss()
|
| 839 |
+
shift_logits = shift_logits.view(-1, shift_logits.size(-1))
|
| 840 |
+
shift_labels = shift_labels.view(-1)
|
| 841 |
+
# Enable model/pipeline parallelism
|
| 842 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
| 843 |
+
loss = loss_fct(shift_logits, shift_labels)
|
| 844 |
+
return loss
|
| 845 |
+
|
| 846 |
+
def concatenated_forward(self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]]) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
|
| 847 |
+
"""Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together.
|
| 848 |
+
|
| 849 |
+
We do this to avoid doing two forward passes, because it's faster for FSDP.
|
| 850 |
+
"""
|
| 851 |
+
# import pdb; pdb.set_trace()
|
| 852 |
+
concatenated_batch = self.concatenated_inputs(
|
| 853 |
+
batch,
|
| 854 |
+
is_encoder_decoder=self.is_encoder_decoder,
|
| 855 |
+
label_pad_token_id=self.label_pad_token_id,
|
| 856 |
+
padding_value=self.padding_value,
|
| 857 |
+
device=self.accelerator.device,
|
| 858 |
+
)
|
| 859 |
+
len_chosen = batch["chosen_labels"].shape[0]
|
| 860 |
+
|
| 861 |
+
# import pdb; pdb.set_trace()
|
| 862 |
+
all_logits, new_labels = model(
|
| 863 |
+
concatenated_batch["concatenated_input_ids"],
|
| 864 |
+
attention_mask=concatenated_batch["concatenated_attention_mask"],
|
| 865 |
+
labels=concatenated_batch["concatenated_labels"],
|
| 866 |
+
images=concatenated_batch["concatenated_images"],
|
| 867 |
+
image_sizes=concatenated_batch["image_sizes"],
|
| 868 |
+
modalities=concatenated_batch["modalities"],
|
| 869 |
+
use_cache=False,
|
| 870 |
+
dpo_forward=True,
|
| 871 |
+
)
|
| 872 |
+
all_logits = all_logits.to(torch.float32)
|
| 873 |
+
all_logps = self.get_batch_logps(
|
| 874 |
+
all_logits,
|
| 875 |
+
new_labels,
|
| 876 |
+
average_log_prob=self.loss_type == "ipo",
|
| 877 |
+
is_encoder_decoder=self.is_encoder_decoder,
|
| 878 |
+
label_pad_token_id=self.label_pad_token_id,
|
| 879 |
+
)
|
| 880 |
+
|
| 881 |
+
chosen_logps = all_logps[:len_chosen]
|
| 882 |
+
rejected_logps = all_logps[len_chosen:]
|
| 883 |
+
|
| 884 |
+
# don't count image embeds logits
|
| 885 |
+
# loss_mask = new_labels != -100
|
| 886 |
+
# logits = [all_logits[i][loss_mask[i]] for i in range(loss_mask.shape[0])]
|
| 887 |
+
# chosen_logits = logits[:len_chosen]
|
| 888 |
+
# rejected_logits = logits[len_chosen:]
|
| 889 |
+
# chosen_logits = [l.detach().cpu().mean() for l in chosen_logits]
|
| 890 |
+
# rejected_logits = [l.detach().cpu().mean() for l in rejected_logits]
|
| 891 |
+
# chosen_logits = sum(chosen_logits)/len_chosen
|
| 892 |
+
# rejected_logits = sum(rejected_logits)/len_chosen
|
| 893 |
+
|
| 894 |
+
chosen_logits = all_logits[:len_chosen]
|
| 895 |
+
rejected_logits = all_logits[len_chosen:]
|
| 896 |
+
|
| 897 |
+
chosen_labels = new_labels[:len_chosen]
|
| 898 |
+
rejected_labels = new_labels[len_chosen:]
|
| 899 |
+
|
| 900 |
+
return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_labels, rejected_labels)
|
| 901 |
+
|
| 902 |
+
def get_batch_loss_metrics(
|
| 903 |
+
self,
|
| 904 |
+
model,
|
| 905 |
+
batch: Dict[str, Union[List, torch.LongTensor]],
|
| 906 |
+
train_eval: Literal["train", "eval"] = "train",
|
| 907 |
+
):
|
| 908 |
+
"""Compute the DPO loss and other metrics for the given batch of inputs for train or test.
|
| 909 |
+
CHANGE: 1. add sft loss
|
| 910 |
+
2. all gather metrics
|
| 911 |
+
"""
|
| 912 |
+
metrics = {}
|
| 913 |
+
|
| 914 |
+
(
|
| 915 |
+
policy_chosen_logps,
|
| 916 |
+
policy_rejected_logps,
|
| 917 |
+
policy_chosen_logits,
|
| 918 |
+
policy_rejected_logits,
|
| 919 |
+
chosen_labels,
|
| 920 |
+
rejected_labels,
|
| 921 |
+
) = self.concatenated_forward(model, batch)
|
| 922 |
+
|
| 923 |
+
# if reference_chosen_logps and reference_rejected_logps in batch use them, otherwise use the reference model
|
| 924 |
+
if "reference_chosen_logps" in batch and "reference_rejected_logps" in batch:
|
| 925 |
+
reference_chosen_logps = batch["reference_chosen_logps"]
|
| 926 |
+
reference_rejected_logps = batch["reference_rejected_logps"]
|
| 927 |
+
else:
|
| 928 |
+
with torch.no_grad():
|
| 929 |
+
if self.ref_model is None:
|
| 930 |
+
with self.null_ref_context():
|
| 931 |
+
(
|
| 932 |
+
reference_chosen_logps,
|
| 933 |
+
reference_rejected_logps,
|
| 934 |
+
) = self.concatenated_forward(
|
| 935 |
+
self.model, batch
|
| 936 |
+
)[:2]
|
| 937 |
+
else:
|
| 938 |
+
(
|
| 939 |
+
reference_chosen_logps,
|
| 940 |
+
reference_rejected_logps,
|
| 941 |
+
) = self.concatenated_forward(
|
| 942 |
+
self.ref_model, batch
|
| 943 |
+
)[:2]
|
| 944 |
+
|
| 945 |
+
unscaled_dpo_losses, chosen_rewards, rejected_rewards = self.dpo_loss(
|
| 946 |
+
policy_chosen_logps,
|
| 947 |
+
policy_rejected_logps,
|
| 948 |
+
reference_chosen_logps,
|
| 949 |
+
reference_rejected_logps,
|
| 950 |
+
)
|
| 951 |
+
unscaled_dpo_losses = unscaled_dpo_losses.mean()
|
| 952 |
+
dpo_losses = unscaled_dpo_losses * self.dpo_alpha
|
| 953 |
+
unscaled_sft_loss = self.get_sft_loss(policy_chosen_logits, chosen_labels)
|
| 954 |
+
sft_loss = unscaled_sft_loss * self.gamma
|
| 955 |
+
|
| 956 |
+
# print(sft_loss.shape, dpo_losses.shape)
|
| 957 |
+
losses = dpo_losses + sft_loss
|
| 958 |
+
# losses = sft_loss # sft only
|
| 959 |
+
# losses = dpo_losses # dpo only
|
| 960 |
+
reward_accuracies = (chosen_rewards > rejected_rewards).float()
|
| 961 |
+
|
| 962 |
+
def all_gather_tensor(tensor):
|
| 963 |
+
if torch.distributed.is_available() and torch.distributed.is_initialized():
|
| 964 |
+
tensor = tensor.detach()
|
| 965 |
+
gathered_tensor = [torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())]
|
| 966 |
+
torch.distributed.all_gather(gathered_tensor, tensor)
|
| 967 |
+
tensor = torch.cat(gathered_tensor, dim=0)
|
| 968 |
+
# else:
|
| 969 |
+
# print('not distributed')
|
| 970 |
+
return tensor
|
| 971 |
+
|
| 972 |
+
# gather chosen_rewards across devices
|
| 973 |
+
chosen_rewards = all_gather_tensor(chosen_rewards)
|
| 974 |
+
rejected_rewards = all_gather_tensor(rejected_rewards)
|
| 975 |
+
reward_accuracies = all_gather_tensor(reward_accuracies)
|
| 976 |
+
policy_chosen_logps = all_gather_tensor(policy_chosen_logps)
|
| 977 |
+
policy_rejected_logps = all_gather_tensor(policy_rejected_logps)
|
| 978 |
+
reference_chosen_logps = all_gather_tensor(reference_chosen_logps)
|
| 979 |
+
reference_rejected_logps = all_gather_tensor(reference_rejected_logps)
|
| 980 |
+
|
| 981 |
+
prefix = "eval_" if train_eval == "eval" else ""
|
| 982 |
+
metrics[f"{prefix}losses/dpo"] = unscaled_dpo_losses.cpu()
|
| 983 |
+
metrics[f"{prefix}losses/sft"] = unscaled_sft_loss.cpu()
|
| 984 |
+
metrics[f"{prefix}losses/total"] = losses.cpu()
|
| 985 |
+
metrics[f"{prefix}rewards/chosen"] = chosen_rewards.mean().cpu()
|
| 986 |
+
metrics[f"{prefix}rewards/rejected"] = rejected_rewards.mean().cpu()
|
| 987 |
+
metrics[f"{prefix}rewards/accuracies"] = reward_accuracies.mean().cpu()
|
| 988 |
+
metrics[f"{prefix}rewards/margins"] = (chosen_rewards - rejected_rewards).mean().cpu()
|
| 989 |
+
# policy logps
|
| 990 |
+
metrics[f"{prefix}logps/rejected"] = policy_rejected_logps.detach().mean().cpu()
|
| 991 |
+
metrics[f"{prefix}logps/chosen"] = policy_chosen_logps.detach().mean().cpu()
|
| 992 |
+
# policy logits (exclude image tokens)
|
| 993 |
+
# metrics[f"{prefix}logits/rejected"] =policy_rejected_logits
|
| 994 |
+
# metrics[f"{prefix}logits/chosen"] = policy_chosen_logits
|
| 995 |
+
# reference logps
|
| 996 |
+
metrics[f"{prefix}ref_logps/rejected"] = reference_rejected_logps.mean().cpu()
|
| 997 |
+
metrics[f"{prefix}ref_logps/chosen"] = reference_chosen_logps.mean().cpu()
|
| 998 |
+
|
| 999 |
+
# metrics all pick .4 digits
|
| 1000 |
+
# for k in metrics:
|
| 1001 |
+
# metrics[k] = round(metrics[k].item(), 4)
|
| 1002 |
+
|
| 1003 |
+
return losses, metrics
|
| 1004 |
+
|
| 1005 |
+
def compute_loss(
|
| 1006 |
+
self,
|
| 1007 |
+
model: Union[PreTrainedModel, nn.Module],
|
| 1008 |
+
inputs: Dict[str, Union[torch.Tensor, Any]],
|
| 1009 |
+
return_outputs=False,
|
| 1010 |
+
) -> Union[torch.Tensor, Tuple[torch.Tensor, Dict[str, torch.Tensor]]]:
|
| 1011 |
+
if not self.use_dpo_data_collator:
|
| 1012 |
+
warnings.warn(
|
| 1013 |
+
"compute_loss is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than "
|
| 1014 |
+
"DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator"
|
| 1015 |
+
)
|
| 1016 |
+
|
| 1017 |
+
compute_loss_context_manager = torch.cuda.amp.autocast if self._peft_has_been_casted_to_bf16 else nullcontext
|
| 1018 |
+
|
| 1019 |
+
with compute_loss_context_manager():
|
| 1020 |
+
loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train")
|
| 1021 |
+
|
| 1022 |
+
# force log the metrics
|
| 1023 |
+
self.store_metrics(metrics, train_eval="train")
|
| 1024 |
+
|
| 1025 |
+
if return_outputs:
|
| 1026 |
+
return (loss, metrics)
|
| 1027 |
+
return loss
|
| 1028 |
+
|
| 1029 |
+
def get_batch_samples(self, model, batch: Dict[str, torch.LongTensor]) -> Tuple[str, str]:
|
| 1030 |
+
"""Generate samples from the model and reference model for the given batch of inputs."""
|
| 1031 |
+
|
| 1032 |
+
# If one uses `generate_during_eval` with peft + bf16, we need to explictly call generate with
|
| 1033 |
+
# the torch cuda amp context manager as some hidden states are silently casted to full precision.
|
| 1034 |
+
generate_context_manager = nullcontext if not self._peft_has_been_casted_to_bf16 else torch.cuda.amp.autocast
|
| 1035 |
+
|
| 1036 |
+
with generate_context_manager():
|
| 1037 |
+
policy_output = model.generate(
|
| 1038 |
+
input_ids=batch["prompt_input_ids"],
|
| 1039 |
+
attention_mask=batch["prompt_attention_mask"],
|
| 1040 |
+
max_length=self.max_length,
|
| 1041 |
+
do_sample=True,
|
| 1042 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 1043 |
+
)
|
| 1044 |
+
|
| 1045 |
+
# if reference_output in batch use that otherwise use the reference model
|
| 1046 |
+
if "reference_output" in batch:
|
| 1047 |
+
reference_output = batch["reference_output"]
|
| 1048 |
+
else:
|
| 1049 |
+
if self.ref_model is None:
|
| 1050 |
+
with self.null_ref_context():
|
| 1051 |
+
reference_output = self.model.generate(
|
| 1052 |
+
input_ids=batch["prompt_input_ids"],
|
| 1053 |
+
attention_mask=batch["prompt_attention_mask"],
|
| 1054 |
+
max_length=self.max_length,
|
| 1055 |
+
do_sample=True,
|
| 1056 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 1057 |
+
)
|
| 1058 |
+
else:
|
| 1059 |
+
reference_output = self.ref_model.generate(
|
| 1060 |
+
input_ids=batch["prompt_input_ids"],
|
| 1061 |
+
attention_mask=batch["prompt_attention_mask"],
|
| 1062 |
+
max_length=self.max_length,
|
| 1063 |
+
do_sample=True,
|
| 1064 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 1065 |
+
)
|
| 1066 |
+
|
| 1067 |
+
policy_output = pad_to_length(policy_output, self.max_length, self.tokenizer.pad_token_id)
|
| 1068 |
+
policy_output_decoded = self.tokenizer.batch_decode(policy_output, skip_special_tokens=True)
|
| 1069 |
+
|
| 1070 |
+
reference_output = pad_to_length(reference_output, self.max_length, self.tokenizer.pad_token_id)
|
| 1071 |
+
reference_output_decoded = self.tokenizer.batch_decode(reference_output, skip_special_tokens=True)
|
| 1072 |
+
|
| 1073 |
+
return policy_output_decoded, reference_output_decoded
|
| 1074 |
+
|
| 1075 |
+
def prediction_step(
|
| 1076 |
+
self,
|
| 1077 |
+
model: Union[PreTrainedModel, nn.Module],
|
| 1078 |
+
inputs: Dict[str, Union[torch.Tensor, Any]],
|
| 1079 |
+
prediction_loss_only: bool,
|
| 1080 |
+
ignore_keys: Optional[List[str]] = None,
|
| 1081 |
+
):
|
| 1082 |
+
if not self.use_dpo_data_collator:
|
| 1083 |
+
warnings.warn(
|
| 1084 |
+
"prediction_step is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than "
|
| 1085 |
+
"DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator"
|
| 1086 |
+
)
|
| 1087 |
+
if ignore_keys is None:
|
| 1088 |
+
if hasattr(model, "config"):
|
| 1089 |
+
ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", [])
|
| 1090 |
+
else:
|
| 1091 |
+
ignore_keys = []
|
| 1092 |
+
|
| 1093 |
+
prediction_context_manager = torch.cuda.amp.autocast if self._peft_has_been_casted_to_bf16 else nullcontext
|
| 1094 |
+
|
| 1095 |
+
with torch.no_grad(), prediction_context_manager():
|
| 1096 |
+
loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval")
|
| 1097 |
+
|
| 1098 |
+
# force log the metrics
|
| 1099 |
+
self.store_metrics(metrics, train_eval="eval")
|
| 1100 |
+
|
| 1101 |
+
if prediction_loss_only:
|
| 1102 |
+
return (loss.detach(), None, None)
|
| 1103 |
+
|
| 1104 |
+
# logits for the chosen and rejected samples from model
|
| 1105 |
+
logits_dict = {
|
| 1106 |
+
"eval_logits/chosen": metrics["eval_logits/chosen"],
|
| 1107 |
+
"eval_logits/rejected": metrics["eval_logits/rejected"],
|
| 1108 |
+
}
|
| 1109 |
+
logits = tuple(v.unsqueeze(dim=0) for k, v in logits_dict.items() if k not in ignore_keys)
|
| 1110 |
+
logits = torch.stack(logits).mean(axis=1).to(self.accelerator.device)
|
| 1111 |
+
labels = torch.zeros(logits.shape[0], device=self.accelerator.device)
|
| 1112 |
+
|
| 1113 |
+
return (loss.detach(), logits, labels)
|
| 1114 |
+
|
| 1115 |
+
def store_metrics(self, metrics: Dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None:
|
| 1116 |
+
for key, value in metrics.items():
|
| 1117 |
+
self._stored_metrics[train_eval][key].append(value)
|
| 1118 |
+
|
| 1119 |
+
def evaluation_loop(
|
| 1120 |
+
self,
|
| 1121 |
+
dataloader: DataLoader,
|
| 1122 |
+
description: str,
|
| 1123 |
+
prediction_loss_only: Optional[bool] = None,
|
| 1124 |
+
ignore_keys: Optional[List[str]] = None,
|
| 1125 |
+
metric_key_prefix: str = "eval",
|
| 1126 |
+
) -> EvalLoopOutput:
|
| 1127 |
+
"""
|
| 1128 |
+
Overriding built-in evaluation loop to store metrics for each batch.
|
| 1129 |
+
Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`.
|
| 1130 |
+
|
| 1131 |
+
Works both with or without labels.
|
| 1132 |
+
"""
|
| 1133 |
+
|
| 1134 |
+
# Sample and save to game log if requested (for one batch to save time)
|
| 1135 |
+
if self.generate_during_eval:
|
| 1136 |
+
# Generate random indices within the range of the total number of samples
|
| 1137 |
+
num_samples = len(dataloader.dataset)
|
| 1138 |
+
random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size)
|
| 1139 |
+
|
| 1140 |
+
# Use dataloader.dataset.select to get the random batch without iterating over the DataLoader
|
| 1141 |
+
random_batch_dataset = dataloader.dataset.select(random_indices)
|
| 1142 |
+
random_batch = self.data_collator(random_batch_dataset)
|
| 1143 |
+
random_batch = self._prepare_inputs(random_batch)
|
| 1144 |
+
|
| 1145 |
+
policy_output_decoded, ref_output_decoded = self.get_batch_samples(self.model, random_batch)
|
| 1146 |
+
|
| 1147 |
+
self.log(
|
| 1148 |
+
{
|
| 1149 |
+
"game_log": wandb.Table(
|
| 1150 |
+
columns=["Prompt", "Policy", "Ref Model"],
|
| 1151 |
+
rows=[[prompt, pol[len(prompt) :], ref[len(prompt) :]] for prompt, pol, ref in zip(random_batch["prompt"], policy_output_decoded, ref_output_decoded)],
|
| 1152 |
+
)
|
| 1153 |
+
}
|
| 1154 |
+
)
|
| 1155 |
+
self.state.log_history.pop()
|
| 1156 |
+
|
| 1157 |
+
# Base evaluation
|
| 1158 |
+
initial_output = super().evaluation_loop(dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix)
|
| 1159 |
+
|
| 1160 |
+
return initial_output
|
| 1161 |
+
|
| 1162 |
+
def log(self, logs: Dict[str, float]) -> None:
|
| 1163 |
+
"""
|
| 1164 |
+
Log `logs` on the various objects watching training, including stored metrics.
|
| 1165 |
+
|
| 1166 |
+
Args:
|
| 1167 |
+
logs (`Dict[str, float]`):
|
| 1168 |
+
The values to log.
|
| 1169 |
+
"""
|
| 1170 |
+
# logs either has 'loss' or 'eval_loss'
|
| 1171 |
+
train_eval = "train" if "loss" in logs else "eval"
|
| 1172 |
+
# Add averaged stored metrics to logs
|
| 1173 |
+
for key, metrics in self._stored_metrics[train_eval].items():
|
| 1174 |
+
logs[key] = torch.tensor(metrics).mean().item()
|
| 1175 |
+
del self._stored_metrics[train_eval]
|
| 1176 |
+
return super().log(logs)
|
| 1177 |
+
|
| 1178 |
+
@wraps(Trainer.push_to_hub)
|
| 1179 |
+
def push_to_hub(self, commit_message: Optional[str] = "End of training", blocking: bool = True, **kwargs) -> str:
|
| 1180 |
+
"""
|
| 1181 |
+
Overwrite the `push_to_hub` method in order to force-add the tag "sft" when pushing the
|
| 1182 |
+
model on the Hub. Please refer to `~transformers.Trainer.push_to_hub` for more details.
|
| 1183 |
+
"""
|
| 1184 |
+
kwargs = trl_sanitze_kwargs_for_tagging(model=self.model, tag_names=self._tag_names, kwargs=kwargs)
|
| 1185 |
+
|
| 1186 |
+
return super().push_to_hub(commit_message=commit_message, blocking=blocking, **kwargs)
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/ppo_trainer.py
ADDED
|
@@ -0,0 +1,1397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import inspect
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import time
|
| 18 |
+
import typing
|
| 19 |
+
import warnings
|
| 20 |
+
from contextlib import nullcontext
|
| 21 |
+
from typing import Callable, List, Optional, Union
|
| 22 |
+
|
| 23 |
+
import datasets
|
| 24 |
+
import numpy as np
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
from accelerate import Accelerator
|
| 28 |
+
from accelerate.utils import ProjectConfiguration, gather_object, is_deepspeed_available
|
| 29 |
+
from datasets import Dataset
|
| 30 |
+
from huggingface_hub import whoami
|
| 31 |
+
from packaging import version
|
| 32 |
+
from torch.optim import Adam
|
| 33 |
+
from transformers import (
|
| 34 |
+
DataCollatorForLanguageModeling,
|
| 35 |
+
PreTrainedTokenizer,
|
| 36 |
+
PreTrainedTokenizerBase,
|
| 37 |
+
PreTrainedTokenizerFast,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
from ..core import (
|
| 41 |
+
WANDB_PADDING,
|
| 42 |
+
PPODecorators,
|
| 43 |
+
clip_by_value,
|
| 44 |
+
convert_to_scalar,
|
| 45 |
+
entropy_from_logits,
|
| 46 |
+
flatten_dict,
|
| 47 |
+
logprobs_from_logits,
|
| 48 |
+
masked_mean,
|
| 49 |
+
masked_var,
|
| 50 |
+
masked_whiten,
|
| 51 |
+
set_seed,
|
| 52 |
+
stack_dicts,
|
| 53 |
+
stats_to_np,
|
| 54 |
+
)
|
| 55 |
+
from ..import_utils import is_npu_available, is_torch_greater_2_0, is_xpu_available
|
| 56 |
+
from ..models import SUPPORTED_ARCHITECTURES, PreTrainedModelWrapper, create_reference_model
|
| 57 |
+
from . import AdaptiveKLController, BaseTrainer, FixedKLController, PPOConfig, RunningMoments
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
if is_deepspeed_available():
|
| 61 |
+
import deepspeed
|
| 62 |
+
|
| 63 |
+
MODEL_CARD_TEMPLATE = """---
|
| 64 |
+
license: apache-2.0
|
| 65 |
+
tags:
|
| 66 |
+
- trl
|
| 67 |
+
- ppo
|
| 68 |
+
- transformers
|
| 69 |
+
- reinforcement-learning
|
| 70 |
+
---
|
| 71 |
+
|
| 72 |
+
# {model_name}
|
| 73 |
+
|
| 74 |
+
This is a [TRL language model](https://github.com/huggingface/trl) that has been fine-tuned with reinforcement learning to
|
| 75 |
+
guide the model outputs according to a value, function, or human feedback. The model can be used for text generation.
|
| 76 |
+
|
| 77 |
+
## Usage
|
| 78 |
+
|
| 79 |
+
To use this model for inference, first install the TRL library:
|
| 80 |
+
|
| 81 |
+
```bash
|
| 82 |
+
python -m pip install trl
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
You can then generate text as follows:
|
| 86 |
+
|
| 87 |
+
```python
|
| 88 |
+
from transformers import pipeline
|
| 89 |
+
|
| 90 |
+
generator = pipeline("text-generation", model="{model_id}")
|
| 91 |
+
outputs = generator("Hello, my llama is cute")
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
If you want to use the model for training or to obtain the outputs from the value head, load the model as follows:
|
| 95 |
+
|
| 96 |
+
```python
|
| 97 |
+
from transformers import AutoTokenizer
|
| 98 |
+
from trl import AutoModelForCausalLMWithValueHead
|
| 99 |
+
|
| 100 |
+
tokenizer = AutoTokenizer.from_pretrained("{model_id}")
|
| 101 |
+
model = AutoModelForCausalLMWithValueHead.from_pretrained("{model_id}")
|
| 102 |
+
|
| 103 |
+
inputs = tokenizer("Hello, my llama is cute", return_tensors="pt")
|
| 104 |
+
outputs = model(**inputs, labels=inputs["input_ids"])
|
| 105 |
+
```
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class PPOTrainer(BaseTrainer):
|
| 110 |
+
"""
|
| 111 |
+
The PPOTrainer uses Proximal Policy Optimization to optimise language models.
|
| 112 |
+
Note, this trainer is heavily inspired by the original OpenAI learning to summarize work here:
|
| 113 |
+
https://github.com/openai/summarize-from-feedback
|
| 114 |
+
|
| 115 |
+
Attributes:
|
| 116 |
+
**config** (`PPOConfig`) -- Configuration object for PPOTrainer. Check the documentation of `PPOConfig` for more
|
| 117 |
+
details.
|
| 118 |
+
**model** (`PreTrainedModelWrapper`) -- Model to be optimized, Hugging Face transformer model with a value head.
|
| 119 |
+
Check the documentation of `PreTrainedModelWrapper` for more details.
|
| 120 |
+
**ref_model** (`PreTrainedModelWrapper`, *optional*) -- Reference model to be used for KL penalty, Hugging Face
|
| 121 |
+
transformer model with a casual language modelling head. Check the documentation of `PreTrainedModelWrapper`
|
| 122 |
+
for more details. If no reference model is provided, the trainer will create a reference model with the same
|
| 123 |
+
architecture as the model to be optimized with shared layers.
|
| 124 |
+
**tokenizer** (`PreTrainedTokenizerBase`) -- Tokenizer to be used for encoding the
|
| 125 |
+
data. Check the documentation of `transformers.PreTrainedTokenizer` and
|
| 126 |
+
`transformers.PreTrainedTokenizerFast` for more details.
|
| 127 |
+
**dataset** (Union[`torch.utils.data.Dataset`, `datasets.Dataset`], *optional*) -- PyTorch dataset or Hugging
|
| 128 |
+
Face dataset. This is used to create a PyTorch dataloader. If no dataset is provided, the dataloader must be
|
| 129 |
+
created outside the trainer users needs to design their own dataloader and make sure the batch
|
| 130 |
+
size that is used is the same as the one specified in the configuration object.
|
| 131 |
+
**optimizer** (`torch.optim.Optimizer`, *optional*) -- Optimizer to be used for training. If no optimizer is
|
| 132 |
+
provided, the trainer will create an Adam optimizer with the learning rate specified in the configuration
|
| 133 |
+
object.
|
| 134 |
+
**data_collator** (DataCollatorForLanguageModeling, *optional*) -- Data collator to be used for training and
|
| 135 |
+
passed along the dataloader
|
| 136 |
+
**num_shared_layers** (int, *optional*) -- Number of layers to be shared between the model and the reference
|
| 137 |
+
model, if no reference model is passed. If no number is provided, all the layers will be shared.
|
| 138 |
+
**lr_scheduler** (`torch.optim.lr_scheduler`, *optional*) -- Learning rate scheduler to be used for training.
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
_tag_names = ["trl", "ppo"]
|
| 142 |
+
|
| 143 |
+
def __init__(
|
| 144 |
+
self,
|
| 145 |
+
config: PPOConfig = None,
|
| 146 |
+
model: PreTrainedModelWrapper = None,
|
| 147 |
+
ref_model: Optional[PreTrainedModelWrapper] = None,
|
| 148 |
+
tokenizer: PreTrainedTokenizerBase = None,
|
| 149 |
+
dataset: Optional[Union[torch.utils.data.Dataset, Dataset]] = None,
|
| 150 |
+
optimizer: Optional[torch.optim.Optimizer] = None,
|
| 151 |
+
data_collator: Optional[typing.Callable] = None,
|
| 152 |
+
num_shared_layers: Optional[int] = None,
|
| 153 |
+
lr_scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None,
|
| 154 |
+
):
|
| 155 |
+
"""
|
| 156 |
+
Initialize PPOTrainer.
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
config (`PPOConfig`):
|
| 160 |
+
Configuration object for PPOTrainer. Check the documentation of `PPOConfig` for more details.
|
| 161 |
+
model (`PreTrainedModelWrapper`):
|
| 162 |
+
Hugging Face transformer model with a value head.
|
| 163 |
+
ref_model (`PreTrainedModelWrapper`):
|
| 164 |
+
Hugging Face transformer model with a casual language modelling head. Used for KL penalty
|
| 165 |
+
tokenizer (`transformers.PreTrainedTokenizerBase`):
|
| 166 |
+
Hugging Face tokenizer
|
| 167 |
+
dataset (Optional[Union[`torch.utils.data.Dataset`, `datasets.Dataset`]]):
|
| 168 |
+
PyTorch dataset or Hugging Face dataset. If a Hugging Face dataset is passed, the dataset
|
| 169 |
+
will be preprocessed by removing the columns that are not used by the model. If none is passed,
|
| 170 |
+
a warning will be raised in a multi-GPU setting.
|
| 171 |
+
optimizer (Optional[`torch.optim.Optimizer`]):
|
| 172 |
+
Optimizer used for training. If `None`, the `Adam` is used as default.
|
| 173 |
+
data_collator (Optional[function]):
|
| 174 |
+
Data collator function.
|
| 175 |
+
num_shared_layers (Optional[int]):
|
| 176 |
+
Number of shared layers between the model and the reference model. If `None`, all layers are shared.
|
| 177 |
+
used only if `ref_model` is `None`.
|
| 178 |
+
lr_scheduler (Optional[`torch.optim.lr_scheduler`]):
|
| 179 |
+
Learning rate scheduler used for training.
|
| 180 |
+
"""
|
| 181 |
+
super().__init__(config)
|
| 182 |
+
|
| 183 |
+
# initial seed for reproducible experiments
|
| 184 |
+
set_seed(config.seed)
|
| 185 |
+
|
| 186 |
+
# Step 0: check positional arguments validity
|
| 187 |
+
if not isinstance(config, PPOConfig):
|
| 188 |
+
raise ValueError(f"config must be a PPOConfig, got {type(config)}")
|
| 189 |
+
if not isinstance(tokenizer, (PreTrainedTokenizerBase)):
|
| 190 |
+
raise ValueError(f"tokenizer must be a PreTrainedTokenizerBase like a PreTrainedTokenizer or a PreTrainedTokenizerFast, got {type(tokenizer)}")
|
| 191 |
+
if not isinstance(model, (SUPPORTED_ARCHITECTURES)):
|
| 192 |
+
raise ValueError(f"model must be a PreTrainedModelWrapper, got {type(model)} - supported architectures are: {SUPPORTED_ARCHITECTURES}")
|
| 193 |
+
# Step 1: Initialize Accelerator
|
| 194 |
+
self.accelerator = Accelerator(
|
| 195 |
+
log_with=config.log_with,
|
| 196 |
+
gradient_accumulation_steps=config.gradient_accumulation_steps,
|
| 197 |
+
project_config=ProjectConfiguration(**config.project_kwargs),
|
| 198 |
+
**config.accelerator_kwargs,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
# Step 1.1 Runtime variables filled by the accelerator
|
| 202 |
+
config.world_size = self.accelerator.num_processes
|
| 203 |
+
config.global_backward_batch_size = config.backward_batch_size * config.world_size
|
| 204 |
+
config.global_batch_size = config.batch_size * config.world_size
|
| 205 |
+
|
| 206 |
+
self.model = model
|
| 207 |
+
self.model_params = filter(lambda p: p.requires_grad, self.model.parameters())
|
| 208 |
+
self.is_encoder_decoder = hasattr(self.model, "is_encoder_decoder")
|
| 209 |
+
self.is_peft_model = getattr(self.model, "is_peft_model", False)
|
| 210 |
+
config.is_encoder_decoder = self.is_encoder_decoder
|
| 211 |
+
config.is_peft_model = self.is_peft_model
|
| 212 |
+
|
| 213 |
+
is_using_tensorboard = config.log_with is not None and config.log_with == "tensorboard"
|
| 214 |
+
self.accelerator.init_trackers(
|
| 215 |
+
config.tracker_project_name,
|
| 216 |
+
config=dict(trl_ppo_trainer_config=config.to_dict()) if not is_using_tensorboard else config.to_dict(),
|
| 217 |
+
init_kwargs=config.tracker_kwargs,
|
| 218 |
+
)
|
| 219 |
+
self.is_using_text_environment = getattr(config, "use_text_environment", False)
|
| 220 |
+
|
| 221 |
+
if isinstance(ref_model, SUPPORTED_ARCHITECTURES):
|
| 222 |
+
self.ref_model = ref_model
|
| 223 |
+
if num_shared_layers is not None:
|
| 224 |
+
warnings.warn(
|
| 225 |
+
"num_shared_layers is ignored when ref_model is provided. Two different models are used for the " "model and the reference model and no layers are shared.",
|
| 226 |
+
UserWarning,
|
| 227 |
+
)
|
| 228 |
+
elif ref_model is None and not self.is_peft_model:
|
| 229 |
+
self.ref_model = create_reference_model(self.model, num_shared_layers=num_shared_layers)
|
| 230 |
+
elif self.is_peft_model:
|
| 231 |
+
self.ref_model = None
|
| 232 |
+
else:
|
| 233 |
+
raise ValueError(f"ref_model must be a PreTrainedModelWrapper or `None`, got {type(ref_model)} - supported " f"architectures are: {SUPPORTED_ARCHITECTURES} ")
|
| 234 |
+
self.optional_peft_ctx = self.accelerator.unwrap_model(self.model).pretrained_model.disable_adapter if self.is_peft_model else nullcontext
|
| 235 |
+
|
| 236 |
+
if not (isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast)):
|
| 237 |
+
raise ValueError("tokenizer must be a transformers.PreTrainedTokenizer or transformers.PreTrainedTokenizerFast")
|
| 238 |
+
self.tokenizer = tokenizer
|
| 239 |
+
|
| 240 |
+
if dataset is not None and not (isinstance(dataset, torch.utils.data.Dataset) or isinstance(dataset, Dataset)):
|
| 241 |
+
raise ValueError("dataset must be a torch.utils.data.Dataset or datasets.Dataset")
|
| 242 |
+
elif dataset is None:
|
| 243 |
+
warnings.warn(
|
| 244 |
+
"No dataset is provided. Make sure to set config.batch_size to the correct value before training.",
|
| 245 |
+
UserWarning,
|
| 246 |
+
)
|
| 247 |
+
self.dataset = dataset
|
| 248 |
+
self._signature_columns = None
|
| 249 |
+
if self.dataset is not None:
|
| 250 |
+
self.dataloader = self.prepare_dataloader(self.dataset, data_collator)
|
| 251 |
+
elif self.dataset is None and self.accelerator.num_processes > 1:
|
| 252 |
+
warnings.warn(
|
| 253 |
+
"No dataset is provided. In a multi-GPU setting, this will lead to an error. You should"
|
| 254 |
+
" prepare your dataloader yourself with `dataloader = ppo_trainer.accelerator.prepare(dataloader)`"
|
| 255 |
+
" and using `torch.utils.data.DataLoader`, or pass a dataset to the `PPOTrainer`. Please "
|
| 256 |
+
" refer to the documentation for more details.",
|
| 257 |
+
UserWarning,
|
| 258 |
+
)
|
| 259 |
+
self.dataloader = None
|
| 260 |
+
else:
|
| 261 |
+
self.dataloader = None
|
| 262 |
+
|
| 263 |
+
# Step 3: Initialize optimizer and data collator
|
| 264 |
+
self.data_collator = DataCollatorForLanguageModeling(self.tokenizer, mlm=False)
|
| 265 |
+
if optimizer is None:
|
| 266 |
+
self.optimizer = Adam(
|
| 267 |
+
filter(lambda p: p.requires_grad, self.model.parameters()),
|
| 268 |
+
lr=self.config.learning_rate,
|
| 269 |
+
)
|
| 270 |
+
else:
|
| 271 |
+
self.optimizer = optimizer
|
| 272 |
+
|
| 273 |
+
self.lr_scheduler = lr_scheduler
|
| 274 |
+
if self.lr_scheduler is not None:
|
| 275 |
+
lr_scheduler_class = torch.optim.lr_scheduler._LRScheduler if not is_torch_greater_2_0() else torch.optim.lr_scheduler.LRScheduler
|
| 276 |
+
|
| 277 |
+
if not isinstance(self.lr_scheduler, lr_scheduler_class):
|
| 278 |
+
raise ValueError("lr_scheduler must be a torch.optim.lr_scheduler._LRScheduler or torch.optim.lr_scheduler.LRScheduler (for torch >= 2.0)")
|
| 279 |
+
|
| 280 |
+
if self.config.adap_kl_ctrl:
|
| 281 |
+
self.kl_ctl = AdaptiveKLController(self.config.init_kl_coef, self.config.target, self.config.horizon)
|
| 282 |
+
else:
|
| 283 |
+
self.kl_ctl = FixedKLController(self.config.init_kl_coef)
|
| 284 |
+
|
| 285 |
+
# Safety checkers for DS integration
|
| 286 |
+
is_deepspeed_used = self.accelerator.distributed_type == "DEEPSPEED" and hasattr(self.accelerator.state, "deepspeed_plugin")
|
| 287 |
+
|
| 288 |
+
(
|
| 289 |
+
self.model,
|
| 290 |
+
self.optimizer,
|
| 291 |
+
self.data_collator,
|
| 292 |
+
self.dataloader,
|
| 293 |
+
self.lr_scheduler,
|
| 294 |
+
) = self.accelerator.prepare(
|
| 295 |
+
self.model,
|
| 296 |
+
self.optimizer,
|
| 297 |
+
self.data_collator,
|
| 298 |
+
self.dataloader,
|
| 299 |
+
self.lr_scheduler,
|
| 300 |
+
)
|
| 301 |
+
if is_deepspeed_used:
|
| 302 |
+
# Quantized models are already set on the correct device
|
| 303 |
+
if not self.is_peft_model and not (getattr(self.ref_model.pretrained_model, "is_loaded_in_8bit", False) or getattr(self.ref_model.pretrained_model, "is_loaded_in_4bit", False)):
|
| 304 |
+
self.ref_model = self._prepare_deepspeed(self.ref_model)
|
| 305 |
+
else:
|
| 306 |
+
self.ref_model = self.accelerator.prepare(self.ref_model)
|
| 307 |
+
|
| 308 |
+
# In a distributed setup, only logging needs to be performed on the main process
|
| 309 |
+
# check: https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html
|
| 310 |
+
# or: https://discuss.pytorch.org/t/use-distributed-data-parallel-correctly/82500/11
|
| 311 |
+
self.is_distributed = self.accelerator.num_processes > 1
|
| 312 |
+
|
| 313 |
+
# init the current step
|
| 314 |
+
self.current_step = 0
|
| 315 |
+
|
| 316 |
+
# init variables for pushing model to hub
|
| 317 |
+
if config.push_to_hub_if_best_kwargs:
|
| 318 |
+
if "repo_id" not in config.push_to_hub_if_best_kwargs:
|
| 319 |
+
raise ValueError("You have to specify repo_id in order to push the model to the hub!")
|
| 320 |
+
self.push_to_hub_kwargs = config.push_to_hub_if_best_kwargs
|
| 321 |
+
self.compare_step = 0
|
| 322 |
+
self.highest_reward = torch.tensor(-float("inf"))
|
| 323 |
+
|
| 324 |
+
# post process for PP
|
| 325 |
+
if not getattr(self.model, "is_sequential_parallel", False):
|
| 326 |
+
self.current_device = self.accelerator.device
|
| 327 |
+
else:
|
| 328 |
+
if is_xpu_available():
|
| 329 |
+
self.current_device = torch.device("xpu:0")
|
| 330 |
+
elif is_npu_available():
|
| 331 |
+
self.current_device = torch.device("npu:0")
|
| 332 |
+
else:
|
| 333 |
+
self.current_device = torch.device("cuda:0")
|
| 334 |
+
|
| 335 |
+
PPODecorators.optimize_device_cache = self.config.optimize_device_cache
|
| 336 |
+
|
| 337 |
+
self.running = RunningMoments(self.accelerator)
|
| 338 |
+
|
| 339 |
+
def _filter_kwargs(self, kwargs, target_func):
|
| 340 |
+
"""
|
| 341 |
+
filter the keyword arguments that are supported by the target function.
|
| 342 |
+
|
| 343 |
+
Args:
|
| 344 |
+
kwargs (dict):
|
| 345 |
+
Keyword arguments
|
| 346 |
+
target_func (function):
|
| 347 |
+
Target function
|
| 348 |
+
"""
|
| 349 |
+
return {k: v for k, v in kwargs.items() if k in inspect.signature(target_func).parameters.keys()}
|
| 350 |
+
|
| 351 |
+
def prepare_dataloader(self, dataset: Union[torch.utils.data.Dataset, Dataset], data_collator=None):
|
| 352 |
+
"""
|
| 353 |
+
Prepare the dataloader for training.
|
| 354 |
+
|
| 355 |
+
Args:
|
| 356 |
+
dataset (Union[`torch.utils.data.Dataset`, `datasets.Dataset`]):
|
| 357 |
+
PyTorch dataset or Hugging Face dataset. If a Hugging Face dataset is passed, the dataset
|
| 358 |
+
will be preprocessed by removing the columns that are not used by the model.
|
| 359 |
+
data_collator (Optional[function]):
|
| 360 |
+
Data collator function.
|
| 361 |
+
|
| 362 |
+
Returns:
|
| 363 |
+
`torch.utils.data.DataLoader`: PyTorch dataloader
|
| 364 |
+
"""
|
| 365 |
+
if isinstance(dataset, Dataset):
|
| 366 |
+
dataset = self._remove_unused_columns(dataset)
|
| 367 |
+
dataloader = torch.utils.data.DataLoader(
|
| 368 |
+
dataset,
|
| 369 |
+
batch_size=self.config.batch_size,
|
| 370 |
+
collate_fn=data_collator,
|
| 371 |
+
shuffle=True,
|
| 372 |
+
drop_last=True,
|
| 373 |
+
)
|
| 374 |
+
return dataloader
|
| 375 |
+
|
| 376 |
+
# Adapted from transformers.Trainer._set_signature_columns_if_needed
|
| 377 |
+
def _set_signature_columns_if_needed(self):
|
| 378 |
+
if self._signature_columns is None:
|
| 379 |
+
# Inspect model forward signature to keep only the arguments it accepts.
|
| 380 |
+
signature = inspect.signature(self.model.forward)
|
| 381 |
+
self._signature_columns = list(signature.parameters.keys())
|
| 382 |
+
# label => sentiment | we need query and response for logging purpose
|
| 383 |
+
self._signature_columns += ["label", "query", "response"]
|
| 384 |
+
|
| 385 |
+
# Adapted from transformers.Trainer._remove_unused_columns
|
| 386 |
+
def _remove_unused_columns(self, dataset: "Dataset"):
|
| 387 |
+
if not self.config.remove_unused_columns:
|
| 388 |
+
return dataset
|
| 389 |
+
self._set_signature_columns_if_needed()
|
| 390 |
+
signature_columns = self._signature_columns
|
| 391 |
+
|
| 392 |
+
ignored_columns = list(set(dataset.column_names) - set(signature_columns))
|
| 393 |
+
|
| 394 |
+
columns = [k for k in signature_columns if k in dataset.column_names]
|
| 395 |
+
|
| 396 |
+
if version.parse(datasets.__version__) < version.parse("1.4.0"):
|
| 397 |
+
dataset.set_format(
|
| 398 |
+
type=dataset.format["type"],
|
| 399 |
+
columns=columns,
|
| 400 |
+
format_kwargs=dataset.format["format_kwargs"],
|
| 401 |
+
)
|
| 402 |
+
return dataset
|
| 403 |
+
else:
|
| 404 |
+
return dataset.remove_columns(ignored_columns)
|
| 405 |
+
|
| 406 |
+
def generate(
|
| 407 |
+
self,
|
| 408 |
+
query_tensor: Union[torch.Tensor, List[torch.Tensor]],
|
| 409 |
+
length_sampler: Callable = None,
|
| 410 |
+
batch_size: int = 4,
|
| 411 |
+
return_prompt: bool = True,
|
| 412 |
+
generate_ref_response: bool = False,
|
| 413 |
+
**generation_kwargs,
|
| 414 |
+
):
|
| 415 |
+
"""
|
| 416 |
+
Generate response with the model given the query tensor.
|
| 417 |
+
call the `generate` method of the model.
|
| 418 |
+
|
| 419 |
+
Args:
|
| 420 |
+
query_tensor (`torch.LongTensor`):
|
| 421 |
+
A tensor of shape (`seq_len`) containing query tokens or a list of tensors of shape (`seq_len`).
|
| 422 |
+
length_sampler (`Callable`, *optional*):
|
| 423 |
+
Callable that returns the number of newly generated tokens.
|
| 424 |
+
batch_size (`int`, *optional):
|
| 425 |
+
Batch size used for generation, defaults to `4`.
|
| 426 |
+
return_prompt (`bool`, *optional*):
|
| 427 |
+
If set to `False` the prompt is not returned but only the newly generated tokens, defaults to `True`.
|
| 428 |
+
generate_ref_response (`bool`, *optional*):
|
| 429 |
+
If set to `True` the reference response is also generated, defaults to `False`.
|
| 430 |
+
generation_kwargs (dict[str, Any]):
|
| 431 |
+
Keyword arguments for generation.
|
| 432 |
+
|
| 433 |
+
Returns:
|
| 434 |
+
`torch.LongTensor`: A tensor of shape (`batch_size`, `gen_len`) containing response tokens.
|
| 435 |
+
"""
|
| 436 |
+
if generate_ref_response:
|
| 437 |
+
ref_model = self.model if self.is_peft_model else self.ref_model
|
| 438 |
+
if isinstance(query_tensor, List):
|
| 439 |
+
response = self._generate_batched(
|
| 440 |
+
self.model,
|
| 441 |
+
query_tensor,
|
| 442 |
+
length_sampler=length_sampler,
|
| 443 |
+
batch_size=batch_size,
|
| 444 |
+
return_prompt=return_prompt,
|
| 445 |
+
**generation_kwargs,
|
| 446 |
+
)
|
| 447 |
+
if generate_ref_response:
|
| 448 |
+
with self.optional_peft_ctx():
|
| 449 |
+
ref_response = self._generate_batched(
|
| 450 |
+
ref_model,
|
| 451 |
+
query_tensor,
|
| 452 |
+
length_sampler=length_sampler,
|
| 453 |
+
batch_size=batch_size,
|
| 454 |
+
return_prompt=return_prompt,
|
| 455 |
+
**generation_kwargs,
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
else:
|
| 459 |
+
if len(query_tensor.shape) == 2:
|
| 460 |
+
raise ValueError("query_tensor must be a tensor of shape (`seq_len`) or a list of tensors of shape (`seq_len`)")
|
| 461 |
+
|
| 462 |
+
if length_sampler is not None:
|
| 463 |
+
generation_kwargs["max_new_tokens"] = length_sampler()
|
| 464 |
+
response = self.accelerator.unwrap_model(self.model).generate(input_ids=query_tensor.unsqueeze(dim=0), **generation_kwargs)
|
| 465 |
+
if generate_ref_response:
|
| 466 |
+
with self.optional_peft_ctx():
|
| 467 |
+
ref_response = ref_model.generate(input_ids=query_tensor.unsqueeze(dim=0), **generation_kwargs)
|
| 468 |
+
|
| 469 |
+
if not return_prompt and not self.is_encoder_decoder:
|
| 470 |
+
response = response[:, query_tensor.shape[0] :]
|
| 471 |
+
if generate_ref_response:
|
| 472 |
+
ref_response = ref_response[:, query_tensor.shape[0] :]
|
| 473 |
+
|
| 474 |
+
if generate_ref_response:
|
| 475 |
+
return response, ref_response
|
| 476 |
+
return response
|
| 477 |
+
|
| 478 |
+
def _generate_batched(
|
| 479 |
+
self,
|
| 480 |
+
model: PreTrainedModelWrapper,
|
| 481 |
+
query_tensors: List[torch.Tensor],
|
| 482 |
+
length_sampler: Callable = None,
|
| 483 |
+
batch_size: int = 4,
|
| 484 |
+
return_prompt: bool = True,
|
| 485 |
+
pad_to_multiple_of: int = None,
|
| 486 |
+
remove_padding: bool = True,
|
| 487 |
+
**generation_kwargs,
|
| 488 |
+
):
|
| 489 |
+
outputs = []
|
| 490 |
+
|
| 491 |
+
padding_side_default = self.tokenizer.padding_side
|
| 492 |
+
if not self.is_encoder_decoder:
|
| 493 |
+
self.tokenizer.padding_side = "left"
|
| 494 |
+
|
| 495 |
+
# in case we have fewer examples than bs
|
| 496 |
+
batch_size = min(len(query_tensors), batch_size)
|
| 497 |
+
|
| 498 |
+
for i in range(0, len(query_tensors), batch_size):
|
| 499 |
+
if length_sampler is not None:
|
| 500 |
+
generation_kwargs["max_new_tokens"] = length_sampler()
|
| 501 |
+
|
| 502 |
+
# prevent overflow if query tensors are not even multiple of bs
|
| 503 |
+
end_index = min(len(query_tensors), i + batch_size)
|
| 504 |
+
|
| 505 |
+
batch = query_tensors[i:end_index]
|
| 506 |
+
batch_mask = [torch.ones_like(element) for element in batch]
|
| 507 |
+
inputs = {"input_ids": batch, "attention_mask": batch_mask}
|
| 508 |
+
|
| 509 |
+
padded_inputs = self.tokenizer.pad(
|
| 510 |
+
inputs,
|
| 511 |
+
padding=True,
|
| 512 |
+
max_length=None,
|
| 513 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 514 |
+
return_tensors="pt",
|
| 515 |
+
).to(self.current_device)
|
| 516 |
+
|
| 517 |
+
generations = self.accelerator.unwrap_model(model).generate(**padded_inputs, **generation_kwargs)
|
| 518 |
+
|
| 519 |
+
for generation, mask in zip(generations, padded_inputs["attention_mask"]):
|
| 520 |
+
if not self.is_encoder_decoder:
|
| 521 |
+
output = generation[(1 - mask).sum() :] # remove padding
|
| 522 |
+
else:
|
| 523 |
+
output = generation
|
| 524 |
+
|
| 525 |
+
if not return_prompt and not self.is_encoder_decoder:
|
| 526 |
+
output = output[(mask).sum() :] # remove prompt
|
| 527 |
+
|
| 528 |
+
if remove_padding and self.tokenizer.eos_token_id in output:
|
| 529 |
+
pad_mask = output == self.tokenizer.eos_token_id
|
| 530 |
+
pad_start = torch.nonzero(pad_mask, as_tuple=False)[0, 0].item()
|
| 531 |
+
output = output[: pad_start + 1] # keep the eos token at the end
|
| 532 |
+
|
| 533 |
+
outputs.append(output)
|
| 534 |
+
|
| 535 |
+
self.tokenizer.padding_side = padding_side_default
|
| 536 |
+
return outputs
|
| 537 |
+
|
| 538 |
+
def _step_safety_checker(
|
| 539 |
+
self,
|
| 540 |
+
batch_size: int,
|
| 541 |
+
queries: List[torch.LongTensor],
|
| 542 |
+
responses: List[torch.LongTensor],
|
| 543 |
+
scores: List[torch.FloatTensor],
|
| 544 |
+
masks: Optional[List[torch.LongTensor]] = None,
|
| 545 |
+
):
|
| 546 |
+
"""
|
| 547 |
+
Check if the input data is valid for training.
|
| 548 |
+
|
| 549 |
+
Args:
|
| 550 |
+
batch_size (int):
|
| 551 |
+
Batch size from the config file.
|
| 552 |
+
queries (List[`torch.LongTensor`]):
|
| 553 |
+
List of tensors containing the encoded queries of shape (`query_length`)
|
| 554 |
+
responses (List[`torch.LongTensor`]):
|
| 555 |
+
List of tensors containing the encoded responses of shape (`response_length`)
|
| 556 |
+
scores (List[`torch.FloatTensor`]):
|
| 557 |
+
List of tensors containing the scores.
|
| 558 |
+
masks (List[`torch.LongTensor`], *optional*):
|
| 559 |
+
list of optional tensors containing the masks of shape (`query_length` + `response_length`)
|
| 560 |
+
Returns:
|
| 561 |
+
`tuple`: The input processed data.
|
| 562 |
+
"""
|
| 563 |
+
for name, tensor_list in zip(["queries", "responses", "scores"], [queries, responses, scores]):
|
| 564 |
+
if not isinstance(tensor_list, list):
|
| 565 |
+
raise ValueError(f"{name} must be a list of tensors - got {type(tensor_list)}")
|
| 566 |
+
if not isinstance(tensor_list[0], torch.Tensor):
|
| 567 |
+
raise ValueError(f"Elements in {name} must be tensors - got {type(tensor_list[0])}")
|
| 568 |
+
if batch_size is not None and len(tensor_list) != batch_size:
|
| 569 |
+
raise ValueError(f"Batch size ({batch_size}) does not match number of examples - but got {len(tensor_list)} for: {name}")
|
| 570 |
+
|
| 571 |
+
# add queries, scores and responses on the correct device
|
| 572 |
+
queries = [tensor.to(self.current_device) for tensor in queries]
|
| 573 |
+
responses = [tensor.to(self.current_device) for tensor in responses]
|
| 574 |
+
scores = [tensor.to(self.current_device) for tensor in scores]
|
| 575 |
+
masks = [tensor.to(self.current_device) for tensor in masks] if masks is not None else None
|
| 576 |
+
|
| 577 |
+
# squeeze scores if needed
|
| 578 |
+
for i, score in enumerate(scores):
|
| 579 |
+
if score.dim() > 1:
|
| 580 |
+
raise ValueError(f"Scores must be 1-dimensional - got {score.dim()} for {score}")
|
| 581 |
+
elif score.dim() == 1:
|
| 582 |
+
scores[i] = score.squeeze()
|
| 583 |
+
|
| 584 |
+
return queries, responses, scores, masks
|
| 585 |
+
|
| 586 |
+
@PPODecorators.empty_device_cache()
|
| 587 |
+
def step(
|
| 588 |
+
self,
|
| 589 |
+
queries: List[torch.LongTensor],
|
| 590 |
+
responses: List[torch.LongTensor],
|
| 591 |
+
scores: List[torch.FloatTensor],
|
| 592 |
+
response_masks: Optional[List[torch.LongTensor]] = None,
|
| 593 |
+
):
|
| 594 |
+
"""
|
| 595 |
+
Run a PPO optimisation step given a list of queries, model responses, and rewards.
|
| 596 |
+
|
| 597 |
+
Args:
|
| 598 |
+
queries (List[`torch.LongTensor`]):
|
| 599 |
+
List of tensors containing the encoded queries of shape (`query_length`)
|
| 600 |
+
responses (List[`torch.LongTensor`]):
|
| 601 |
+
List of tensors containing the encoded responses of shape (`response_length`)
|
| 602 |
+
scores (List[`torch.FloatTensor`]):
|
| 603 |
+
List of tensors containing the scores.
|
| 604 |
+
response_masks (List[`torch.FloatTensor`], *optional*)):
|
| 605 |
+
List of tensors containing masks of the response tokens.
|
| 606 |
+
|
| 607 |
+
Returns:
|
| 608 |
+
`dict[str, Any]`: A summary of the training statistics
|
| 609 |
+
"""
|
| 610 |
+
bs = self.config.batch_size
|
| 611 |
+
|
| 612 |
+
queries, responses, scores, response_masks = self._step_safety_checker(bs, queries, responses, scores, response_masks)
|
| 613 |
+
scores = torch.tensor(scores, device=self.current_device)
|
| 614 |
+
if self.config.use_score_scaling:
|
| 615 |
+
# Score scaling
|
| 616 |
+
scores_mean, scores_std = self.running.update(scores)
|
| 617 |
+
tensor_to_kwargs = dict(dtype=scores.dtype, device=scores.device)
|
| 618 |
+
score_scaling_factor = self.running.std.to(**tensor_to_kwargs) + torch.finfo(scores.dtype).eps
|
| 619 |
+
if self.config.use_score_norm:
|
| 620 |
+
scores = (scores - self.running.mean.to(**tensor_to_kwargs)) / score_scaling_factor
|
| 621 |
+
else:
|
| 622 |
+
scores /= score_scaling_factor
|
| 623 |
+
|
| 624 |
+
if self.config.score_clip is not None:
|
| 625 |
+
# Score clipping
|
| 626 |
+
scores_dtype = scores.dtype
|
| 627 |
+
scores = torch.clip(scores.float(), -self.config.score_clip, self.config.score_clip).to(dtype=scores_dtype)
|
| 628 |
+
|
| 629 |
+
# if we want to push best model to the hub
|
| 630 |
+
if hasattr(self, "highest_reward"):
|
| 631 |
+
if self.compare_step % self.config.compare_steps == 0:
|
| 632 |
+
curr_mean_reward = scores.mean()
|
| 633 |
+
# if the best reward ever seen
|
| 634 |
+
if curr_mean_reward > self.highest_reward:
|
| 635 |
+
self.highest_reward = curr_mean_reward
|
| 636 |
+
# push model to hub
|
| 637 |
+
self.push_to_hub(**self.push_to_hub_kwargs)
|
| 638 |
+
self.compare_step += 1
|
| 639 |
+
|
| 640 |
+
timing = dict()
|
| 641 |
+
t0 = time.time()
|
| 642 |
+
|
| 643 |
+
t = time.time()
|
| 644 |
+
|
| 645 |
+
model_inputs = self.prepare_model_inputs(queries, responses)
|
| 646 |
+
|
| 647 |
+
if self.is_distributed:
|
| 648 |
+
pad_first = self.tokenizer.padding_side == "left"
|
| 649 |
+
|
| 650 |
+
model_inputs["input_ids"] = self.accelerator.pad_across_processes(
|
| 651 |
+
model_inputs["input_ids"],
|
| 652 |
+
dim=1,
|
| 653 |
+
pad_index=self.tokenizer.pad_token_id,
|
| 654 |
+
pad_first=pad_first,
|
| 655 |
+
)
|
| 656 |
+
model_inputs["attention_mask"] = self.accelerator.pad_across_processes(model_inputs["attention_mask"], dim=1, pad_index=0, pad_first=pad_first)
|
| 657 |
+
if self.is_encoder_decoder:
|
| 658 |
+
model_inputs["decoder_input_ids"] = self.accelerator.pad_across_processes(
|
| 659 |
+
model_inputs["decoder_input_ids"],
|
| 660 |
+
dim=1,
|
| 661 |
+
pad_index=self.tokenizer.pad_token_id,
|
| 662 |
+
pad_first=pad_first,
|
| 663 |
+
)
|
| 664 |
+
model_inputs["decoder_attention_mask"] = self.accelerator.pad_across_processes(
|
| 665 |
+
model_inputs["decoder_attention_mask"],
|
| 666 |
+
dim=1,
|
| 667 |
+
pad_index=0,
|
| 668 |
+
pad_first=pad_first,
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
model_inputs_names = list(model_inputs.keys())
|
| 672 |
+
|
| 673 |
+
full_kl_penalty = self.config.kl_penalty == "full"
|
| 674 |
+
|
| 675 |
+
with torch.no_grad():
|
| 676 |
+
all_logprobs, logits_or_none, values, masks = self.batched_forward_pass(
|
| 677 |
+
self.model,
|
| 678 |
+
queries,
|
| 679 |
+
responses,
|
| 680 |
+
model_inputs,
|
| 681 |
+
response_masks=response_masks,
|
| 682 |
+
return_logits=full_kl_penalty,
|
| 683 |
+
)
|
| 684 |
+
with self.optional_peft_ctx():
|
| 685 |
+
ref_logprobs, ref_logits_or_none, _, _ = self.batched_forward_pass(
|
| 686 |
+
self.model if self.is_peft_model else self.ref_model,
|
| 687 |
+
queries,
|
| 688 |
+
responses,
|
| 689 |
+
model_inputs,
|
| 690 |
+
return_logits=full_kl_penalty,
|
| 691 |
+
)
|
| 692 |
+
|
| 693 |
+
timing["time/ppo/forward_pass"] = time.time() - t
|
| 694 |
+
|
| 695 |
+
with torch.no_grad():
|
| 696 |
+
t = time.time()
|
| 697 |
+
if full_kl_penalty:
|
| 698 |
+
active_full_logprobs = logprobs_from_logits(logits_or_none, None, gather=False)
|
| 699 |
+
ref_full_logprobs = logprobs_from_logits(ref_logits_or_none, None, gather=False)
|
| 700 |
+
|
| 701 |
+
rewards, non_score_reward, kls = self.compute_rewards(scores, active_full_logprobs, ref_full_logprobs, masks)
|
| 702 |
+
else:
|
| 703 |
+
rewards, non_score_reward, kls = self.compute_rewards(scores, all_logprobs, ref_logprobs, masks)
|
| 704 |
+
timing["time/ppo/compute_rewards"] = time.time() - t
|
| 705 |
+
|
| 706 |
+
t = time.time()
|
| 707 |
+
values, advantages, returns = self.compute_advantages(values, rewards, masks)
|
| 708 |
+
timing["time/ppo/compute_advantages"] = time.time() - t
|
| 709 |
+
|
| 710 |
+
# upcast to float32 to avoid dataset issues
|
| 711 |
+
batch_dict = {
|
| 712 |
+
"queries": queries,
|
| 713 |
+
"responses": responses,
|
| 714 |
+
"logprobs": all_logprobs.to(torch.float32),
|
| 715 |
+
"values": values.to(torch.float32),
|
| 716 |
+
"masks": masks,
|
| 717 |
+
"advantages": advantages,
|
| 718 |
+
"returns": returns,
|
| 719 |
+
}
|
| 720 |
+
batch_dict.update(model_inputs)
|
| 721 |
+
|
| 722 |
+
t = time.time()
|
| 723 |
+
all_stats = []
|
| 724 |
+
early_stop = False
|
| 725 |
+
for _ in range(self.config.ppo_epochs):
|
| 726 |
+
if early_stop:
|
| 727 |
+
break
|
| 728 |
+
b_inds = np.random.permutation(bs)
|
| 729 |
+
for backward_batch_start in range(0, bs, self.config.backward_batch_size):
|
| 730 |
+
backward_batch_end = backward_batch_start + self.config.backward_batch_size
|
| 731 |
+
backward_batch_inds = b_inds[backward_batch_start:backward_batch_end]
|
| 732 |
+
|
| 733 |
+
for mini_batch_start in range(0, self.config.backward_batch_size, self.config.mini_batch_size):
|
| 734 |
+
mini_batch_end = mini_batch_start + self.config.mini_batch_size
|
| 735 |
+
mini_batch_inds = backward_batch_inds[mini_batch_start:mini_batch_end]
|
| 736 |
+
mini_batch_dict = {
|
| 737 |
+
"logprobs": batch_dict["logprobs"][mini_batch_inds],
|
| 738 |
+
"values": batch_dict["values"][mini_batch_inds],
|
| 739 |
+
"masks": batch_dict["masks"][mini_batch_inds],
|
| 740 |
+
# hacks: the queries and responses are ragged.
|
| 741 |
+
"queries": [batch_dict["queries"][i] for i in mini_batch_inds],
|
| 742 |
+
"responses": [batch_dict["responses"][i] for i in mini_batch_inds],
|
| 743 |
+
"advantages": batch_dict["advantages"][mini_batch_inds],
|
| 744 |
+
"returns": batch_dict["returns"][mini_batch_inds],
|
| 745 |
+
}
|
| 746 |
+
for k in model_inputs_names:
|
| 747 |
+
mini_batch_dict[k] = batch_dict[k][mini_batch_inds]
|
| 748 |
+
with self.accelerator.accumulate(self.model):
|
| 749 |
+
model_inputs = {k: mini_batch_dict[k] for k in model_inputs_names}
|
| 750 |
+
|
| 751 |
+
logprobs, logits, vpreds, _ = self.batched_forward_pass(
|
| 752 |
+
self.model,
|
| 753 |
+
mini_batch_dict["queries"],
|
| 754 |
+
mini_batch_dict["responses"],
|
| 755 |
+
model_inputs,
|
| 756 |
+
return_logits=True,
|
| 757 |
+
)
|
| 758 |
+
train_stats = self.train_minibatch(
|
| 759 |
+
mini_batch_dict["logprobs"],
|
| 760 |
+
mini_batch_dict["values"],
|
| 761 |
+
logprobs,
|
| 762 |
+
logits,
|
| 763 |
+
vpreds,
|
| 764 |
+
mini_batch_dict["masks"],
|
| 765 |
+
mini_batch_dict["advantages"],
|
| 766 |
+
mini_batch_dict["returns"],
|
| 767 |
+
)
|
| 768 |
+
all_stats.append(train_stats)
|
| 769 |
+
|
| 770 |
+
# typically, early stopping is done at the epoch level
|
| 771 |
+
if self.config.early_stopping:
|
| 772 |
+
policykl = train_stats["policy/policykl"]
|
| 773 |
+
early_stop = self._early_stop(policykl)
|
| 774 |
+
if early_stop:
|
| 775 |
+
break
|
| 776 |
+
|
| 777 |
+
timing["time/ppo/optimize_step"] = time.time() - t
|
| 778 |
+
|
| 779 |
+
t = time.time()
|
| 780 |
+
train_stats = stack_dicts(all_stats)
|
| 781 |
+
|
| 782 |
+
# reshape advantages/ratios such that they are not averaged.
|
| 783 |
+
train_stats["policy/advantages"] = torch.flatten(train_stats["policy/advantages"]).unsqueeze(0)
|
| 784 |
+
train_stats["policy/advantages"] = torch.nan_to_num(train_stats["policy/advantages"], WANDB_PADDING)
|
| 785 |
+
train_stats["policy/ratio"] = torch.flatten(train_stats["policy/ratio"]).unsqueeze(0)
|
| 786 |
+
|
| 787 |
+
stats = self.record_step_stats(
|
| 788 |
+
scores=scores,
|
| 789 |
+
logprobs=all_logprobs,
|
| 790 |
+
ref_logprobs=ref_logprobs,
|
| 791 |
+
non_score_reward=non_score_reward,
|
| 792 |
+
train_stats=train_stats,
|
| 793 |
+
kl_coef=self.kl_ctl.value,
|
| 794 |
+
masks=masks,
|
| 795 |
+
queries=queries,
|
| 796 |
+
responses=responses,
|
| 797 |
+
kls=kls,
|
| 798 |
+
)
|
| 799 |
+
# Gather/Reduce stats from all processes
|
| 800 |
+
if self.is_distributed:
|
| 801 |
+
stats = self.gather_stats(stats)
|
| 802 |
+
stats = stats_to_np(stats)
|
| 803 |
+
timing["time/ppo/calc_stats"] = time.time() - t
|
| 804 |
+
stats["ppo/learning_rate"] = self.optimizer.param_groups[0]["lr"]
|
| 805 |
+
|
| 806 |
+
# Update the KL control - multiply the batch_size by the number of processes
|
| 807 |
+
self.kl_ctl.update(
|
| 808 |
+
stats["objective/kl"],
|
| 809 |
+
self.config.batch_size * self.accelerator.num_processes,
|
| 810 |
+
)
|
| 811 |
+
|
| 812 |
+
# Log the total ppo time
|
| 813 |
+
timing["time/ppo/total"] = time.time() - t0
|
| 814 |
+
stats.update(timing)
|
| 815 |
+
|
| 816 |
+
# post-process stats for tensorboard and other loggers
|
| 817 |
+
if self.config.log_with != "wandb":
|
| 818 |
+
stats = convert_to_scalar(stats)
|
| 819 |
+
|
| 820 |
+
if self.lr_scheduler is not None:
|
| 821 |
+
self.lr_scheduler.step()
|
| 822 |
+
|
| 823 |
+
return stats
|
| 824 |
+
|
| 825 |
+
def _early_stop(self, policykl):
|
| 826 |
+
r"""
|
| 827 |
+
Handles the early stopping logic. If the policy KL is greater than the target KL, then the gradient is zeroed and
|
| 828 |
+
the optimization step is skipped.
|
| 829 |
+
This also handles the multi-gpu case where the policy KL is averaged across all processes.
|
| 830 |
+
|
| 831 |
+
Args:
|
| 832 |
+
policy_kl (torch.Tensor):
|
| 833 |
+
the policy KL
|
| 834 |
+
|
| 835 |
+
Returns:
|
| 836 |
+
`bool`: whether to early stop or not
|
| 837 |
+
"""
|
| 838 |
+
early_stop = False
|
| 839 |
+
if not self.config.early_stopping:
|
| 840 |
+
return early_stop
|
| 841 |
+
|
| 842 |
+
if not self.is_distributed and policykl > 1.5 * self.config.target_kl:
|
| 843 |
+
self.optimizer.zero_grad()
|
| 844 |
+
early_stop = True
|
| 845 |
+
elif self.is_distributed:
|
| 846 |
+
import torch.distributed as dist
|
| 847 |
+
|
| 848 |
+
# Wait for all processes to finish
|
| 849 |
+
dist.barrier()
|
| 850 |
+
|
| 851 |
+
# all gather the policykl
|
| 852 |
+
dist.all_reduce(policykl, dist.ReduceOp.SUM)
|
| 853 |
+
policykl /= self.accelerator.num_processes
|
| 854 |
+
|
| 855 |
+
if policykl > 1.5 * self.config.target_kl:
|
| 856 |
+
self.optimizer.zero_grad()
|
| 857 |
+
early_stop = True
|
| 858 |
+
return early_stop
|
| 859 |
+
|
| 860 |
+
def gather_stats(self, stats):
|
| 861 |
+
"""
|
| 862 |
+
Gather stats from all processes. Useful in the context of distributed training.
|
| 863 |
+
|
| 864 |
+
Args:
|
| 865 |
+
stats (dict[str, Any]):
|
| 866 |
+
a dictionary of stats to be gathered. The stats should contain torch tensors.
|
| 867 |
+
|
| 868 |
+
Returns:
|
| 869 |
+
`dict[str, Any]`: A dictionary of stats with the tensors gathered.
|
| 870 |
+
"""
|
| 871 |
+
import torch.distributed as dist
|
| 872 |
+
|
| 873 |
+
# Wait for all processes to finish
|
| 874 |
+
dist.barrier()
|
| 875 |
+
|
| 876 |
+
for k, v in stats.items():
|
| 877 |
+
if isinstance(v, torch.Tensor):
|
| 878 |
+
dist.all_reduce(v.to(self.accelerator.device), dist.ReduceOp.SUM)
|
| 879 |
+
v /= self.accelerator.num_processes
|
| 880 |
+
stats[k] = v
|
| 881 |
+
return stats
|
| 882 |
+
|
| 883 |
+
def prepare_model_inputs(self, queries: torch.Tensor, responses: torch.Tensor):
|
| 884 |
+
if self.is_encoder_decoder:
|
| 885 |
+
input_data = self.data_collator([{"input_ids": q, "attention_mask": torch.ones_like(q)} for q in queries]).to(self.current_device)
|
| 886 |
+
|
| 887 |
+
decoder_inputs = self.data_collator([{"input_ids": r, "attention_mask": torch.ones_like(r)} for r in responses]).to(self.current_device)
|
| 888 |
+
|
| 889 |
+
input_data["decoder_input_ids"] = decoder_inputs["input_ids"]
|
| 890 |
+
input_data["decoder_attention_mask"] = decoder_inputs["attention_mask"]
|
| 891 |
+
else:
|
| 892 |
+
input_ids = [torch.cat([q, r]) for q, r in zip(queries, responses)]
|
| 893 |
+
input_data = self.data_collator([{"input_ids": ids, "attention_mask": torch.ones_like(ids)} for ids in input_ids]).to(self.current_device)
|
| 894 |
+
|
| 895 |
+
input_data.pop("labels", None) # we don't want to compute LM losses
|
| 896 |
+
return input_data
|
| 897 |
+
|
| 898 |
+
@PPODecorators.empty_device_cache()
|
| 899 |
+
def batched_forward_pass(
|
| 900 |
+
self,
|
| 901 |
+
model: PreTrainedModelWrapper,
|
| 902 |
+
queries: torch.Tensor,
|
| 903 |
+
responses: torch.Tensor,
|
| 904 |
+
model_inputs: dict,
|
| 905 |
+
return_logits: bool = False,
|
| 906 |
+
response_masks: Optional[torch.Tensor] = None,
|
| 907 |
+
):
|
| 908 |
+
"""
|
| 909 |
+
Calculate model outputs in multiple batches.
|
| 910 |
+
|
| 911 |
+
Args:
|
| 912 |
+
queries (`torch.LongTensor`):
|
| 913 |
+
List of tensors containing the encoded queries, shape (`batch_size`, `query_length`)
|
| 914 |
+
responses (`torch.LongTensor`):
|
| 915 |
+
List of tensors containing the encoded responses, shape (`batch_size`, `response_length`)
|
| 916 |
+
return_logits (`bool`, *optional*, defaults to `False`):
|
| 917 |
+
Whether to return all_logits. Set to `False` if logits are not needed to reduce memory consumption.
|
| 918 |
+
Returns:
|
| 919 |
+
(tuple):
|
| 920 |
+
- all_logprobs (`torch.FloatTensor`): Log probabilities of the responses,
|
| 921 |
+
shape (`batch_size`, `response_length`)
|
| 922 |
+
- all_ref_logprobs (`torch.FloatTensor`): Log probabilities of the responses,
|
| 923 |
+
shape (`batch_size`, `response_length`)
|
| 924 |
+
- all_values (`torch.FloatTensor`): Values of the responses, shape (`batch_size`, `response_length`)
|
| 925 |
+
"""
|
| 926 |
+
bs = len(queries)
|
| 927 |
+
fbs = self.config.mini_batch_size
|
| 928 |
+
all_logprobs = []
|
| 929 |
+
all_logits = []
|
| 930 |
+
all_masks = []
|
| 931 |
+
all_values = []
|
| 932 |
+
|
| 933 |
+
model.eval()
|
| 934 |
+
|
| 935 |
+
for i in range(math.ceil(bs / fbs)):
|
| 936 |
+
input_kwargs = {key: value[i * fbs : (i + 1) * fbs] for key, value in model_inputs.items()}
|
| 937 |
+
query_batch = queries[i * fbs : (i + 1) * fbs]
|
| 938 |
+
response_batch = responses[i * fbs : (i + 1) * fbs]
|
| 939 |
+
if response_masks is not None:
|
| 940 |
+
response_masks_batch = response_masks[i * fbs : (i + 1) * fbs]
|
| 941 |
+
logits, _, values = model(**input_kwargs)
|
| 942 |
+
|
| 943 |
+
if self.is_encoder_decoder:
|
| 944 |
+
input_ids = input_kwargs["decoder_input_ids"]
|
| 945 |
+
attention_mask = input_kwargs["decoder_attention_mask"]
|
| 946 |
+
else:
|
| 947 |
+
input_ids = input_kwargs["input_ids"]
|
| 948 |
+
attention_mask = input_kwargs["attention_mask"]
|
| 949 |
+
|
| 950 |
+
logprobs = logprobs_from_logits(logits[:, :-1, :], input_ids[:, 1:])
|
| 951 |
+
masks = torch.zeros_like(attention_mask)
|
| 952 |
+
masks[:, :-1] = attention_mask[:, 1:]
|
| 953 |
+
|
| 954 |
+
for j in range(len(query_batch)):
|
| 955 |
+
if self.is_encoder_decoder:
|
| 956 |
+
# Decoder sentence starts always in the index 1 after padding in the Enc-Dec Models
|
| 957 |
+
start = 1
|
| 958 |
+
end = attention_mask[j, :].sum() - 1
|
| 959 |
+
else:
|
| 960 |
+
start = len(query_batch[j]) - 1 # logprobs starts from the second query token
|
| 961 |
+
if attention_mask[j, 0] == 0: # offset left padding
|
| 962 |
+
start += attention_mask[j, :].nonzero()[0]
|
| 963 |
+
end = start + len(response_batch[j])
|
| 964 |
+
if response_masks is not None:
|
| 965 |
+
response_masks_batch[j] = torch.cat((torch.zeros_like(query_batch[j]), response_masks_batch[j]))[1:]
|
| 966 |
+
|
| 967 |
+
masks[j, :start] = 0
|
| 968 |
+
masks[j, end:] = 0
|
| 969 |
+
if response_masks is not None:
|
| 970 |
+
masks[j, start:end] = masks[j, start:end] * response_masks_batch[j][start:end]
|
| 971 |
+
|
| 972 |
+
if return_logits:
|
| 973 |
+
all_logits.append(logits)
|
| 974 |
+
else:
|
| 975 |
+
del logits
|
| 976 |
+
all_values.append(values)
|
| 977 |
+
all_logprobs.append(logprobs)
|
| 978 |
+
all_masks.append(masks)
|
| 979 |
+
|
| 980 |
+
return (
|
| 981 |
+
torch.cat(all_logprobs),
|
| 982 |
+
torch.cat(all_logits)[:, :-1] if return_logits else None,
|
| 983 |
+
torch.cat(all_values)[:, :-1],
|
| 984 |
+
torch.cat(all_masks)[:, :-1],
|
| 985 |
+
)
|
| 986 |
+
|
| 987 |
+
@PPODecorators.empty_device_cache()
|
| 988 |
+
def train_minibatch(
|
| 989 |
+
self,
|
| 990 |
+
old_logprobs: torch.FloatTensor,
|
| 991 |
+
values: torch.FloatTensor,
|
| 992 |
+
logprobs: torch.FloatTensor,
|
| 993 |
+
logits: torch.FloatTensor,
|
| 994 |
+
vpreds: torch.FloatTensor,
|
| 995 |
+
mask: torch.LongTensor,
|
| 996 |
+
advantages: torch.FloatTensor,
|
| 997 |
+
returns: torch.FloatTensor,
|
| 998 |
+
):
|
| 999 |
+
"""
|
| 1000 |
+
Train one PPO minibatch
|
| 1001 |
+
|
| 1002 |
+
Args:
|
| 1003 |
+
logprobs (`torch.FloatTensor`):
|
| 1004 |
+
Log probabilities of the model, shape [mini_batch_size, response_length]
|
| 1005 |
+
values (`torch.FloatTensor`):
|
| 1006 |
+
Values of the value head, shape [mini_batch_size, response_length]
|
| 1007 |
+
query (`torch.LongTensor`):
|
| 1008 |
+
Encoded queries, shape [mini_batch_size, query_length]
|
| 1009 |
+
response (`torch.LongTensor`):
|
| 1010 |
+
Encoded responses, shape [mini_batch_size, response_length]
|
| 1011 |
+
model_input (`torch.LongTensor`):
|
| 1012 |
+
Concatenated queries and responses, shape [mini_batch_size, query_length+response_length]
|
| 1013 |
+
|
| 1014 |
+
Returns:
|
| 1015 |
+
train_stats (dict[str, `torch.Tensor`]):
|
| 1016 |
+
Dictionary of training statistics
|
| 1017 |
+
"""
|
| 1018 |
+
self.model.train()
|
| 1019 |
+
loss_p, loss_v, train_stats = self.loss(old_logprobs, values, logits, vpreds, logprobs, mask, advantages, returns)
|
| 1020 |
+
loss = loss_p + loss_v
|
| 1021 |
+
self.accelerator.backward(loss)
|
| 1022 |
+
if self.config.max_grad_norm is not None:
|
| 1023 |
+
if self.accelerator.sync_gradients:
|
| 1024 |
+
self.accelerator.clip_grad_norm_(self.model_params, self.config.max_grad_norm)
|
| 1025 |
+
self.optimizer.step()
|
| 1026 |
+
# we call optimizer.zero_grad() every time and let `accelerator` handle accumulation
|
| 1027 |
+
# see https://huggingface.co/docs/accelerate/usage_guides/gradient_accumulation#the-finished-code
|
| 1028 |
+
self.optimizer.zero_grad()
|
| 1029 |
+
return train_stats
|
| 1030 |
+
|
| 1031 |
+
def compute_rewards(
|
| 1032 |
+
self,
|
| 1033 |
+
scores: torch.FloatTensor,
|
| 1034 |
+
logprobs: torch.FloatTensor,
|
| 1035 |
+
ref_logprobs: torch.FloatTensor,
|
| 1036 |
+
masks: torch.LongTensor,
|
| 1037 |
+
):
|
| 1038 |
+
"""
|
| 1039 |
+
Compute per token rewards from scores and KL-penalty.
|
| 1040 |
+
|
| 1041 |
+
Args:
|
| 1042 |
+
scores (`torch.FloatTensor`):
|
| 1043 |
+
Scores from the reward model, shape (`batch_size`)
|
| 1044 |
+
logprobs (`torch.FloatTensor`):
|
| 1045 |
+
Log probabilities of the model, shape (`batch_size`, `response_length`)
|
| 1046 |
+
ref_logprobs (`torch.FloatTensor`):
|
| 1047 |
+
Log probabilities of the reference model, shape (`batch_size`, `response_length`)
|
| 1048 |
+
|
| 1049 |
+
Returns:
|
| 1050 |
+
`torch.FloatTensor`: Per token rewards, shape (`batch_size`, `response_length`)
|
| 1051 |
+
`torch.FloatTensor`: Non score rewards, shape (`batch_size`, `response_length`)
|
| 1052 |
+
`torch.FloatTensor`: KL penalty, shape (`batch_size`, `response_length`)
|
| 1053 |
+
"""
|
| 1054 |
+
rewards, non_score_rewards, kls = [], [], []
|
| 1055 |
+
for score, logprob, ref_logprob, mask in zip(scores, logprobs, ref_logprobs, masks):
|
| 1056 |
+
# compute KL penalty (from difference in logprobs)
|
| 1057 |
+
kl = self._kl_penalty(logprob, ref_logprob)
|
| 1058 |
+
kls.append(kl)
|
| 1059 |
+
non_score_reward = -self.kl_ctl.value * kl
|
| 1060 |
+
non_score_rewards.append(non_score_reward)
|
| 1061 |
+
reward = non_score_reward.clone()
|
| 1062 |
+
last_non_masked_index = mask.nonzero()[-1]
|
| 1063 |
+
|
| 1064 |
+
# reward is preference model score + KL penalty
|
| 1065 |
+
reward[last_non_masked_index] += score
|
| 1066 |
+
rewards.append(reward)
|
| 1067 |
+
return torch.stack(rewards), torch.stack(non_score_rewards), torch.stack(kls)
|
| 1068 |
+
|
| 1069 |
+
def _kl_penalty(self, logprob: torch.FloatTensor, ref_logprob: torch.FloatTensor) -> torch.FloatTensor:
|
| 1070 |
+
if self.config.kl_penalty == "kl":
|
| 1071 |
+
return logprob - ref_logprob
|
| 1072 |
+
|
| 1073 |
+
if self.config.kl_penalty == "abs":
|
| 1074 |
+
return (logprob - ref_logprob).abs()
|
| 1075 |
+
|
| 1076 |
+
if self.config.kl_penalty == "mse":
|
| 1077 |
+
return 0.5 * (logprob - ref_logprob).square()
|
| 1078 |
+
|
| 1079 |
+
if self.config.kl_penalty == "full":
|
| 1080 |
+
# Flip is required due to this issue? :https://github.com/pytorch/pytorch/issues/57459
|
| 1081 |
+
return F.kl_div(ref_logprob, logprob, log_target=True, reduction="none").sum(-1)
|
| 1082 |
+
|
| 1083 |
+
raise NotImplementedError
|
| 1084 |
+
|
| 1085 |
+
def compute_advantages(
|
| 1086 |
+
self,
|
| 1087 |
+
values: torch.FloatTensor,
|
| 1088 |
+
rewards: torch.FloatTensor,
|
| 1089 |
+
mask: torch.FloatTensor,
|
| 1090 |
+
):
|
| 1091 |
+
lastgaelam = 0
|
| 1092 |
+
advantages_reversed = []
|
| 1093 |
+
gen_len = rewards.shape[-1]
|
| 1094 |
+
|
| 1095 |
+
values = values * mask
|
| 1096 |
+
rewards = rewards * mask
|
| 1097 |
+
|
| 1098 |
+
if self.config.whiten_rewards:
|
| 1099 |
+
rewards = masked_whiten(rewards, mask, shift_mean=False)
|
| 1100 |
+
|
| 1101 |
+
for t in reversed(range(gen_len)):
|
| 1102 |
+
nextvalues = values[:, t + 1] if t < gen_len - 1 else 0.0
|
| 1103 |
+
delta = rewards[:, t] + self.config.gamma * nextvalues - values[:, t]
|
| 1104 |
+
lastgaelam = delta + self.config.gamma * self.config.lam * lastgaelam
|
| 1105 |
+
advantages_reversed.append(lastgaelam)
|
| 1106 |
+
advantages = torch.stack(advantages_reversed[::-1]).transpose(0, 1)
|
| 1107 |
+
|
| 1108 |
+
returns = advantages + values
|
| 1109 |
+
advantages = masked_whiten(advantages, mask)
|
| 1110 |
+
advantages = advantages.detach()
|
| 1111 |
+
return values, advantages, returns
|
| 1112 |
+
|
| 1113 |
+
def loss(
|
| 1114 |
+
self,
|
| 1115 |
+
old_logprobs: torch.FloatTensor,
|
| 1116 |
+
values: torch.FloatTensor,
|
| 1117 |
+
logits: torch.FloatTensor,
|
| 1118 |
+
vpreds: torch.FloatTensor,
|
| 1119 |
+
logprobs: torch.FloatTensor,
|
| 1120 |
+
mask: torch.LongTensor,
|
| 1121 |
+
advantages: torch.FloatTensor,
|
| 1122 |
+
returns: torch.FloatTensor,
|
| 1123 |
+
):
|
| 1124 |
+
"""
|
| 1125 |
+
Calculate policy and value losses.
|
| 1126 |
+
|
| 1127 |
+
Args:
|
| 1128 |
+
old_logprobs (`torch.FloatTensor`):
|
| 1129 |
+
Log probabilities of the model, shape (`batch_size`, `response_length`)
|
| 1130 |
+
values (`torch.FloatTensor`):
|
| 1131 |
+
Values of the value head, shape (`batch_size`, `response_length`)
|
| 1132 |
+
rewards (`torch.FloatTensor`):
|
| 1133 |
+
Rewards from the reward model, shape (`batch_size`, `response_length`)
|
| 1134 |
+
logits (`torch.FloatTensor`):
|
| 1135 |
+
Logits of the model, shape (`batch_size`, `response_length`, `vocab_size`)
|
| 1136 |
+
v_pred (`torch.FloatTensor`):
|
| 1137 |
+
Values of the value head, shape (`batch_size`, `response_length`)
|
| 1138 |
+
logprobs (`torch.FloatTensor`):
|
| 1139 |
+
Log probabilities of the model, shape (`batch_size`, `response_length`)
|
| 1140 |
+
"""
|
| 1141 |
+
|
| 1142 |
+
vpredclipped = clip_by_value(
|
| 1143 |
+
vpreds,
|
| 1144 |
+
values - self.config.cliprange_value,
|
| 1145 |
+
values + self.config.cliprange_value,
|
| 1146 |
+
)
|
| 1147 |
+
|
| 1148 |
+
vf_losses1 = (vpreds - returns) ** 2
|
| 1149 |
+
vf_losses2 = (vpredclipped - returns) ** 2
|
| 1150 |
+
vf_loss = 0.5 * masked_mean(torch.max(vf_losses1, vf_losses2), mask)
|
| 1151 |
+
vf_clipfrac = masked_mean(torch.gt(vf_losses2, vf_losses1).float(), mask)
|
| 1152 |
+
|
| 1153 |
+
ratio = torch.exp(logprobs - old_logprobs)
|
| 1154 |
+
|
| 1155 |
+
pg_losses = -advantages * ratio
|
| 1156 |
+
pg_losses2 = -advantages * torch.clamp(ratio, 1.0 - self.config.cliprange, 1.0 + self.config.cliprange)
|
| 1157 |
+
|
| 1158 |
+
pg_loss = masked_mean(torch.max(pg_losses, pg_losses2), mask)
|
| 1159 |
+
pg_clipfrac = masked_mean(torch.gt(pg_losses2, pg_losses).float(), mask)
|
| 1160 |
+
|
| 1161 |
+
loss = pg_loss + self.config.vf_coef * vf_loss
|
| 1162 |
+
|
| 1163 |
+
avg_ratio = masked_mean(ratio, mask).item()
|
| 1164 |
+
if avg_ratio > self.config.ratio_threshold:
|
| 1165 |
+
warnings.warn(f"The average ratio of batch ({avg_ratio:.2f}) exceeds threshold {self.config.ratio_threshold:.2f}. Skipping batch.")
|
| 1166 |
+
pg_loss = pg_loss * 0.0
|
| 1167 |
+
vf_loss = vf_loss * 0.0
|
| 1168 |
+
loss = loss * 0.0
|
| 1169 |
+
|
| 1170 |
+
entropy = masked_mean(entropy_from_logits(logits), mask)
|
| 1171 |
+
|
| 1172 |
+
approxkl = 0.5 * masked_mean((logprobs - old_logprobs) ** 2, mask)
|
| 1173 |
+
policykl = masked_mean(old_logprobs - logprobs, mask)
|
| 1174 |
+
|
| 1175 |
+
return_mean, return_var = masked_mean(returns, mask), masked_var(returns, mask)
|
| 1176 |
+
value_mean, value_var = masked_mean(values, mask), masked_var(values, mask)
|
| 1177 |
+
|
| 1178 |
+
stats = dict(
|
| 1179 |
+
loss=dict(policy=pg_loss.detach(), value=vf_loss.detach(), total=loss.detach()),
|
| 1180 |
+
policy=dict(
|
| 1181 |
+
entropy=entropy.detach(),
|
| 1182 |
+
approxkl=approxkl.detach(),
|
| 1183 |
+
policykl=policykl.detach(),
|
| 1184 |
+
clipfrac=pg_clipfrac.detach(),
|
| 1185 |
+
advantages=advantages.detach(),
|
| 1186 |
+
advantages_mean=masked_mean(advantages, mask).detach(),
|
| 1187 |
+
ratio=ratio.detach(),
|
| 1188 |
+
),
|
| 1189 |
+
returns=dict(mean=return_mean.detach(), var=return_var.detach()),
|
| 1190 |
+
val=dict(
|
| 1191 |
+
vpred=masked_mean(vpreds, mask).detach(),
|
| 1192 |
+
error=masked_mean((vpreds - returns) ** 2, mask).detach(),
|
| 1193 |
+
clipfrac=vf_clipfrac.detach(),
|
| 1194 |
+
mean=value_mean.detach(),
|
| 1195 |
+
var=value_var.detach(),
|
| 1196 |
+
),
|
| 1197 |
+
)
|
| 1198 |
+
return pg_loss, self.config.vf_coef * vf_loss, flatten_dict(stats)
|
| 1199 |
+
|
| 1200 |
+
def record_step_stats(self, kl_coef: float, **data):
|
| 1201 |
+
"""
|
| 1202 |
+
Record training step statistics.
|
| 1203 |
+
|
| 1204 |
+
|
| 1205 |
+
Args:
|
| 1206 |
+
kl_coef (`float`):
|
| 1207 |
+
KL coefficient
|
| 1208 |
+
data (`dict`):
|
| 1209 |
+
Dictionary of training step data
|
| 1210 |
+
|
| 1211 |
+
Returns:
|
| 1212 |
+
stats (`dict`):
|
| 1213 |
+
Dictionary of training step statistics
|
| 1214 |
+
"""
|
| 1215 |
+
mask = data.pop("masks")
|
| 1216 |
+
|
| 1217 |
+
kls = data.pop("kls")
|
| 1218 |
+
kl_list = ((kls) * mask).sum(axis=-1)
|
| 1219 |
+
mean_kl = kl_list.mean()
|
| 1220 |
+
mean_entropy = (-data["logprobs"] * mask).sum(axis=-1).mean()
|
| 1221 |
+
|
| 1222 |
+
mean_non_score_reward = masked_mean(data["non_score_reward"], mask) # non_score_reward is size `batch_size`, `response_length`
|
| 1223 |
+
mean_scores = data["scores"].mean() # scores is size `batch_size`
|
| 1224 |
+
std_scores = data["scores"].std()
|
| 1225 |
+
|
| 1226 |
+
if mean_kl.item() < -1.0:
|
| 1227 |
+
# warn users
|
| 1228 |
+
warnings.warn(
|
| 1229 |
+
f"KL divergence is starting to become negative: {mean_kl.item():.2f} - this might be a precursor for failed training."
|
| 1230 |
+
" sometimes this happens because the generation kwargs are not correctly set. Please make sure"
|
| 1231 |
+
" that the generation kwargs are set correctly, or review your training hyperparameters."
|
| 1232 |
+
)
|
| 1233 |
+
|
| 1234 |
+
stats = {
|
| 1235 |
+
"objective/kl": mean_kl,
|
| 1236 |
+
"objective/kl_dist": kl_list,
|
| 1237 |
+
"objective/logprobs": data["logprobs"],
|
| 1238 |
+
"objective/ref_logprobs": data["ref_logprobs"],
|
| 1239 |
+
"objective/kl_coef": kl_coef,
|
| 1240 |
+
"objective/entropy": mean_entropy,
|
| 1241 |
+
"ppo/mean_non_score_reward": mean_non_score_reward,
|
| 1242 |
+
"ppo/mean_scores": mean_scores,
|
| 1243 |
+
"ppo/std_scores": std_scores,
|
| 1244 |
+
}
|
| 1245 |
+
|
| 1246 |
+
# Log text properties
|
| 1247 |
+
query_lens = torch.tensor([len(query) for query in data["queries"]], dtype=torch.float)
|
| 1248 |
+
response_lens = torch.tensor([len(response) for response in data["responses"]], dtype=torch.float)
|
| 1249 |
+
|
| 1250 |
+
stats["tokens/queries_len_mean"] = torch.mean(query_lens).cpu().numpy().item()
|
| 1251 |
+
stats["tokens/queries_len_std"] = torch.std(query_lens).cpu().numpy().item()
|
| 1252 |
+
stats["tokens/queries_dist"] = query_lens.cpu().numpy()
|
| 1253 |
+
stats["tokens/responses_len_mean"] = torch.mean(response_lens).cpu().numpy().item()
|
| 1254 |
+
stats["tokens/responses_len_std"] = torch.std(response_lens).cpu().numpy().item()
|
| 1255 |
+
stats["tokens/responses_dist"] = response_lens.cpu().numpy()
|
| 1256 |
+
|
| 1257 |
+
for k, v in data["train_stats"].items():
|
| 1258 |
+
stats[f"ppo/{k}"] = torch.mean(v, axis=0)
|
| 1259 |
+
stats["ppo/val/var_explained"] = 1 - stats["ppo/val/error"] / stats["ppo/returns/var"]
|
| 1260 |
+
return stats
|
| 1261 |
+
|
| 1262 |
+
def log_stats(
|
| 1263 |
+
self,
|
| 1264 |
+
stats: dict,
|
| 1265 |
+
batch: dict,
|
| 1266 |
+
rewards: List[torch.FloatTensor],
|
| 1267 |
+
columns_to_log: List[str] = ["query", "response"],
|
| 1268 |
+
):
|
| 1269 |
+
"""
|
| 1270 |
+
A function that logs all the training stats. Call it at the end of each epoch.
|
| 1271 |
+
|
| 1272 |
+
Args:
|
| 1273 |
+
stats (dict[str, Any]):
|
| 1274 |
+
A dictionary of training stats.
|
| 1275 |
+
batch (dict[str, Any]):
|
| 1276 |
+
A dictionary of batch data, this contains the queries and responses.
|
| 1277 |
+
rewards (`List[torch.FloatTensor]`):
|
| 1278 |
+
A tensor of rewards.
|
| 1279 |
+
"""
|
| 1280 |
+
|
| 1281 |
+
# all gather stats
|
| 1282 |
+
if not isinstance(rewards, torch.Tensor):
|
| 1283 |
+
rewards = torch.tensor(rewards).to(self.current_device)
|
| 1284 |
+
rewards = self.accelerator.gather(rewards).flatten()
|
| 1285 |
+
|
| 1286 |
+
if self.config.log_with == "wandb":
|
| 1287 |
+
import wandb
|
| 1288 |
+
|
| 1289 |
+
if any([column_to_log not in batch.keys() for column_to_log in columns_to_log]):
|
| 1290 |
+
raise ValueError(f"Columns to log {columns_to_log} are not present in the batch {batch.keys()}.")
|
| 1291 |
+
|
| 1292 |
+
batch_list = [batch[column_to_log] for column_to_log in columns_to_log]
|
| 1293 |
+
if self.is_distributed:
|
| 1294 |
+
gathered_batch_list = []
|
| 1295 |
+
for b in batch_list:
|
| 1296 |
+
flattened = gather_object(b)
|
| 1297 |
+
gathered_batch_list.append(flattened)
|
| 1298 |
+
batch_list = gathered_batch_list
|
| 1299 |
+
|
| 1300 |
+
# Log only if we are in the main process
|
| 1301 |
+
if self.accelerator.is_main_process:
|
| 1302 |
+
logs = {}
|
| 1303 |
+
|
| 1304 |
+
# Log stats
|
| 1305 |
+
if "query" not in batch.keys() and "response" not in batch.keys():
|
| 1306 |
+
# warn the user that the game logs will not be logged
|
| 1307 |
+
warnings.warn("The game logs will not be logged because the batch does not contain the keys 'query' and " "'response'. ")
|
| 1308 |
+
elif self.config.log_with == "wandb":
|
| 1309 |
+
table_rows = [list(r) for r in zip(*batch_list, rewards.cpu().tolist())]
|
| 1310 |
+
logs.update({"game_log": wandb.Table(columns=[*columns_to_log, "reward"], rows=table_rows)})
|
| 1311 |
+
|
| 1312 |
+
logs.update(stats)
|
| 1313 |
+
|
| 1314 |
+
# manually cast in fp32 for bf16 torch tensors
|
| 1315 |
+
for k, v in logs.items():
|
| 1316 |
+
if isinstance(v, torch.Tensor) and v.dtype == torch.bfloat16:
|
| 1317 |
+
logs[k] = v.float()
|
| 1318 |
+
|
| 1319 |
+
logs["env/reward_mean"] = torch.mean(rewards).cpu().numpy().item()
|
| 1320 |
+
logs["env/reward_std"] = torch.std(rewards).cpu().numpy().item()
|
| 1321 |
+
logs["env/reward_dist"] = rewards.cpu().numpy()
|
| 1322 |
+
|
| 1323 |
+
if self.config.log_with == "tensorboard":
|
| 1324 |
+
# update the current step
|
| 1325 |
+
self.current_step += 1
|
| 1326 |
+
|
| 1327 |
+
self.accelerator.log(
|
| 1328 |
+
logs,
|
| 1329 |
+
step=self.current_step if self.config.log_with == "tensorboard" else None,
|
| 1330 |
+
)
|
| 1331 |
+
|
| 1332 |
+
def create_model_card(self, path: str, model_name: Optional[str] = "TRL Model") -> None:
|
| 1333 |
+
"""Creates and saves a model card for a TRL model.
|
| 1334 |
+
|
| 1335 |
+
Args:
|
| 1336 |
+
path (`str`): The path to save the model card to.
|
| 1337 |
+
model_name (`str`, *optional*): The name of the model, defaults to `TRL Model`.
|
| 1338 |
+
"""
|
| 1339 |
+
try:
|
| 1340 |
+
user = whoami()["name"]
|
| 1341 |
+
# handle the offline case
|
| 1342 |
+
except: # noqa
|
| 1343 |
+
warnings.warn("Cannot retrieve user information assuming you are running in offline mode.")
|
| 1344 |
+
return
|
| 1345 |
+
|
| 1346 |
+
if not os.path.exists(path):
|
| 1347 |
+
os.makedirs(path)
|
| 1348 |
+
|
| 1349 |
+
model_card_content = MODEL_CARD_TEMPLATE.format(model_name=model_name, model_id=f"{user}/{path}")
|
| 1350 |
+
with open(os.path.join(path, "README.md"), "w", encoding="utf-8") as f:
|
| 1351 |
+
f.write(model_card_content)
|
| 1352 |
+
|
| 1353 |
+
def _save_pretrained(self, save_directory: str) -> None:
|
| 1354 |
+
self.accelerator.unwrap_model(self.model).save_pretrained(save_directory)
|
| 1355 |
+
self.tokenizer.save_pretrained(save_directory)
|
| 1356 |
+
self.create_model_card(save_directory)
|
| 1357 |
+
|
| 1358 |
+
def _show_tokens(self, tokens, masks):
|
| 1359 |
+
from rich import print
|
| 1360 |
+
from rich.text import Text
|
| 1361 |
+
|
| 1362 |
+
text = Text()
|
| 1363 |
+
|
| 1364 |
+
for i, (token, mask) in enumerate(zip(tokens, masks)):
|
| 1365 |
+
if mask == 1:
|
| 1366 |
+
text.append(self.tokenizer.decode(token.item()), style="black on deep_sky_blue1")
|
| 1367 |
+
text.append(" ")
|
| 1368 |
+
else:
|
| 1369 |
+
text.append(self.tokenizer.decode(token.item()), style="black on cyan3")
|
| 1370 |
+
text.append(" ")
|
| 1371 |
+
print(text)
|
| 1372 |
+
|
| 1373 |
+
def _prepare_deepspeed(self, model: PreTrainedModelWrapper):
|
| 1374 |
+
# Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473
|
| 1375 |
+
deepspeed_plugin = self.accelerator.state.deepspeed_plugin
|
| 1376 |
+
config_kwargs = deepspeed_plugin.deepspeed_config
|
| 1377 |
+
if model is not None:
|
| 1378 |
+
if hasattr(model, "config"):
|
| 1379 |
+
hidden_size = max(model.config.hidden_sizes) if getattr(model.config, "hidden_sizes", None) else getattr(model.config, "hidden_size", None)
|
| 1380 |
+
if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3:
|
| 1381 |
+
# Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0`
|
| 1382 |
+
# This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081
|
| 1383 |
+
config_kwargs.update(
|
| 1384 |
+
{
|
| 1385 |
+
"zero_optimization.reduce_bucket_size": hidden_size * hidden_size,
|
| 1386 |
+
"zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size,
|
| 1387 |
+
"zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size,
|
| 1388 |
+
}
|
| 1389 |
+
)
|
| 1390 |
+
|
| 1391 |
+
# If ZeRO-3 is used, we shard both the active and reference model.
|
| 1392 |
+
# Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO disabled (stage 0)
|
| 1393 |
+
if config_kwargs["zero_optimization"]["stage"] != 3:
|
| 1394 |
+
config_kwargs["zero_optimization"]["stage"] = 0
|
| 1395 |
+
model, *_ = deepspeed.initialize(model=model, config=config_kwargs)
|
| 1396 |
+
model.eval()
|
| 1397 |
+
return model
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/reward_config.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
from typing import Optional
|
| 17 |
+
|
| 18 |
+
from transformers import TrainingArguments
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class RewardConfig(TrainingArguments):
|
| 23 |
+
"""
|
| 24 |
+
RewardConfig collects all training arguments related to the [`RewardTrainer`] class.
|
| 25 |
+
|
| 26 |
+
Using [`HfArgumentParser`] we can turn this class into
|
| 27 |
+
[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
|
| 28 |
+
command line.
|
| 29 |
+
|
| 30 |
+
Parameters:
|
| 31 |
+
max_length (`int`, *optional*, defaults to `None`):
|
| 32 |
+
The maximum length of the sequences in the batch. This argument is required if you want to use the default data collator.
|
| 33 |
+
gradient_checkpointing (`bool`, *optional*, defaults to `True`):
|
| 34 |
+
If True, use gradient checkpointing to save memory at the expense of slower backward pass.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
max_length: Optional[int] = None
|
| 38 |
+
"""The maximum length of the sequences in the batch. This argument is required if you want to use the default data collator."""
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/reward_trainer.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import inspect
|
| 15 |
+
import warnings
|
| 16 |
+
from dataclasses import FrozenInstanceError, replace
|
| 17 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
from datasets import Dataset
|
| 22 |
+
from transformers import DataCollator, PreTrainedModel, PreTrainedTokenizerBase, Trainer, TrainingArguments
|
| 23 |
+
from transformers.trainer_callback import TrainerCallback
|
| 24 |
+
from transformers.trainer_pt_utils import nested_detach
|
| 25 |
+
from transformers.trainer_utils import EvalPrediction
|
| 26 |
+
|
| 27 |
+
from ..import_utils import is_peft_available
|
| 28 |
+
from .reward_config import RewardConfig
|
| 29 |
+
from .utils import RewardDataCollatorWithPadding, compute_accuracy
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if is_peft_available():
|
| 33 |
+
from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class RewardTrainer(Trainer):
|
| 37 |
+
r"""
|
| 38 |
+
The RewardTrainer can be used to train your custom Reward Model. It is a subclass of the
|
| 39 |
+
`transformers.Trainer` class and inherits all of its attributes and methods. It is recommended to use
|
| 40 |
+
an `AutoModelForSequenceClassification` as the reward model. The reward model should be trained on a dataset
|
| 41 |
+
of paired examples, where each example is a tuple of two sequences. The reward model should be trained to
|
| 42 |
+
predict which example in the pair is more relevant to the task at hand.
|
| 43 |
+
|
| 44 |
+
The reward trainer expects a very specific format for the dataset. The dataset should contain two 4 entries at least
|
| 45 |
+
if you don't use the default `RewardDataCollatorWithPadding` data collator. The entries should be named
|
| 46 |
+
- `input_ids_chosen`
|
| 47 |
+
- `attention_mask_chosen`
|
| 48 |
+
- `input_ids_rejected`
|
| 49 |
+
- `attention_mask_rejected`
|
| 50 |
+
|
| 51 |
+
Optionally, you can also pass a `margin` entry to the dataset. This entry should contain the margin used to modulate the
|
| 52 |
+
loss of the reward model as outlined in https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/.
|
| 53 |
+
If you don't pass a margin, no margin will be used.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
def __init__(
|
| 57 |
+
self,
|
| 58 |
+
model: Union[PreTrainedModel, nn.Module] = None,
|
| 59 |
+
args: Optional[RewardConfig] = None,
|
| 60 |
+
data_collator: Optional[DataCollator] = None,
|
| 61 |
+
train_dataset: Optional[Dataset] = None,
|
| 62 |
+
eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None,
|
| 63 |
+
tokenizer: Optional[PreTrainedTokenizerBase] = None,
|
| 64 |
+
model_init: Optional[Callable[[], PreTrainedModel]] = None,
|
| 65 |
+
compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None,
|
| 66 |
+
callbacks: Optional[List[TrainerCallback]] = None,
|
| 67 |
+
optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (
|
| 68 |
+
None,
|
| 69 |
+
None,
|
| 70 |
+
),
|
| 71 |
+
preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
|
| 72 |
+
max_length: Optional[int] = None,
|
| 73 |
+
peft_config: Optional[Dict] = None,
|
| 74 |
+
):
|
| 75 |
+
"""
|
| 76 |
+
Initialize RewardTrainer.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
model (`transformers.PreTrainedModel`):
|
| 80 |
+
The model to train, preferably an `AutoModelForSequenceClassification`.
|
| 81 |
+
args (`RewardConfig`):
|
| 82 |
+
The arguments to use for training.
|
| 83 |
+
data_collator (`transformers.DataCollator`):
|
| 84 |
+
The data collator to use for training. If None is specified, the default data collator (`RewardDataCollatorWithPadding`) will be used
|
| 85 |
+
which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences.
|
| 86 |
+
train_dataset (`datasets.Dataset`):
|
| 87 |
+
The dataset to use for training.
|
| 88 |
+
eval_dataset (`datasets.Dataset`):
|
| 89 |
+
The dataset to use for evaluation.
|
| 90 |
+
tokenizer (`transformers.PreTrainedTokenizerBase`):
|
| 91 |
+
The tokenizer to use for training. This argument is required if you want to use the default data collator.
|
| 92 |
+
model_init (`Callable[[], transformers.PreTrainedModel]`):
|
| 93 |
+
The model initializer to use for training. If None is specified, the default model initializer will be used.
|
| 94 |
+
compute_metrics (`Callable[[transformers.EvalPrediction], Dict]`, *optional* defaults to `compute_accuracy`):
|
| 95 |
+
The metrics to use for evaluation. If no metrics are specified, the default metric (`compute_accuracy`) will be used.
|
| 96 |
+
callbacks (`List[transformers.TrainerCallback]`):
|
| 97 |
+
The callbacks to use for training.
|
| 98 |
+
optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
|
| 99 |
+
The optimizer and scheduler to use for training.
|
| 100 |
+
preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
|
| 101 |
+
The function to use to preprocess the logits before computing the metrics.
|
| 102 |
+
max_length (`int`, defaults to `None`):
|
| 103 |
+
The maximum length of the sequences in the batch. This argument is required if you want to use the default data collator.
|
| 104 |
+
peft_config (`Dict`, defaults to `None`):
|
| 105 |
+
The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model.
|
| 106 |
+
"""
|
| 107 |
+
if type(args) == TrainingArguments:
|
| 108 |
+
warnings.warn(
|
| 109 |
+
"Using `transformers.TrainingArguments` for `args` is deprecated and will be removed in a future version. Please use `RewardConfig` instead.",
|
| 110 |
+
FutureWarning,
|
| 111 |
+
)
|
| 112 |
+
if max_length is not None:
|
| 113 |
+
warnings.warn(
|
| 114 |
+
"The `max_length` argument is deprecated and will be removed in a future version. Please use the `RewardConfig` to set `max_length` instead.",
|
| 115 |
+
FutureWarning,
|
| 116 |
+
)
|
| 117 |
+
else:
|
| 118 |
+
if max_length is not None and args.max_length is not None:
|
| 119 |
+
raise ValueError("You cannot specify both `max_length` and `args.max_length`. Please use the `RewardConfig` to set `max_length` once.")
|
| 120 |
+
if max_length is not None and args.max_length is None:
|
| 121 |
+
warnings.warn(
|
| 122 |
+
"The `max_length` argument is deprecated and will be removed in a future version. Please use the `RewardConfig` to set `max_length` instead.",
|
| 123 |
+
FutureWarning,
|
| 124 |
+
)
|
| 125 |
+
if not is_peft_available() and peft_config is not None:
|
| 126 |
+
raise ValueError("PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models")
|
| 127 |
+
elif is_peft_available() and peft_config is not None:
|
| 128 |
+
if not isinstance(model, PeftModel):
|
| 129 |
+
if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_quantized", False):
|
| 130 |
+
_supports_gc_kwargs = "gradient_checkpointing_kwargs" in list(inspect.signature(prepare_model_for_kbit_training).parameters)
|
| 131 |
+
|
| 132 |
+
preprare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing}
|
| 133 |
+
|
| 134 |
+
if not _supports_gc_kwargs and args.gradient_checkpointing_kwargs is not None:
|
| 135 |
+
warnings.warn("You passed `gradient_checkpointing_kwargs` in the trainer's kwargs, but your peft version does not support it. " "please update to the latest version of peft to use `gradient_checkpointing_kwargs`.")
|
| 136 |
+
elif _supports_gc_kwargs and args.gradient_checkpointing_kwargs is not None:
|
| 137 |
+
preprare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs
|
| 138 |
+
|
| 139 |
+
model = prepare_model_for_kbit_training(model, **preprare_model_kwargs)
|
| 140 |
+
|
| 141 |
+
model = get_peft_model(model, peft_config)
|
| 142 |
+
|
| 143 |
+
if compute_metrics is None:
|
| 144 |
+
compute_metrics = compute_accuracy
|
| 145 |
+
|
| 146 |
+
if data_collator is None:
|
| 147 |
+
if tokenizer is None:
|
| 148 |
+
raise ValueError("max_length or a tokenizer must be specified when using the default RewardDataCollatorWithPadding")
|
| 149 |
+
if type(args) == TrainingArguments:
|
| 150 |
+
if max_length is None:
|
| 151 |
+
warnings.warn(
|
| 152 |
+
"When using RewardDataCollatorWithPadding, you should set `max_length` in RewardConfig." " It will be set to `512` by default, but you should do it yourself in the future.",
|
| 153 |
+
UserWarning,
|
| 154 |
+
)
|
| 155 |
+
max_length = 512
|
| 156 |
+
else:
|
| 157 |
+
if max_length is None and args.max_length is None:
|
| 158 |
+
warnings.warn(
|
| 159 |
+
"When using RewardDataCollatorWithPadding, you should set `max_length` in RewardConfig." " It will be set to `512` by default, but you should do it yourself in the future.",
|
| 160 |
+
UserWarning,
|
| 161 |
+
)
|
| 162 |
+
max_length = 512
|
| 163 |
+
if max_length is None and args.max_length is not None:
|
| 164 |
+
max_length = args.max_length
|
| 165 |
+
|
| 166 |
+
data_collator = RewardDataCollatorWithPadding(tokenizer, max_length=max_length)
|
| 167 |
+
|
| 168 |
+
if args.remove_unused_columns:
|
| 169 |
+
try: # for bc before https://github.com/huggingface/transformers/pull/25435
|
| 170 |
+
args.remove_unused_columns = False
|
| 171 |
+
except FrozenInstanceError:
|
| 172 |
+
args = replace(args, remove_unused_columns=False)
|
| 173 |
+
# warn users
|
| 174 |
+
warnings.warn(
|
| 175 |
+
"When using RewardDataCollatorWithPadding, you should set `remove_unused_columns=False` in your RewardConfig" " we have set it for you, but you should do it yourself in the future.",
|
| 176 |
+
UserWarning,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
self.use_reward_data_collator = True
|
| 180 |
+
else:
|
| 181 |
+
self.use_reward_data_collator = False
|
| 182 |
+
super().__init__(
|
| 183 |
+
model,
|
| 184 |
+
args,
|
| 185 |
+
data_collator,
|
| 186 |
+
train_dataset,
|
| 187 |
+
eval_dataset,
|
| 188 |
+
tokenizer,
|
| 189 |
+
model_init,
|
| 190 |
+
compute_metrics,
|
| 191 |
+
callbacks,
|
| 192 |
+
optimizers,
|
| 193 |
+
preprocess_logits_for_metrics,
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
def compute_loss(
|
| 197 |
+
self,
|
| 198 |
+
model: Union[PreTrainedModel, nn.Module],
|
| 199 |
+
inputs: Dict[str, Union[torch.Tensor, Any]],
|
| 200 |
+
return_outputs=False,
|
| 201 |
+
) -> Union[torch.Tensor, Tuple[torch.Tensor, Dict[str, torch.Tensor]]]:
|
| 202 |
+
if not self.use_reward_data_collator:
|
| 203 |
+
warnings.warn("The current compute_loss is implemented for RewardDataCollatorWithPadding," " if you are using a custom data collator make sure you know what you are doing or" " implement your own compute_loss method.")
|
| 204 |
+
rewards_chosen = model(
|
| 205 |
+
input_ids=inputs["input_ids_chosen"],
|
| 206 |
+
attention_mask=inputs["attention_mask_chosen"],
|
| 207 |
+
return_dict=True,
|
| 208 |
+
)["logits"]
|
| 209 |
+
rewards_rejected = model(
|
| 210 |
+
input_ids=inputs["input_ids_rejected"],
|
| 211 |
+
attention_mask=inputs["attention_mask_rejected"],
|
| 212 |
+
return_dict=True,
|
| 213 |
+
)["logits"]
|
| 214 |
+
# calculate loss, optionally modulate with margin
|
| 215 |
+
if "margin" in inputs:
|
| 216 |
+
loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected - inputs["margin"]).mean()
|
| 217 |
+
else:
|
| 218 |
+
loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected).mean()
|
| 219 |
+
|
| 220 |
+
if return_outputs:
|
| 221 |
+
return loss, {
|
| 222 |
+
"rewards_chosen": rewards_chosen,
|
| 223 |
+
"rewards_rejected": rewards_rejected,
|
| 224 |
+
}
|
| 225 |
+
return loss
|
| 226 |
+
|
| 227 |
+
def prediction_step(
|
| 228 |
+
self,
|
| 229 |
+
model: Union[PreTrainedModel, nn.Module],
|
| 230 |
+
inputs: Dict[str, Union[torch.Tensor, Any]],
|
| 231 |
+
prediction_loss_only: bool,
|
| 232 |
+
ignore_keys: Optional[List[str]] = None,
|
| 233 |
+
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]:
|
| 234 |
+
inputs = self._prepare_inputs(inputs)
|
| 235 |
+
if ignore_keys is None:
|
| 236 |
+
if hasattr(self.model, "config"):
|
| 237 |
+
ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", [])
|
| 238 |
+
else:
|
| 239 |
+
ignore_keys = []
|
| 240 |
+
|
| 241 |
+
with torch.no_grad():
|
| 242 |
+
loss, logits_dict = self.compute_loss(model, inputs, return_outputs=True)
|
| 243 |
+
|
| 244 |
+
if prediction_loss_only:
|
| 245 |
+
return (loss, None, None)
|
| 246 |
+
|
| 247 |
+
loss = loss.detach()
|
| 248 |
+
logits = tuple(v for k, v in logits_dict.items() if k not in ignore_keys)
|
| 249 |
+
logits = nested_detach(logits)
|
| 250 |
+
# Stack accepted against rejected, mean over logits
|
| 251 |
+
# and softmax to get preferences between accepted and rejected to sum to 1
|
| 252 |
+
logits = torch.stack(logits).mean(dim=2).softmax(dim=0).T
|
| 253 |
+
|
| 254 |
+
labels = torch.zeros(logits.shape[0])
|
| 255 |
+
labels = self._prepare_inputs(labels)
|
| 256 |
+
|
| 257 |
+
return loss, logits, labels
|
之前的代码版本/注意力用于sam的prompt的版本/MedEvalKit/LLaVA-NeXT/trl/trainer/sft_trainer.py
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import dataclasses
|
| 15 |
+
import inspect
|
| 16 |
+
import warnings
|
| 17 |
+
from functools import wraps
|
| 18 |
+
from typing import Callable, Dict, List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
from accelerate.state import PartialState
|
| 23 |
+
from datasets import Dataset
|
| 24 |
+
from datasets.arrow_writer import SchemaInferenceError
|
| 25 |
+
from datasets.builder import DatasetGenerationError
|
| 26 |
+
from transformers import (
|
| 27 |
+
AutoModelForCausalLM,
|
| 28 |
+
AutoTokenizer,
|
| 29 |
+
DataCollator,
|
| 30 |
+
DataCollatorForLanguageModeling,
|
| 31 |
+
PreTrainedModel,
|
| 32 |
+
PreTrainedTokenizerBase,
|
| 33 |
+
Trainer,
|
| 34 |
+
TrainingArguments,
|
| 35 |
+
)
|
| 36 |
+
from transformers.modeling_utils import unwrap_model
|
| 37 |
+
from transformers.trainer_callback import TrainerCallback
|
| 38 |
+
from transformers.trainer_utils import EvalPrediction
|
| 39 |
+
|
| 40 |
+
from ..extras.dataset_formatting import get_formatting_func_from_dataset
|
| 41 |
+
from ..import_utils import is_peft_available
|
| 42 |
+
from .utils import (
|
| 43 |
+
ConstantLengthDataset,
|
| 44 |
+
DataCollatorForCompletionOnlyLM,
|
| 45 |
+
neftune_post_forward_hook,
|
| 46 |
+
peft_module_casting_to_bf16,
|
| 47 |
+
trl_sanitze_kwargs_for_tagging,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if is_peft_available():
|
| 52 |
+
from peft import PeftConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class SFTTrainer(Trainer):
|
| 56 |
+
r"""
|
| 57 |
+
Class definition of the Supervised Finetuning Trainer (SFT Trainer).
|
| 58 |
+
This class is a wrapper around the `transformers.Trainer` class and inherits all of its attributes and methods.
|
| 59 |
+
The trainer takes care of properly initializing the PeftModel in case a user passes a `PeftConfig` object.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
model (Union[`transformers.PreTrainedModel`, `nn.Module`, `str`]):
|
| 63 |
+
The model to train, can be a `PreTrainedModel`, a `torch.nn.Module` or a string with the model name to
|
| 64 |
+
load from cache or download. The model can be also converted to a `PeftModel` if a `PeftConfig` object is
|
| 65 |
+
passed to the `peft_config` argument.
|
| 66 |
+
args (Optional[`transformers.TrainingArguments`]):
|
| 67 |
+
The arguments to tweak for training. Please refer to the official documentation of `transformers.TrainingArguments`
|
| 68 |
+
for more information.
|
| 69 |
+
data_collator (Optional[`transformers.DataCollator`]):
|
| 70 |
+
The data collator to use for training.
|
| 71 |
+
train_dataset (Optional[`datasets.Dataset`]):
|
| 72 |
+
The dataset to use for training. We recommend users to use `trl.trainer.ConstantLengthDataset` to create their dataset.
|
| 73 |
+
eval_dataset (Optional[Union[`datasets.Dataset`, Dict[`str`, `datasets.Dataset`]]]):
|
| 74 |
+
The dataset to use for evaluation. We recommend users to use `trl.trainer.ConstantLengthDataset` to create their dataset.
|
| 75 |
+
tokenizer (Optional[`transformers.PreTrainedTokenizer`]):
|
| 76 |
+
The tokenizer to use for training. If not specified, the tokenizer associated to the model will be used.
|
| 77 |
+
model_init (`Callable[[], transformers.PreTrainedModel]`):
|
| 78 |
+
The model initializer to use for training. If None is specified, the default model initializer will be used.
|
| 79 |
+
compute_metrics (`Callable[[transformers.EvalPrediction], Dict]`, *optional* defaults to None):
|
| 80 |
+
The function used to compute metrics during evaluation. It should return a dictionary mapping metric names to metric values.
|
| 81 |
+
If not specified, only the loss will be computed during evaluation.
|
| 82 |
+
callbacks (`List[transformers.TrainerCallback]`):
|
| 83 |
+
The callbacks to use for training.
|
| 84 |
+
optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
|
| 85 |
+
The optimizer and scheduler to use for training.
|
| 86 |
+
preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
|
| 87 |
+
The function to use to preprocess the logits before computing the metrics.
|
| 88 |
+
peft_config (`Optional[PeftConfig]`):
|
| 89 |
+
The PeftConfig object to use to initialize the PeftModel.
|
| 90 |
+
dataset_text_field (`Optional[str]`):
|
| 91 |
+
The name of the text field of the dataset, in case this is passed by a user, the trainer will automatically create a
|
| 92 |
+
`ConstantLengthDataset` based on the `dataset_text_field` argument.
|
| 93 |
+
formatting_func (`Optional[Callable]`):
|
| 94 |
+
The formatting function to be used for creating the `ConstantLengthDataset`.
|
| 95 |
+
max_seq_length (`Optional[int]`):
|
| 96 |
+
The maximum sequence length to use for the `ConstantLengthDataset` and for automatically creating the Dataset. Defaults to `512`.
|
| 97 |
+
infinite (`Optional[bool]`):
|
| 98 |
+
Whether to use an infinite dataset or not. Defaults to `False`.
|
| 99 |
+
num_of_sequences (`Optional[int]`):
|
| 100 |
+
The number of sequences to use for the `ConstantLengthDataset`. Defaults to `1024`.
|
| 101 |
+
chars_per_token (`Optional[float]`):
|
| 102 |
+
The number of characters per token to use for the `ConstantLengthDataset`. Defaults to `3.6`. You can check how this is computed in the
|
| 103 |
+
stack-llama example: https://github.com/huggingface/trl/blob/08f550674c553c36c51d1027613c29f14f3676a5/examples/stack_llama/scripts/supervised_finetuning.py#L53.
|
| 104 |
+
packing (`Optional[bool]`):
|
| 105 |
+
Used only in case `dataset_text_field` is passed. This argument is used by the `ConstantLengthDataset` to pack the sequences
|
| 106 |
+
of the dataset.
|
| 107 |
+
dataset_num_proc (`Optional[int]`):
|
| 108 |
+
The number of workers to use to tokenize the data. Only used when `packing=False`. Defaults to None.
|
| 109 |
+
dataset_batch_size (`int`):
|
| 110 |
+
The number of examples to tokenize per batch. If batch_size <= 0 or batch_size == None,
|
| 111 |
+
tokenize the full dataset as a single batch. Defaults to 1000.
|
| 112 |
+
neftune_noise_alpha (`Optional[float]`):
|
| 113 |
+
If not `None`, this will activate NEFTune noise embeddings. This has been proven to drastically improve model performances for instruction
|
| 114 |
+
fine-tuning. Check out the original paper here: https://arxiv.org/abs/2310.05914 and the original code here: https://github.com/neelsjain/NEFTune
|
| 115 |
+
model_init_kwargs: (`Optional[Dict]`, *optional*):
|
| 116 |
+
Dict of Optional kwargs to pass when instantiating the model from a string
|
| 117 |
+
dataset_kwargs: (`Optional[Dict]`, *optional*):
|
| 118 |
+
Dict of Optional kwargs to pass when creating packed or non-packed datasets
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
_tag_names = ["trl", "sft"]
|
| 122 |
+
|
| 123 |
+
def __init__(
|
| 124 |
+
self,
|
| 125 |
+
model: Union[PreTrainedModel, nn.Module, str] = None,
|
| 126 |
+
args: TrainingArguments = None,
|
| 127 |
+
data_collator: Optional[DataCollator] = None,
|
| 128 |
+
train_dataset: Optional[Dataset] = None,
|
| 129 |
+
eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None,
|
| 130 |
+
tokenizer: Optional[PreTrainedTokenizerBase] = None,
|
| 131 |
+
model_init: Optional[Callable[[], PreTrainedModel]] = None,
|
| 132 |
+
compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None,
|
| 133 |
+
callbacks: Optional[List[TrainerCallback]] = None,
|
| 134 |
+
optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
|
| 135 |
+
preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
|
| 136 |
+
peft_config: Optional["PeftConfig"] = None,
|
| 137 |
+
dataset_text_field: Optional[str] = None,
|
| 138 |
+
packing: Optional[bool] = False,
|
| 139 |
+
formatting_func: Optional[Callable] = None,
|
| 140 |
+
max_seq_length: Optional[int] = None,
|
| 141 |
+
infinite: Optional[bool] = None,
|
| 142 |
+
num_of_sequences: Optional[int] = 1024,
|
| 143 |
+
chars_per_token: Optional[float] = 3.6,
|
| 144 |
+
dataset_num_proc: Optional[int] = None,
|
| 145 |
+
dataset_batch_size: int = 1000,
|
| 146 |
+
neftune_noise_alpha: Optional[float] = None,
|
| 147 |
+
model_init_kwargs: Optional[Dict] = None,
|
| 148 |
+
dataset_kwargs: Optional[Dict] = None,
|
| 149 |
+
):
|
| 150 |
+
if model_init_kwargs is None:
|
| 151 |
+
model_init_kwargs = {}
|
| 152 |
+
elif not isinstance(model, str):
|
| 153 |
+
raise ValueError("You passed model_kwargs to the SFTTrainer. But your model is already instantiated.")
|
| 154 |
+
|
| 155 |
+
if infinite is not None:
|
| 156 |
+
warnings.warn("The `infinite` argument is deprecated and will be removed in a future version of TRL. Use `TrainingArguments.max_steps` or `TrainingArguments.num_train_epochs` instead to control training length.")
|
| 157 |
+
|
| 158 |
+
if isinstance(model, str):
|
| 159 |
+
warnings.warn("You passed a model_id to the SFTTrainer. This will automatically create an " "`AutoModelForCausalLM` or a `PeftModel` (if you passed a `peft_config`) for you.")
|
| 160 |
+
model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs)
|
| 161 |
+
|
| 162 |
+
if packing and data_collator is not None and isinstance(data_collator, DataCollatorForCompletionOnlyLM):
|
| 163 |
+
raise ValueError("You passed a `DataCollatorForCompletionOnlyLM` to the SFTTrainer. This is not compatible with the `packing` argument.")
|
| 164 |
+
|
| 165 |
+
if is_peft_available() and peft_config is not None:
|
| 166 |
+
if not isinstance(peft_config, PeftConfig):
|
| 167 |
+
raise ValueError("If you want to use the PeftModel, you need to pass a PeftConfig object to the SFTTrainer." f" and you passed a {type(peft_config)}.")
|
| 168 |
+
|
| 169 |
+
if not isinstance(model, PeftModel):
|
| 170 |
+
_support_gc_kwargs = hasattr(args, "gradient_checkpointing_kwargs") and "gradient_checkpointing_kwargs" in list(inspect.signature(prepare_model_for_kbit_training).parameters)
|
| 171 |
+
gradient_checkpointing_kwargs = getattr(args, "gradient_checkpointing_kwargs", None) or {}
|
| 172 |
+
if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False):
|
| 173 |
+
preprare_model_kwargs = {"use_gradient_checkpointing": getattr(args, "gradient_checkpointing", False)}
|
| 174 |
+
|
| 175 |
+
if _support_gc_kwargs:
|
| 176 |
+
preprare_model_kwargs["gradient_checkpointing_kwargs"] = gradient_checkpointing_kwargs
|
| 177 |
+
|
| 178 |
+
model = prepare_model_for_kbit_training(model, **preprare_model_kwargs)
|
| 179 |
+
|
| 180 |
+
if args is not None:
|
| 181 |
+
args = dataclasses.replace(args, gradient_checkpointing=False)
|
| 182 |
+
elif getattr(args, "gradient_checkpointing", False) and ("use_reentrant" not in gradient_checkpointing_kwargs or gradient_checkpointing_kwargs["use_reentrant"]):
|
| 183 |
+
# For backward compatibility with older versions of transformers
|
| 184 |
+
if hasattr(model, "enable_input_require_grads"):
|
| 185 |
+
model.enable_input_require_grads()
|
| 186 |
+
else:
|
| 187 |
+
|
| 188 |
+
def make_inputs_require_grad(module, input, output):
|
| 189 |
+
output.requires_grad_(True)
|
| 190 |
+
|
| 191 |
+
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
| 192 |
+
|
| 193 |
+
model = get_peft_model(model, peft_config)
|
| 194 |
+
if args.bf16 and getattr(model, "is_loaded_in_4bit", False):
|
| 195 |
+
peft_module_casting_to_bf16(model)
|
| 196 |
+
|
| 197 |
+
if tokenizer is None:
|
| 198 |
+
tokenizer = AutoTokenizer.from_pretrained(model.config._name_or_path)
|
| 199 |
+
if getattr(tokenizer, "pad_token", None) is None:
|
| 200 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 201 |
+
|
| 202 |
+
if max_seq_length is None:
|
| 203 |
+
# to overcome some issues with broken tokenizers
|
| 204 |
+
max_seq_length = min(tokenizer.model_max_length, 1024)
|
| 205 |
+
|
| 206 |
+
warnings.warn(f"You didn't pass a `max_seq_length` argument to the SFTTrainer, this will default to {max_seq_length}")
|
| 207 |
+
|
| 208 |
+
self.dataset_num_proc = dataset_num_proc
|
| 209 |
+
self.dataset_batch_size = dataset_batch_size
|
| 210 |
+
|
| 211 |
+
self._trainer_supports_neftune = hasattr(args, "neftune_noise_alpha")
|
| 212 |
+
|
| 213 |
+
if neftune_noise_alpha is not None and self._trainer_supports_neftune:
|
| 214 |
+
args.neftune_noise_alpha = neftune_noise_alpha
|
| 215 |
+
warnings.warn("You passed a `neftune_noise_alpha` argument to the SFTTrainer, the value you passed will override the one in the `TrainingArguments`.")
|
| 216 |
+
# self.neftune_noise_alpha is done at Trainer level
|
| 217 |
+
elif not self._trainer_supports_neftune:
|
| 218 |
+
self.neftune_noise_alpha = neftune_noise_alpha
|
| 219 |
+
|
| 220 |
+
if formatting_func is None and dataset_text_field is None:
|
| 221 |
+
# check if dataset has ChatML format or instruction format and is supported
|
| 222 |
+
# if not stays #None
|
| 223 |
+
formatting_func = get_formatting_func_from_dataset(train_dataset, tokenizer)
|
| 224 |
+
|
| 225 |
+
if not packing:
|
| 226 |
+
if dataset_text_field is None and formatting_func is None:
|
| 227 |
+
raise ValueError("You passed `packing=False` to the SFTTrainer, but you didn't pass a `dataset_text_field` or `formatting_func` argument.")
|
| 228 |
+
|
| 229 |
+
if data_collator is None:
|
| 230 |
+
data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
|
| 231 |
+
|
| 232 |
+
# Pre-process the datasets only once per node. The remaining processes will use the cache.
|
| 233 |
+
with PartialState().local_main_process_first():
|
| 234 |
+
if dataset_kwargs is None:
|
| 235 |
+
dataset_kwargs = {}
|
| 236 |
+
if train_dataset is not None:
|
| 237 |
+
train_dataset = self._prepare_dataset(
|
| 238 |
+
train_dataset,
|
| 239 |
+
tokenizer,
|
| 240 |
+
packing,
|
| 241 |
+
dataset_text_field,
|
| 242 |
+
max_seq_length,
|
| 243 |
+
formatting_func,
|
| 244 |
+
num_of_sequences,
|
| 245 |
+
chars_per_token,
|
| 246 |
+
remove_unused_columns=args.remove_unused_columns if args is not None else True,
|
| 247 |
+
**dataset_kwargs,
|
| 248 |
+
)
|
| 249 |
+
if eval_dataset is not None:
|
| 250 |
+
_multiple = isinstance(eval_dataset, dict)
|
| 251 |
+
_eval_datasets = eval_dataset if _multiple else {"singleton": eval_dataset}
|
| 252 |
+
for _eval_dataset_name, _eval_dataset in _eval_datasets.items():
|
| 253 |
+
_eval_datasets[_eval_dataset_name] = self._prepare_dataset(
|
| 254 |
+
_eval_dataset,
|
| 255 |
+
tokenizer,
|
| 256 |
+
packing,
|
| 257 |
+
dataset_text_field,
|
| 258 |
+
max_seq_length,
|
| 259 |
+
formatting_func,
|
| 260 |
+
num_of_sequences,
|
| 261 |
+
chars_per_token,
|
| 262 |
+
remove_unused_columns=args.remove_unused_columns if args is not None else True,
|
| 263 |
+
**dataset_kwargs,
|
| 264 |
+
)
|
| 265 |
+
if not _multiple:
|
| 266 |
+
eval_dataset = _eval_datasets["singleton"]
|
| 267 |
+
|
| 268 |
+
if tokenizer.padding_side is not None and tokenizer.padding_side != "right":
|
| 269 |
+
warnings.warn(
|
| 270 |
+
"You passed a tokenizer with `padding_side` not equal to `right` to the SFTTrainer. This might lead to some unexpected behaviour due to "
|
| 271 |
+
"overflow issues when training a model in half-precision. You might consider adding `tokenizer.padding_side = 'right'` to your code."
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
super().__init__(
|
| 275 |
+
model=model,
|
| 276 |
+
args=args,
|
| 277 |
+
data_collator=data_collator,
|
| 278 |
+
train_dataset=train_dataset,
|
| 279 |
+
eval_dataset=eval_dataset,
|
| 280 |
+
tokenizer=tokenizer,
|
| 281 |
+
model_init=model_init,
|
| 282 |
+
compute_metrics=compute_metrics,
|
| 283 |
+
callbacks=callbacks,
|
| 284 |
+
optimizers=optimizers,
|
| 285 |
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
if self.args.max_steps > 0 and packing:
|
| 289 |
+
warnings.warn("You passed `packing=True` to the SFTTrainer, and you are training your model with `max_steps` strategy. The dataset will be iterated until the `max_steps` are reached.")
|
| 290 |
+
self.train_dataset.infinite = True
|
| 291 |
+
elif self.args.max_steps == -1 and packing:
|
| 292 |
+
self.train_dataset.infinite = False
|
| 293 |
+
|
| 294 |
+
@wraps(Trainer.train)
|
| 295 |
+
def train(self, *args, **kwargs):
|
| 296 |
+
# Activate neftune right before training.
|
| 297 |
+
if self.neftune_noise_alpha is not None and not self._trainer_supports_neftune:
|
| 298 |
+
self.model = self._trl_activate_neftune(self.model)
|
| 299 |
+
|
| 300 |
+
output = super().train(*args, **kwargs)
|
| 301 |
+
|
| 302 |
+
# After training we make sure to retrieve back the original forward pass method
|
| 303 |
+
# for the embedding layer by removing the forward post hook.
|
| 304 |
+
if self.neftune_noise_alpha is not None and not self._trainer_supports_neftune:
|
| 305 |
+
unwrapped_model = unwrap_model(self.model)
|
| 306 |
+
if is_peft_available() and isinstance(unwrapped_model, PeftModel):
|
| 307 |
+
embeddings = unwrapped_model.base_model.model.get_input_embeddings()
|
| 308 |
+
else:
|
| 309 |
+
embeddings = unwrapped_model.get_input_embeddings()
|
| 310 |
+
|
| 311 |
+
self.neftune_hook_handle.remove()
|
| 312 |
+
del embeddings.neftune_noise_alpha
|
| 313 |
+
|
| 314 |
+
return output
|
| 315 |
+
|
| 316 |
+
@wraps(Trainer.push_to_hub)
|
| 317 |
+
def push_to_hub(self, commit_message: Optional[str] = "End of training", blocking: bool = True, **kwargs) -> str:
|
| 318 |
+
"""
|
| 319 |
+
Overwrite the `push_to_hub` method in order to force-add the tag "sft" when pushing the
|
| 320 |
+
model on the Hub. Please refer to `~transformers.Trainer.push_to_hub` for more details.
|
| 321 |
+
"""
|
| 322 |
+
kwargs = trl_sanitze_kwargs_for_tagging(model=self.model, tag_names=self._tag_names, kwargs=kwargs)
|
| 323 |
+
|
| 324 |
+
return super().push_to_hub(commit_message=commit_message, blocking=blocking, **kwargs)
|
| 325 |
+
|
| 326 |
+
def _prepare_dataset(
|
| 327 |
+
self,
|
| 328 |
+
dataset,
|
| 329 |
+
tokenizer,
|
| 330 |
+
packing,
|
| 331 |
+
dataset_text_field,
|
| 332 |
+
max_seq_length,
|
| 333 |
+
formatting_func,
|
| 334 |
+
num_of_sequences,
|
| 335 |
+
chars_per_token,
|
| 336 |
+
remove_unused_columns=True,
|
| 337 |
+
append_concat_token=True,
|
| 338 |
+
add_special_tokens=True,
|
| 339 |
+
):
|
| 340 |
+
if dataset is None:
|
| 341 |
+
raise ValueError("The dataset should not be None")
|
| 342 |
+
|
| 343 |
+
# check if torch dataset / dataloader and do nothing
|
| 344 |
+
if isinstance(dataset, (torch.utils.data.IterableDataset, torch.utils.data.Dataset, ConstantLengthDataset)):
|
| 345 |
+
return dataset
|
| 346 |
+
|
| 347 |
+
if not packing:
|
| 348 |
+
return self._prepare_non_packed_dataloader(
|
| 349 |
+
tokenizer,
|
| 350 |
+
dataset,
|
| 351 |
+
dataset_text_field,
|
| 352 |
+
max_seq_length,
|
| 353 |
+
formatting_func,
|
| 354 |
+
add_special_tokens,
|
| 355 |
+
remove_unused_columns,
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
else:
|
| 359 |
+
return self._prepare_packed_dataloader(
|
| 360 |
+
tokenizer,
|
| 361 |
+
dataset,
|
| 362 |
+
dataset_text_field,
|
| 363 |
+
max_seq_length,
|
| 364 |
+
num_of_sequences,
|
| 365 |
+
chars_per_token,
|
| 366 |
+
formatting_func,
|
| 367 |
+
append_concat_token,
|
| 368 |
+
add_special_tokens,
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
def _prepare_non_packed_dataloader(
|
| 372 |
+
self,
|
| 373 |
+
tokenizer,
|
| 374 |
+
dataset,
|
| 375 |
+
dataset_text_field,
|
| 376 |
+
max_seq_length,
|
| 377 |
+
formatting_func=None,
|
| 378 |
+
add_special_tokens=True,
|
| 379 |
+
remove_unused_columns=True,
|
| 380 |
+
):
|
| 381 |
+
use_formatting_func = formatting_func is not None and dataset_text_field is None
|
| 382 |
+
self._dataset_sanity_checked = False
|
| 383 |
+
|
| 384 |
+
# Inspired from: https://huggingface.co/learn/nlp-course/chapter7/6?fw=pt
|
| 385 |
+
def tokenize(element):
|
| 386 |
+
outputs = tokenizer(
|
| 387 |
+
element[dataset_text_field] if not use_formatting_func else formatting_func(element),
|
| 388 |
+
add_special_tokens=add_special_tokens,
|
| 389 |
+
truncation=True,
|
| 390 |
+
padding=False,
|
| 391 |
+
max_length=max_seq_length,
|
| 392 |
+
return_overflowing_tokens=False,
|
| 393 |
+
return_length=False,
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
if use_formatting_func and not self._dataset_sanity_checked:
|
| 397 |
+
if not isinstance(formatting_func(element), list):
|
| 398 |
+
raise ValueError("The `formatting_func` should return a list of processed strings since it can lead to silent bugs.")
|
| 399 |
+
else:
|
| 400 |
+
self._dataset_sanity_checked = True
|
| 401 |
+
|
| 402 |
+
return {"input_ids": outputs["input_ids"], "attention_mask": outputs["attention_mask"]}
|
| 403 |
+
|
| 404 |
+
signature_columns = ["input_ids", "labels", "attention_mask"]
|
| 405 |
+
|
| 406 |
+
extra_columns = list(set(dataset.column_names) - set(signature_columns))
|
| 407 |
+
|
| 408 |
+
if not remove_unused_columns and len(extra_columns) > 0:
|
| 409 |
+
warnings.warn(
|
| 410 |
+
"You passed `remove_unused_columns=False` on a non-packed dataset. This might create some issues with the default collator and yield to errors. If you want to "
|
| 411 |
+
f"inspect dataset other columns (in this case {extra_columns}), you can subclass `DataCollatorForLanguageModeling` in case you used the default collator and create your own data collator in order to inspect the unused dataset columns."
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
tokenized_dataset = dataset.map(
|
| 415 |
+
tokenize,
|
| 416 |
+
batched=True,
|
| 417 |
+
remove_columns=dataset.column_names if remove_unused_columns else None,
|
| 418 |
+
num_proc=self.dataset_num_proc,
|
| 419 |
+
batch_size=self.dataset_batch_size,
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
return tokenized_dataset
|
| 423 |
+
|
| 424 |
+
def _prepare_packed_dataloader(
|
| 425 |
+
self,
|
| 426 |
+
tokenizer,
|
| 427 |
+
dataset,
|
| 428 |
+
dataset_text_field,
|
| 429 |
+
max_seq_length,
|
| 430 |
+
num_of_sequences,
|
| 431 |
+
chars_per_token,
|
| 432 |
+
formatting_func=None,
|
| 433 |
+
append_concat_token=True,
|
| 434 |
+
add_special_tokens=True,
|
| 435 |
+
):
|
| 436 |
+
if dataset_text_field is not None or formatting_func is not None:
|
| 437 |
+
if tokenizer is None:
|
| 438 |
+
raise ValueError("You need to pass a tokenizer when using `dataset_text_field` with `SFTTrainer`.")
|
| 439 |
+
|
| 440 |
+
constant_length_iterator = ConstantLengthDataset(
|
| 441 |
+
tokenizer,
|
| 442 |
+
dataset,
|
| 443 |
+
dataset_text_field=dataset_text_field,
|
| 444 |
+
formatting_func=formatting_func,
|
| 445 |
+
seq_length=max_seq_length,
|
| 446 |
+
infinite=False,
|
| 447 |
+
num_of_sequences=num_of_sequences,
|
| 448 |
+
chars_per_token=chars_per_token,
|
| 449 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 450 |
+
append_concat_token=append_concat_token,
|
| 451 |
+
add_special_tokens=add_special_tokens,
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
def data_generator(constant_length_iterator):
|
| 455 |
+
for i in constant_length_iterator:
|
| 456 |
+
yield i
|
| 457 |
+
|
| 458 |
+
try:
|
| 459 |
+
packed_dataset = Dataset.from_generator(data_generator, gen_kwargs={"constant_length_iterator": constant_length_iterator})
|
| 460 |
+
except (DatasetGenerationError, SchemaInferenceError):
|
| 461 |
+
raise ValueError("Error occurred while packing the dataset. Make sure that your dataset has enough samples to at least yield one packed sequence.")
|
| 462 |
+
return packed_dataset
|
| 463 |
+
else:
|
| 464 |
+
raise ValueError("You need to pass a `dataset_text_field` or `formatting_func` argument to the SFTTrainer if you want to use the `ConstantLengthDataset`.")
|
| 465 |
+
|
| 466 |
+
def _trl_activate_neftune(self, model):
|
| 467 |
+
r"""
|
| 468 |
+
Activates the neftune as presented in this code: https://github.com/neelsjain/NEFTune and paper: https://arxiv.org/abs/2310.05914
|
| 469 |
+
Since in transformers Trainer we do have an `_activate_neftune` method, we need to rename this method to avoid conflicts.
|
| 470 |
+
"""
|
| 471 |
+
unwrapped_model = unwrap_model(model)
|
| 472 |
+
if is_peft_available() and isinstance(unwrapped_model, PeftModel):
|
| 473 |
+
embeddings = unwrapped_model.base_model.model.get_input_embeddings()
|
| 474 |
+
else:
|
| 475 |
+
embeddings = unwrapped_model.get_input_embeddings()
|
| 476 |
+
|
| 477 |
+
embeddings.neftune_noise_alpha = self.neftune_noise_alpha
|
| 478 |
+
hook_handle = embeddings.register_forward_hook(neftune_post_forward_hook)
|
| 479 |
+
self.neftune_hook_handle = hook_handle
|
| 480 |
+
return model
|