Upload folder using huggingface_hub (part 12)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/models/modeling_sd_base.py +644 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/models/modeling_value_head.py +429 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/models/utils.py +101 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/__init__.py +45 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/base.py +46 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/ddpo_config.py +136 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/ddpo_trainer.py +628 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/dpo_trainer.py +1309 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/iterative_sft_trainer.py +366 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/model_config.py +100 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/ppo_config.py +178 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/ppo_trainer.py +1454 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/reward_config.py +38 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/reward_trainer.py +274 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/sft_trainer.py +512 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/utils.py +724 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/unit_test_utils.py +36 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils.py +144 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils/__init__.py +1 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils/distributed.py +48 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils/io.py +162 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils/merge_lora_weights_and_save_hf_model.py +105 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils/tokenizer.py +165 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils/utils.py +143 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/__init__.py +7 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids.py +825 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_bench.py +47 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_cleanup.py +94 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_dir.py +21 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_dl.py +156 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_index.py +319 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_lru.py +64 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_mmtar.py +151 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_specs.py +175 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_tar.py +81 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000850_n.mp4 +3 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000850_r.mp4 +3 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000852_m.mp4 +3 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000855_i.mp4 +3 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000855_m.mp4 +3 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000863_f.mp4 +3 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000872_e.mp4 +3 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000876_c.mp4 +3 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000892_e.mp4 +3 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/mllm_few_shot_egs.json +137 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_q_align/q_align/__init__.py +3 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_q_align/q_align/constants.py +9 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_q_align/q_align/conversation.py +301 -0
- video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_q_align/q_align/evaluate/__init__.py +1 -0
.gitattributes
CHANGED
|
@@ -63,3 +63,4 @@ video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/ViTDetector/data
|
|
| 63 |
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/ViTDetector/lvis/lvis_v1_minival_inserted_image_name.json filter=lfs diff=lfs merge=lfs -text
|
| 64 |
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/ViTDetector/third_party/YOLO-World/data/coco/lvis/lvis_v1_minival_inserted_image_name.json filter=lfs diff=lfs merge=lfs -text
|
| 65 |
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/YOLO-World/data/coco/lvis/lvis_v1_minival_inserted_image_name.json filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 63 |
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/ViTDetector/lvis/lvis_v1_minival_inserted_image_name.json filter=lfs diff=lfs merge=lfs -text
|
| 64 |
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/ViTDetector/third_party/YOLO-World/data/coco/lvis/lvis_v1_minival_inserted_image_name.json filter=lfs diff=lfs merge=lfs -text
|
| 65 |
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/YOLO-World/data/coco/lvis/lvis_v1_minival_inserted_image_name.json filter=lfs diff=lfs merge=lfs -text
|
| 66 |
+
video_gen_14d/third_party/Wan2.1/examples/i2v_input.JPG filter=lfs diff=lfs merge=lfs -text
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/models/modeling_sd_base.py
ADDED
|
@@ -0,0 +1,644 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
if is_peft_available():
|
| 31 |
+
from peft import LoraConfig
|
| 32 |
+
from peft.utils import get_peft_model_state_dict
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class DDPOPipelineOutput:
|
| 37 |
+
"""
|
| 38 |
+
Output class for the diffusers pipeline to be finetuned with the DDPO trainer
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
images (`torch.Tensor`):
|
| 42 |
+
The generated images.
|
| 43 |
+
latents (`List[torch.Tensor]`):
|
| 44 |
+
The latents used to generate the images.
|
| 45 |
+
log_probs (`List[torch.Tensor]`):
|
| 46 |
+
The log probabilities of the latents.
|
| 47 |
+
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
images: torch.Tensor
|
| 51 |
+
latents: torch.Tensor
|
| 52 |
+
log_probs: torch.Tensor
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass
|
| 56 |
+
class DDPOSchedulerOutput:
|
| 57 |
+
"""
|
| 58 |
+
Output class for the diffusers scheduler to be finetuned with the DDPO trainer
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
latents (`torch.Tensor`):
|
| 62 |
+
Predicted sample at the previous timestep. Shape: `(batch_size, num_channels, height, width)`
|
| 63 |
+
log_probs (`torch.Tensor`):
|
| 64 |
+
Log probability of the above mentioned sample. Shape: `(batch_size)`
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
latents: torch.Tensor
|
| 68 |
+
log_probs: torch.Tensor
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class DDPOStableDiffusionPipeline:
|
| 72 |
+
"""
|
| 73 |
+
Main class for the diffusers pipeline to be finetuned with the DDPO trainer
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
def __call__(self, *args, **kwargs) -> DDPOPipelineOutput:
|
| 77 |
+
raise NotImplementedError
|
| 78 |
+
|
| 79 |
+
def scheduler_step(self, *args, **kwargs) -> DDPOSchedulerOutput:
|
| 80 |
+
raise NotImplementedError
|
| 81 |
+
|
| 82 |
+
@property
|
| 83 |
+
def unet(self):
|
| 84 |
+
"""
|
| 85 |
+
Returns the 2d U-Net model used for diffusion.
|
| 86 |
+
"""
|
| 87 |
+
raise NotImplementedError
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def vae(self):
|
| 91 |
+
"""
|
| 92 |
+
Returns the Variational Autoencoder model used from mapping images to and from the latent space
|
| 93 |
+
"""
|
| 94 |
+
raise NotImplementedError
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def tokenizer(self):
|
| 98 |
+
"""
|
| 99 |
+
Returns the tokenizer used for tokenizing text inputs
|
| 100 |
+
"""
|
| 101 |
+
raise NotImplementedError
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def scheduler(self):
|
| 105 |
+
"""
|
| 106 |
+
Returns the scheduler associated with the pipeline used for the diffusion process
|
| 107 |
+
"""
|
| 108 |
+
raise NotImplementedError
|
| 109 |
+
|
| 110 |
+
@property
|
| 111 |
+
def text_encoder(self):
|
| 112 |
+
"""
|
| 113 |
+
Returns the text encoder used for encoding text inputs
|
| 114 |
+
"""
|
| 115 |
+
raise NotImplementedError
|
| 116 |
+
|
| 117 |
+
@property
|
| 118 |
+
def autocast(self):
|
| 119 |
+
"""
|
| 120 |
+
Returns the autocast context manager
|
| 121 |
+
"""
|
| 122 |
+
raise NotImplementedError
|
| 123 |
+
|
| 124 |
+
def set_progress_bar_config(self, *args, **kwargs):
|
| 125 |
+
"""
|
| 126 |
+
Sets the progress bar config for the pipeline
|
| 127 |
+
"""
|
| 128 |
+
raise NotImplementedError
|
| 129 |
+
|
| 130 |
+
def save_pretrained(self, *args, **kwargs):
|
| 131 |
+
"""
|
| 132 |
+
Saves all of the model weights
|
| 133 |
+
"""
|
| 134 |
+
raise NotImplementedError
|
| 135 |
+
|
| 136 |
+
def get_trainable_layers(self, *args, **kwargs):
|
| 137 |
+
"""
|
| 138 |
+
Returns the trainable parameters of the pipeline
|
| 139 |
+
"""
|
| 140 |
+
raise NotImplementedError
|
| 141 |
+
|
| 142 |
+
def save_checkpoint(self, *args, **kwargs):
|
| 143 |
+
"""
|
| 144 |
+
Light wrapper around accelerate's register_save_state_pre_hook which is run before saving state
|
| 145 |
+
"""
|
| 146 |
+
raise NotImplementedError
|
| 147 |
+
|
| 148 |
+
def load_checkpoint(self, *args, **kwargs):
|
| 149 |
+
"""
|
| 150 |
+
Light wrapper around accelerate's register_lad_state_pre_hook which is run before loading state
|
| 151 |
+
"""
|
| 152 |
+
raise NotImplementedError
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _left_broadcast(input_tensor, shape):
|
| 156 |
+
"""
|
| 157 |
+
As opposed to the default direction of broadcasting (right to left), this function broadcasts
|
| 158 |
+
from left to right
|
| 159 |
+
Args:
|
| 160 |
+
input_tensor (`torch.FloatTensor`): is the tensor to broadcast
|
| 161 |
+
shape (`Tuple[int]`): is the shape to broadcast to
|
| 162 |
+
"""
|
| 163 |
+
input_ndim = input_tensor.ndim
|
| 164 |
+
if input_ndim > len(shape):
|
| 165 |
+
raise ValueError(
|
| 166 |
+
"The number of dimensions of the tensor to broadcast cannot be greater than the length of the shape to broadcast to"
|
| 167 |
+
)
|
| 168 |
+
return input_tensor.reshape(input_tensor.shape + (1,) * (len(shape) - input_ndim)).broadcast_to(shape)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _get_variance(self, timestep, prev_timestep):
|
| 172 |
+
alpha_prod_t = torch.gather(self.alphas_cumprod, 0, timestep.cpu()).to(timestep.device)
|
| 173 |
+
alpha_prod_t_prev = torch.where(
|
| 174 |
+
prev_timestep.cpu() >= 0,
|
| 175 |
+
self.alphas_cumprod.gather(0, prev_timestep.cpu()),
|
| 176 |
+
self.final_alpha_cumprod,
|
| 177 |
+
).to(timestep.device)
|
| 178 |
+
beta_prod_t = 1 - alpha_prod_t
|
| 179 |
+
beta_prod_t_prev = 1 - alpha_prod_t_prev
|
| 180 |
+
|
| 181 |
+
variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)
|
| 182 |
+
|
| 183 |
+
return variance
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def scheduler_step(
|
| 187 |
+
self,
|
| 188 |
+
model_output: torch.FloatTensor,
|
| 189 |
+
timestep: int,
|
| 190 |
+
sample: torch.FloatTensor,
|
| 191 |
+
eta: float = 0.0,
|
| 192 |
+
use_clipped_model_output: bool = False,
|
| 193 |
+
generator=None,
|
| 194 |
+
prev_sample: Optional[torch.FloatTensor] = None,
|
| 195 |
+
) -> DDPOSchedulerOutput:
|
| 196 |
+
"""
|
| 197 |
+
|
| 198 |
+
Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
|
| 199 |
+
process from the learned model outputs (most often the predicted noise).
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
model_output (`torch.FloatTensor`): direct output from learned diffusion model.
|
| 203 |
+
timestep (`int`): current discrete timestep in the diffusion chain.
|
| 204 |
+
sample (`torch.FloatTensor`):
|
| 205 |
+
current instance of sample being created by diffusion process.
|
| 206 |
+
eta (`float`): weight of noise for added noise in diffusion step.
|
| 207 |
+
use_clipped_model_output (`bool`): if `True`, compute "corrected" `model_output` from the clipped
|
| 208 |
+
predicted original sample. Necessary because predicted original sample is clipped to [-1, 1] when
|
| 209 |
+
`self.config.clip_sample` is `True`. If no clipping has happened, "corrected" `model_output` would
|
| 210 |
+
coincide with the one provided as input and `use_clipped_model_output` will have not effect.
|
| 211 |
+
generator: random number generator.
|
| 212 |
+
variance_noise (`torch.FloatTensor`): instead of generating noise for the variance using `generator`, we
|
| 213 |
+
can directly provide the noise for the variance itself. This is useful for methods such as
|
| 214 |
+
CycleDiffusion. (https://arxiv.org/abs/2210.05559)
|
| 215 |
+
|
| 216 |
+
Returns:
|
| 217 |
+
`DDPOSchedulerOutput`: the predicted sample at the previous timestep and the log probability of the sample
|
| 218 |
+
"""
|
| 219 |
+
|
| 220 |
+
if self.num_inference_steps is None:
|
| 221 |
+
raise ValueError(
|
| 222 |
+
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
# See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
|
| 226 |
+
# Ideally, read DDIM paper in-detail understanding
|
| 227 |
+
|
| 228 |
+
# Notation (<variable name> -> <name in paper>
|
| 229 |
+
# - pred_noise_t -> e_theta(x_t, t)
|
| 230 |
+
# - pred_original_sample -> f_theta(x_t, t) or x_0
|
| 231 |
+
# - std_dev_t -> sigma_t
|
| 232 |
+
# - eta -> η
|
| 233 |
+
# - pred_sample_direction -> "direction pointing to x_t"
|
| 234 |
+
# - pred_prev_sample -> "x_t-1"
|
| 235 |
+
|
| 236 |
+
# 1. get previous step value (=t-1)
|
| 237 |
+
prev_timestep = timestep - self.config.num_train_timesteps // self.num_inference_steps
|
| 238 |
+
# to prevent OOB on gather
|
| 239 |
+
prev_timestep = torch.clamp(prev_timestep, 0, self.config.num_train_timesteps - 1)
|
| 240 |
+
|
| 241 |
+
# 2. compute alphas, betas
|
| 242 |
+
alpha_prod_t = self.alphas_cumprod.gather(0, timestep.cpu())
|
| 243 |
+
alpha_prod_t_prev = torch.where(
|
| 244 |
+
prev_timestep.cpu() >= 0,
|
| 245 |
+
self.alphas_cumprod.gather(0, prev_timestep.cpu()),
|
| 246 |
+
self.final_alpha_cumprod,
|
| 247 |
+
)
|
| 248 |
+
alpha_prod_t = _left_broadcast(alpha_prod_t, sample.shape).to(sample.device)
|
| 249 |
+
alpha_prod_t_prev = _left_broadcast(alpha_prod_t_prev, sample.shape).to(sample.device)
|
| 250 |
+
|
| 251 |
+
beta_prod_t = 1 - alpha_prod_t
|
| 252 |
+
|
| 253 |
+
# 3. compute predicted original sample from predicted noise also called
|
| 254 |
+
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
|
| 255 |
+
if self.config.prediction_type == "epsilon":
|
| 256 |
+
pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
|
| 257 |
+
pred_epsilon = model_output
|
| 258 |
+
elif self.config.prediction_type == "sample":
|
| 259 |
+
pred_original_sample = model_output
|
| 260 |
+
pred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)
|
| 261 |
+
elif self.config.prediction_type == "v_prediction":
|
| 262 |
+
pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
|
| 263 |
+
pred_epsilon = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
|
| 264 |
+
else:
|
| 265 |
+
raise ValueError(
|
| 266 |
+
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
|
| 267 |
+
" `v_prediction`"
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# 4. Clip or threshold "predicted x_0"
|
| 271 |
+
if self.config.thresholding:
|
| 272 |
+
pred_original_sample = self._threshold_sample(pred_original_sample)
|
| 273 |
+
elif self.config.clip_sample:
|
| 274 |
+
pred_original_sample = pred_original_sample.clamp(-self.config.clip_sample_range, self.config.clip_sample_range)
|
| 275 |
+
|
| 276 |
+
# 5. compute variance: "sigma_t(η)" -> see formula (16)
|
| 277 |
+
# σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
|
| 278 |
+
variance = _get_variance(self, timestep, prev_timestep)
|
| 279 |
+
std_dev_t = eta * variance ** (0.5)
|
| 280 |
+
std_dev_t = _left_broadcast(std_dev_t, sample.shape).to(sample.device)
|
| 281 |
+
|
| 282 |
+
if use_clipped_model_output:
|
| 283 |
+
# the pred_epsilon is always re-derived from the clipped x_0 in Glide
|
| 284 |
+
pred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)
|
| 285 |
+
|
| 286 |
+
# 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
|
| 287 |
+
pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * pred_epsilon
|
| 288 |
+
|
| 289 |
+
# 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
|
| 290 |
+
prev_sample_mean = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
|
| 291 |
+
|
| 292 |
+
if prev_sample is not None and generator is not None:
|
| 293 |
+
raise ValueError(
|
| 294 |
+
"Cannot pass both generator and prev_sample. Please make sure that either `generator` or"
|
| 295 |
+
" `prev_sample` stays `None`."
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
if prev_sample is None:
|
| 299 |
+
variance_noise = randn_tensor(
|
| 300 |
+
model_output.shape,
|
| 301 |
+
generator=generator,
|
| 302 |
+
device=model_output.device,
|
| 303 |
+
dtype=model_output.dtype,
|
| 304 |
+
)
|
| 305 |
+
prev_sample = prev_sample_mean + std_dev_t * variance_noise
|
| 306 |
+
|
| 307 |
+
# log prob of prev_sample given prev_sample_mean and std_dev_t
|
| 308 |
+
log_prob = (
|
| 309 |
+
-((prev_sample.detach() - prev_sample_mean) ** 2) / (2 * (std_dev_t**2))
|
| 310 |
+
- torch.log(std_dev_t)
|
| 311 |
+
- torch.log(torch.sqrt(2 * torch.as_tensor(np.pi)))
|
| 312 |
+
)
|
| 313 |
+
# mean along all but batch dimension
|
| 314 |
+
log_prob = log_prob.mean(dim=tuple(range(1, log_prob.ndim)))
|
| 315 |
+
|
| 316 |
+
return DDPOSchedulerOutput(prev_sample.type(sample.dtype), log_prob)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
# 1. The output type for call is different as the logprobs are now returned
|
| 320 |
+
# 2. An extra method called `scheduler_step` is added which is used to constraint the scheduler output
|
| 321 |
+
@torch.no_grad()
|
| 322 |
+
def pipeline_step(
|
| 323 |
+
self,
|
| 324 |
+
prompt: Optional[Union[str, List[str]]] = None,
|
| 325 |
+
height: Optional[int] = None,
|
| 326 |
+
width: Optional[int] = None,
|
| 327 |
+
num_inference_steps: int = 50,
|
| 328 |
+
guidance_scale: float = 7.5,
|
| 329 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 330 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 331 |
+
eta: float = 0.0,
|
| 332 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 333 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 334 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 335 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 336 |
+
output_type: Optional[str] = "pil",
|
| 337 |
+
return_dict: bool = True,
|
| 338 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 339 |
+
callback_steps: int = 1,
|
| 340 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 341 |
+
guidance_rescale: float = 0.0,
|
| 342 |
+
):
|
| 343 |
+
r"""
|
| 344 |
+
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.
|
| 345 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 346 |
+
The width in pixels of the generated image.
|
| 347 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 348 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 349 |
+
expense of slower inference.
|
| 350 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 351 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
| 352 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
| 353 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
| 354 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
| 355 |
+
usually at the expense of lower image quality.
|
| 356 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 357 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 358 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 359 |
+
less than `1`).
|
| 360 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 361 |
+
The number of images to generate per prompt.
|
| 362 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 363 |
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
| 364 |
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
| 365 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 366 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 367 |
+
to make generation deterministic.
|
| 368 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 369 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
| 370 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 371 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
| 372 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 373 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 374 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 375 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 376 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 377 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 378 |
+
argument.
|
| 379 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 380 |
+
The output format of the generate image. Choose between
|
| 381 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 382 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 383 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 384 |
+
plain tuple.
|
| 385 |
+
callback (`Callable`, *optional*):
|
| 386 |
+
A function that will be called every `callback_steps` steps during inference. The function will be
|
| 387 |
+
called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 388 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 389 |
+
The frequency at which the `callback` function will be called. If not specified, the callback will be
|
| 390 |
+
called at every step.
|
| 391 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 392 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 393 |
+
`self.processor` in
|
| 394 |
+
[diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
|
| 395 |
+
guidance_rescale (`float`, *optional*, defaults to 0.7):
|
| 396 |
+
Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
|
| 397 |
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
|
| 398 |
+
[Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
|
| 399 |
+
Guidance rescale factor should fix overexposure when using zero terminal SNR.
|
| 400 |
+
|
| 401 |
+
Examples:
|
| 402 |
+
|
| 403 |
+
Returns:
|
| 404 |
+
`DDPOPipelineOutput`: The generated image, the predicted latents used to generate the image and the associated log probabilities
|
| 405 |
+
"""
|
| 406 |
+
# 0. Default height and width to unet
|
| 407 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 408 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 409 |
+
|
| 410 |
+
# 1. Check inputs. Raise error if not correct
|
| 411 |
+
self.check_inputs(
|
| 412 |
+
prompt,
|
| 413 |
+
height,
|
| 414 |
+
width,
|
| 415 |
+
callback_steps,
|
| 416 |
+
negative_prompt,
|
| 417 |
+
prompt_embeds,
|
| 418 |
+
negative_prompt_embeds,
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
# 2. Define call parameters
|
| 422 |
+
if prompt is not None and isinstance(prompt, str):
|
| 423 |
+
batch_size = 1
|
| 424 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 425 |
+
batch_size = len(prompt)
|
| 426 |
+
else:
|
| 427 |
+
batch_size = prompt_embeds.shape[0]
|
| 428 |
+
|
| 429 |
+
device = self._execution_device
|
| 430 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 431 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 432 |
+
# corresponds to doing no classifier free guidance.
|
| 433 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 434 |
+
|
| 435 |
+
# 3. Encode input prompt
|
| 436 |
+
text_encoder_lora_scale = cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
| 437 |
+
prompt_embeds = self._encode_prompt(
|
| 438 |
+
prompt,
|
| 439 |
+
device,
|
| 440 |
+
num_images_per_prompt,
|
| 441 |
+
do_classifier_free_guidance,
|
| 442 |
+
negative_prompt,
|
| 443 |
+
prompt_embeds=prompt_embeds,
|
| 444 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 445 |
+
lora_scale=text_encoder_lora_scale,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
# 4. Prepare timesteps
|
| 449 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 450 |
+
timesteps = self.scheduler.timesteps
|
| 451 |
+
|
| 452 |
+
# 5. Prepare latent variables
|
| 453 |
+
num_channels_latents = self.unet.config.in_channels
|
| 454 |
+
latents = self.prepare_latents(
|
| 455 |
+
batch_size * num_images_per_prompt,
|
| 456 |
+
num_channels_latents,
|
| 457 |
+
height,
|
| 458 |
+
width,
|
| 459 |
+
prompt_embeds.dtype,
|
| 460 |
+
device,
|
| 461 |
+
generator,
|
| 462 |
+
latents,
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
# 6. Denoising loop
|
| 466 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 467 |
+
all_latents = [latents]
|
| 468 |
+
all_log_probs = []
|
| 469 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 470 |
+
for i, t in enumerate(timesteps):
|
| 471 |
+
# expand the latents if we are doing classifier free guidance
|
| 472 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 473 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 474 |
+
|
| 475 |
+
# predict the noise residual
|
| 476 |
+
noise_pred = self.unet(
|
| 477 |
+
latent_model_input,
|
| 478 |
+
t,
|
| 479 |
+
encoder_hidden_states=prompt_embeds,
|
| 480 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
| 481 |
+
return_dict=False,
|
| 482 |
+
)[0]
|
| 483 |
+
|
| 484 |
+
# perform guidance
|
| 485 |
+
if do_classifier_free_guidance:
|
| 486 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 487 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 488 |
+
|
| 489 |
+
if do_classifier_free_guidance and guidance_rescale > 0.0:
|
| 490 |
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
| 491 |
+
noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
|
| 492 |
+
|
| 493 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 494 |
+
scheduler_output = scheduler_step(self.scheduler, noise_pred, t, latents, eta)
|
| 495 |
+
latents = scheduler_output.latents
|
| 496 |
+
log_prob = scheduler_output.log_probs
|
| 497 |
+
|
| 498 |
+
all_latents.append(latents)
|
| 499 |
+
all_log_probs.append(log_prob)
|
| 500 |
+
|
| 501 |
+
# call the callback, if provided
|
| 502 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 503 |
+
progress_bar.update()
|
| 504 |
+
if callback is not None and i % callback_steps == 0:
|
| 505 |
+
callback(i, t, latents)
|
| 506 |
+
|
| 507 |
+
if not output_type == "latent":
|
| 508 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
| 509 |
+
image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
|
| 510 |
+
else:
|
| 511 |
+
image = latents
|
| 512 |
+
has_nsfw_concept = None
|
| 513 |
+
|
| 514 |
+
if has_nsfw_concept is None:
|
| 515 |
+
do_denormalize = [True] * image.shape[0]
|
| 516 |
+
else:
|
| 517 |
+
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
| 518 |
+
|
| 519 |
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
| 520 |
+
|
| 521 |
+
# Offload last model to CPU
|
| 522 |
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
| 523 |
+
self.final_offload_hook.offload()
|
| 524 |
+
|
| 525 |
+
return DDPOPipelineOutput(image, all_latents, all_log_probs)
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
class DefaultDDPOStableDiffusionPipeline(DDPOStableDiffusionPipeline):
|
| 529 |
+
def __init__(self, pretrained_model_name: str, *, pretrained_model_revision: str = "main", use_lora: bool = True):
|
| 530 |
+
self.sd_pipeline = StableDiffusionPipeline.from_pretrained(
|
| 531 |
+
pretrained_model_name, revision=pretrained_model_revision
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
self.use_lora = use_lora
|
| 535 |
+
self.pretrained_model = pretrained_model_name
|
| 536 |
+
self.pretrained_revision = pretrained_model_revision
|
| 537 |
+
|
| 538 |
+
try:
|
| 539 |
+
self.sd_pipeline.load_lora_weights(
|
| 540 |
+
pretrained_model_name,
|
| 541 |
+
weight_name="pytorch_lora_weights.safetensors",
|
| 542 |
+
revision=pretrained_model_revision,
|
| 543 |
+
)
|
| 544 |
+
self.use_lora = True
|
| 545 |
+
except OSError:
|
| 546 |
+
if use_lora:
|
| 547 |
+
warnings.warn(
|
| 548 |
+
"If you are aware that the pretrained model has no lora weights to it, ignore this message. "
|
| 549 |
+
"Otherwise please check the if `pytorch_lora_weights.safetensors` exists in the model folder."
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
+
self.sd_pipeline.scheduler = DDIMScheduler.from_config(self.sd_pipeline.scheduler.config)
|
| 553 |
+
self.sd_pipeline.safety_checker = None
|
| 554 |
+
|
| 555 |
+
# memory optimization
|
| 556 |
+
self.sd_pipeline.vae.requires_grad_(False)
|
| 557 |
+
self.sd_pipeline.text_encoder.requires_grad_(False)
|
| 558 |
+
self.sd_pipeline.unet.requires_grad_(not self.use_lora)
|
| 559 |
+
|
| 560 |
+
def __call__(self, *args, **kwargs) -> DDPOPipelineOutput:
|
| 561 |
+
return pipeline_step(self.sd_pipeline, *args, **kwargs)
|
| 562 |
+
|
| 563 |
+
def scheduler_step(self, *args, **kwargs) -> DDPOSchedulerOutput:
|
| 564 |
+
return scheduler_step(self.sd_pipeline.scheduler, *args, **kwargs)
|
| 565 |
+
|
| 566 |
+
@property
|
| 567 |
+
def unet(self):
|
| 568 |
+
return self.sd_pipeline.unet
|
| 569 |
+
|
| 570 |
+
@property
|
| 571 |
+
def vae(self):
|
| 572 |
+
return self.sd_pipeline.vae
|
| 573 |
+
|
| 574 |
+
@property
|
| 575 |
+
def tokenizer(self):
|
| 576 |
+
return self.sd_pipeline.tokenizer
|
| 577 |
+
|
| 578 |
+
@property
|
| 579 |
+
def scheduler(self):
|
| 580 |
+
return self.sd_pipeline.scheduler
|
| 581 |
+
|
| 582 |
+
@property
|
| 583 |
+
def text_encoder(self):
|
| 584 |
+
return self.sd_pipeline.text_encoder
|
| 585 |
+
|
| 586 |
+
@property
|
| 587 |
+
def autocast(self):
|
| 588 |
+
return contextlib.nullcontext if self.use_lora else None
|
| 589 |
+
|
| 590 |
+
def save_pretrained(self, output_dir):
|
| 591 |
+
if self.use_lora:
|
| 592 |
+
state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(self.sd_pipeline.unet))
|
| 593 |
+
self.sd_pipeline.save_lora_weights(save_directory=output_dir, unet_lora_layers=state_dict)
|
| 594 |
+
self.sd_pipeline.save_pretrained(output_dir)
|
| 595 |
+
|
| 596 |
+
def set_progress_bar_config(self, *args, **kwargs):
|
| 597 |
+
self.sd_pipeline.set_progress_bar_config(*args, **kwargs)
|
| 598 |
+
|
| 599 |
+
def get_trainable_layers(self):
|
| 600 |
+
if self.use_lora:
|
| 601 |
+
lora_config = LoraConfig(
|
| 602 |
+
r=4,
|
| 603 |
+
lora_alpha=4,
|
| 604 |
+
init_lora_weights="gaussian",
|
| 605 |
+
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
|
| 606 |
+
)
|
| 607 |
+
self.sd_pipeline.unet.add_adapter(lora_config)
|
| 608 |
+
|
| 609 |
+
# To avoid accelerate unscaling problems in FP16.
|
| 610 |
+
for param in self.sd_pipeline.unet.parameters():
|
| 611 |
+
# only upcast trainable parameters (LoRA) into fp32
|
| 612 |
+
if param.requires_grad:
|
| 613 |
+
param.data = param.to(torch.float32)
|
| 614 |
+
return self.sd_pipeline.unet
|
| 615 |
+
else:
|
| 616 |
+
return self.sd_pipeline.unet
|
| 617 |
+
|
| 618 |
+
def save_checkpoint(self, models, weights, output_dir):
|
| 619 |
+
if len(models) != 1:
|
| 620 |
+
raise ValueError("Given how the trainable params were set, this should be of length 1")
|
| 621 |
+
if self.use_lora and hasattr(models[0], "peft_config") and getattr(models[0], "peft_config", None) is not None:
|
| 622 |
+
state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(models[0]))
|
| 623 |
+
self.sd_pipeline.save_lora_weights(save_directory=output_dir, unet_lora_layers=state_dict)
|
| 624 |
+
elif not self.use_lora and isinstance(models[0], UNet2DConditionModel):
|
| 625 |
+
models[0].save_pretrained(os.path.join(output_dir, "unet"))
|
| 626 |
+
else:
|
| 627 |
+
raise ValueError(f"Unknown model type {type(models[0])}")
|
| 628 |
+
|
| 629 |
+
def load_checkpoint(self, models, input_dir):
|
| 630 |
+
if len(models) != 1:
|
| 631 |
+
raise ValueError("Given how the trainable params were set, this should be of length 1")
|
| 632 |
+
if self.use_lora:
|
| 633 |
+
lora_state_dict, network_alphas = self.sd_pipeline.lora_state_dict(
|
| 634 |
+
input_dir, weight_name="pytorch_lora_weights.safetensors"
|
| 635 |
+
)
|
| 636 |
+
self.sd_pipeline.load_lora_into_unet(lora_state_dict, network_alphas=network_alphas, unet=models[0])
|
| 637 |
+
|
| 638 |
+
elif not self.use_lora and isinstance(models[0], UNet2DConditionModel):
|
| 639 |
+
load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet")
|
| 640 |
+
models[0].register_to_config(**load_model.config)
|
| 641 |
+
models[0].load_state_dict(load_model.state_dict())
|
| 642 |
+
del load_model
|
| 643 |
+
else:
|
| 644 |
+
raise ValueError(f"Unknown model type {type(models[0])}")
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/models/modeling_value_head.py
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
transformers_parent_class = AutoModelForCausalLM
|
| 89 |
+
lm_head_namings = ["lm_head", "embed_out"]
|
| 90 |
+
supported_args = (
|
| 91 |
+
"summary_dropout_prob",
|
| 92 |
+
"v_head_initializer_range",
|
| 93 |
+
"v_head_init_strategy",
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
def __init__(self, pretrained_model, **kwargs):
|
| 97 |
+
r"""
|
| 98 |
+
Initializes the model.
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
pretrained_model (`transformers.PreTrainedModel`):
|
| 102 |
+
The model to wrap. It should be a causal language model such as GPT2.
|
| 103 |
+
or any model mapped inside the `AutoModelForCausalLM` class.
|
| 104 |
+
kwargs (`dict`, `optional`):
|
| 105 |
+
Additional keyword arguments, that are passed to the `ValueHead` class.
|
| 106 |
+
"""
|
| 107 |
+
super().__init__(pretrained_model, **kwargs)
|
| 108 |
+
v_head_kwargs, _, _ = self._split_kwargs(kwargs)
|
| 109 |
+
|
| 110 |
+
if not any(hasattr(self.pretrained_model, attribute) for attribute in self.lm_head_namings):
|
| 111 |
+
raise ValueError("The model does not have a language model head, please use a model that has one.")
|
| 112 |
+
|
| 113 |
+
self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs)
|
| 114 |
+
|
| 115 |
+
self._init_weights(**v_head_kwargs)
|
| 116 |
+
|
| 117 |
+
def _init_weights(self, **kwargs):
|
| 118 |
+
r"""
|
| 119 |
+
Initializes the weights of the value head. The default initialization strategy is random.
|
| 120 |
+
Users can pass a different initialization strategy by passing the `v_head_init_strategy` argument
|
| 121 |
+
when calling `.from_pretrained`. Supported strategies are:
|
| 122 |
+
- `normal`: initializes the weights with a normal distribution.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
**kwargs (`dict`, `optional`):
|
| 126 |
+
Additional keyword arguments, that are passed to the `ValueHead` class. These arguments
|
| 127 |
+
can contain the `v_head_init_strategy` argument as well as the `v_head_initializer_range`
|
| 128 |
+
argument.
|
| 129 |
+
"""
|
| 130 |
+
initializer_range = kwargs.pop("v_head_initializer_range", 0.2)
|
| 131 |
+
# random init by default
|
| 132 |
+
init_strategy = kwargs.pop("v_head_init_strategy", None)
|
| 133 |
+
if init_strategy is None:
|
| 134 |
+
# do nothing
|
| 135 |
+
pass
|
| 136 |
+
elif init_strategy == "normal":
|
| 137 |
+
self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range)
|
| 138 |
+
self.v_head.summary.bias.data.zero_()
|
| 139 |
+
|
| 140 |
+
def forward(
|
| 141 |
+
self,
|
| 142 |
+
input_ids=None,
|
| 143 |
+
past_key_values=None,
|
| 144 |
+
attention_mask=None,
|
| 145 |
+
**kwargs,
|
| 146 |
+
):
|
| 147 |
+
r"""
|
| 148 |
+
Applies a forward pass to the wrapped model and returns the logits of the value head.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 152 |
+
Indices of input sequence tokens in the vocabulary.
|
| 153 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, `optional`):
|
| 154 |
+
Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model
|
| 155 |
+
(see `past_key_values` input) to speed up sequential decoding.
|
| 156 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, `optional`):
|
| 157 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
|
| 158 |
+
- 1 for tokens that are **not masked**,
|
| 159 |
+
- 0 for tokens that are **masked**.
|
| 160 |
+
kwargs (`dict`, `optional`):
|
| 161 |
+
Additional keyword arguments, that are passed to the wrapped model.
|
| 162 |
+
"""
|
| 163 |
+
kwargs["output_hidden_states"] = True # this had already been set in the LORA / PEFT examples
|
| 164 |
+
kwargs["past_key_values"] = past_key_values
|
| 165 |
+
|
| 166 |
+
if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING":
|
| 167 |
+
kwargs.pop("past_key_values")
|
| 168 |
+
|
| 169 |
+
base_model_output = self.pretrained_model(
|
| 170 |
+
input_ids=input_ids,
|
| 171 |
+
attention_mask=attention_mask,
|
| 172 |
+
**kwargs,
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
last_hidden_state = base_model_output.hidden_states[-1]
|
| 176 |
+
lm_logits = base_model_output.logits
|
| 177 |
+
loss = base_model_output.loss
|
| 178 |
+
|
| 179 |
+
if last_hidden_state.device != self.v_head.summary.weight.device:
|
| 180 |
+
last_hidden_state = last_hidden_state.to(self.v_head.summary.weight.device)
|
| 181 |
+
|
| 182 |
+
value = self.v_head(last_hidden_state).squeeze(-1)
|
| 183 |
+
|
| 184 |
+
# force upcast in fp32 if logits are in half-precision
|
| 185 |
+
if lm_logits.dtype != torch.float32:
|
| 186 |
+
lm_logits = lm_logits.float()
|
| 187 |
+
|
| 188 |
+
return (lm_logits, loss, value)
|
| 189 |
+
|
| 190 |
+
def generate(self, *args, **kwargs):
|
| 191 |
+
r"""
|
| 192 |
+
A simple wrapper around the `generate` method of the wrapped model.
|
| 193 |
+
Please refer to the [`generate`](https://huggingface.co/docs/transformers/internal/generation_utils)
|
| 194 |
+
method of the wrapped model for more information about the supported arguments.
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
*args (`list`, *optional*):
|
| 198 |
+
Positional arguments passed to the `generate` method of the wrapped model.
|
| 199 |
+
**kwargs (`dict`, *optional*):
|
| 200 |
+
Keyword arguments passed to the `generate` method of the wrapped model.
|
| 201 |
+
"""
|
| 202 |
+
return self.pretrained_model.generate(*args, **kwargs)
|
| 203 |
+
|
| 204 |
+
def state_dict(self, *args, **kwargs):
|
| 205 |
+
r"""
|
| 206 |
+
Returns the state dictionary of the model. We add the state dictionary of the value head
|
| 207 |
+
to the state dictionary of the wrapped model by prepending the key with `v_head.`.
|
| 208 |
+
"""
|
| 209 |
+
if not self.is_peft_model:
|
| 210 |
+
pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs)
|
| 211 |
+
else:
|
| 212 |
+
# if it is a peft model, only save the v_head
|
| 213 |
+
pretrained_model_state_dict = {}
|
| 214 |
+
|
| 215 |
+
v_head_state_dict = self.v_head.state_dict(*args, **kwargs)
|
| 216 |
+
for k, v in v_head_state_dict.items():
|
| 217 |
+
pretrained_model_state_dict[f"v_head.{k}"] = v
|
| 218 |
+
return pretrained_model_state_dict
|
| 219 |
+
|
| 220 |
+
def push_to_hub(self, *args, **kwargs):
|
| 221 |
+
setattr(self.pretrained_model, "v_head", self.v_head)
|
| 222 |
+
|
| 223 |
+
return self.pretrained_model.push_to_hub(*args, **kwargs)
|
| 224 |
+
|
| 225 |
+
def post_init(self, state_dict):
|
| 226 |
+
r"""
|
| 227 |
+
We add the state dictionary of the value head to the state dictionary of the wrapped model
|
| 228 |
+
by prepending the key with `v_head.`. This function removes the `v_head.` prefix from the
|
| 229 |
+
keys of the value head state dictionary.
|
| 230 |
+
"""
|
| 231 |
+
for k in list(state_dict.keys()):
|
| 232 |
+
if "v_head." in k:
|
| 233 |
+
state_dict[k.replace("v_head.", "")] = state_dict.pop(k)
|
| 234 |
+
self.v_head.load_state_dict(state_dict, strict=False)
|
| 235 |
+
del state_dict
|
| 236 |
+
|
| 237 |
+
if hasattr(self.pretrained_model, "hf_device_map"):
|
| 238 |
+
if (
|
| 239 |
+
"cpu" in self.pretrained_model.hf_device_map.values()
|
| 240 |
+
or "disk" in self.pretrained_model.hf_device_map.values()
|
| 241 |
+
):
|
| 242 |
+
raise ValueError(
|
| 243 |
+
"The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models."
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
first_device = list(set(self.pretrained_model.hf_device_map.values()))[0]
|
| 247 |
+
|
| 248 |
+
self.v_head = self.v_head.to(first_device)
|
| 249 |
+
|
| 250 |
+
def set_device_hook(module, input, outputs):
|
| 251 |
+
new_output = ()
|
| 252 |
+
for output in outputs:
|
| 253 |
+
if isinstance(output, torch.Tensor):
|
| 254 |
+
new_output += (output.to(first_device),)
|
| 255 |
+
else:
|
| 256 |
+
new_output += (output,)
|
| 257 |
+
return new_output
|
| 258 |
+
|
| 259 |
+
self.register_forward_hook(set_device_hook)
|
| 260 |
+
|
| 261 |
+
self.is_sequential_parallel = True
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class AutoModelForSeq2SeqLMWithValueHead(PreTrainedModelWrapper):
|
| 265 |
+
r"""
|
| 266 |
+
A seq2seq model with a value head in addition to the language model head.
|
| 267 |
+
This class inherits from `~trl.PreTrainedModelWrapper` and wraps a
|
| 268 |
+
`transformers.PreTrainedModel` class. The wrapper class supports classic functions
|
| 269 |
+
such as `from_pretrained` and `push_to_hub` and also provides some additional
|
| 270 |
+
functionalities such as `generate`.
|
| 271 |
+
|
| 272 |
+
Args:
|
| 273 |
+
pretrained_model (`transformers.PreTrainedModel`):
|
| 274 |
+
The model to wrap. It should be a causal language model such as GPT2.
|
| 275 |
+
or any model mapped inside the `AutoModelForSeq2SeqLM` class.
|
| 276 |
+
kwargs:
|
| 277 |
+
Additional keyword arguments passed along to the `ValueHead` class.
|
| 278 |
+
"""
|
| 279 |
+
transformers_parent_class = AutoModelForSeq2SeqLM
|
| 280 |
+
lm_head_namings = ["lm_head", "embed_out", "output_projection"]
|
| 281 |
+
supported_args = (
|
| 282 |
+
"summary_dropout_prob",
|
| 283 |
+
"v_head_initializer_range",
|
| 284 |
+
"v_head_init_strategy",
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
def __init__(self, pretrained_model, **kwargs):
|
| 288 |
+
super().__init__(pretrained_model, **kwargs)
|
| 289 |
+
v_head_kwargs, _, _ = self._split_kwargs(kwargs)
|
| 290 |
+
self.is_encoder_decoder = True
|
| 291 |
+
|
| 292 |
+
if not self._has_lm_head():
|
| 293 |
+
raise ValueError("The model does not have a language model head, please use a model that has one.")
|
| 294 |
+
|
| 295 |
+
self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs)
|
| 296 |
+
|
| 297 |
+
self._init_weights(**v_head_kwargs)
|
| 298 |
+
|
| 299 |
+
def _has_lm_head(self):
|
| 300 |
+
# check module names of all modules inside `pretrained_model` to find the language model head
|
| 301 |
+
for name, module in self.pretrained_model.named_modules():
|
| 302 |
+
if any(attribute in name for attribute in self.lm_head_namings):
|
| 303 |
+
return True
|
| 304 |
+
return False
|
| 305 |
+
|
| 306 |
+
def post_init(self, state_dict):
|
| 307 |
+
r"""
|
| 308 |
+
We add the state dictionary of the value head to the state dictionary of the wrapped model
|
| 309 |
+
by prepending the key with `v_head.`. This function removes the `v_head.` prefix from the
|
| 310 |
+
keys of the value head state dictionary.
|
| 311 |
+
"""
|
| 312 |
+
for k in list(state_dict.keys()):
|
| 313 |
+
if "v_head." in k:
|
| 314 |
+
state_dict[k.replace("v_head.", "")] = state_dict.pop(k)
|
| 315 |
+
self.v_head.load_state_dict(state_dict, strict=False)
|
| 316 |
+
del state_dict
|
| 317 |
+
|
| 318 |
+
if hasattr(self.pretrained_model, "hf_device_map"):
|
| 319 |
+
if (
|
| 320 |
+
"cpu" in self.pretrained_model.hf_device_map.values()
|
| 321 |
+
or "disk" in self.pretrained_model.hf_device_map.values()
|
| 322 |
+
):
|
| 323 |
+
raise ValueError(
|
| 324 |
+
"The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models."
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# get the lm_head device
|
| 328 |
+
for name, module in self.pretrained_model.named_modules():
|
| 329 |
+
if any(attribute in name for attribute in self.lm_head_namings):
|
| 330 |
+
lm_head_device = module.weight.device
|
| 331 |
+
break
|
| 332 |
+
|
| 333 |
+
# put v_head on the same device as the lm_head to avoid issues
|
| 334 |
+
self.v_head = self.v_head.to(lm_head_device)
|
| 335 |
+
|
| 336 |
+
def set_device_hook(module, input, outputs):
|
| 337 |
+
r"""
|
| 338 |
+
A hook that sets the device of the output of the model to the device of the first
|
| 339 |
+
parameter of the model.
|
| 340 |
+
|
| 341 |
+
Args:
|
| 342 |
+
module (`nn.Module`):
|
| 343 |
+
The module to which the hook is attached.
|
| 344 |
+
input (`tuple`):
|
| 345 |
+
The input to the module.
|
| 346 |
+
outputs (`tuple`):
|
| 347 |
+
The output of the module.
|
| 348 |
+
"""
|
| 349 |
+
new_output = ()
|
| 350 |
+
for output in outputs:
|
| 351 |
+
if isinstance(output, torch.Tensor):
|
| 352 |
+
new_output += (output.to(lm_head_device),)
|
| 353 |
+
else:
|
| 354 |
+
new_output += (output,)
|
| 355 |
+
return new_output
|
| 356 |
+
|
| 357 |
+
self.register_forward_hook(set_device_hook)
|
| 358 |
+
self.is_sequential_parallel = True
|
| 359 |
+
|
| 360 |
+
def state_dict(self, *args, **kwargs):
|
| 361 |
+
r"""
|
| 362 |
+
Returns the state dictionary of the model. We add the state dictionary of the value head
|
| 363 |
+
to the state dictionary of the wrapped model by prepending the key with `v_head.`.
|
| 364 |
+
"""
|
| 365 |
+
if not self.is_peft_model:
|
| 366 |
+
pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs)
|
| 367 |
+
else:
|
| 368 |
+
# if it is a peft model, only save the v_head
|
| 369 |
+
pretrained_model_state_dict = {}
|
| 370 |
+
|
| 371 |
+
v_head_state_dict = self.v_head.state_dict(*args, **kwargs)
|
| 372 |
+
for k, v in v_head_state_dict.items():
|
| 373 |
+
pretrained_model_state_dict[f"v_head.{k}"] = v
|
| 374 |
+
return pretrained_model_state_dict
|
| 375 |
+
|
| 376 |
+
def push_to_hub(self, *args, **kwargs):
|
| 377 |
+
setattr(self.pretrained_model, "v_head", self.v_head)
|
| 378 |
+
|
| 379 |
+
return self.pretrained_model.push_to_hub(*args, **kwargs)
|
| 380 |
+
|
| 381 |
+
def _init_weights(self, **kwargs):
|
| 382 |
+
r"""
|
| 383 |
+
We initialize the weights of the value head.
|
| 384 |
+
"""
|
| 385 |
+
initializer_range = kwargs.pop("v_head_initializer_range", 0.2)
|
| 386 |
+
# random init by default
|
| 387 |
+
init_strategy = kwargs.pop("v_head_init_strategy", None)
|
| 388 |
+
if init_strategy is None:
|
| 389 |
+
# do nothing
|
| 390 |
+
pass
|
| 391 |
+
elif init_strategy == "normal":
|
| 392 |
+
self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range)
|
| 393 |
+
self.v_head.summary.bias.data.zero_()
|
| 394 |
+
|
| 395 |
+
def forward(
|
| 396 |
+
self,
|
| 397 |
+
input_ids=None,
|
| 398 |
+
past_key_values=None,
|
| 399 |
+
attention_mask=None,
|
| 400 |
+
**kwargs,
|
| 401 |
+
):
|
| 402 |
+
kwargs["past_key_values"] = past_key_values
|
| 403 |
+
if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING":
|
| 404 |
+
kwargs.pop("past_key_values")
|
| 405 |
+
|
| 406 |
+
base_model_output = self.pretrained_model(
|
| 407 |
+
input_ids=input_ids,
|
| 408 |
+
attention_mask=attention_mask,
|
| 409 |
+
output_hidden_states=True, # We force the model to output hidden states
|
| 410 |
+
**kwargs,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
last_hidden_state = base_model_output.decoder_hidden_states[-1]
|
| 414 |
+
lm_logits = base_model_output.logits
|
| 415 |
+
loss = base_model_output.loss
|
| 416 |
+
|
| 417 |
+
value = self.v_head(last_hidden_state).squeeze(-1)
|
| 418 |
+
|
| 419 |
+
# force upcast in fp32 if logits are in half-precision
|
| 420 |
+
if lm_logits.dtype != torch.float32:
|
| 421 |
+
lm_logits = lm_logits.float()
|
| 422 |
+
|
| 423 |
+
return (lm_logits, loss, value)
|
| 424 |
+
|
| 425 |
+
def generate(self, *args, **kwargs):
|
| 426 |
+
r"""
|
| 427 |
+
We call `generate` on the wrapped model.
|
| 428 |
+
"""
|
| 429 |
+
return self.pretrained_model.generate(*args, **kwargs)
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/models/utils.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 NVIDIA CORPORATION & AFFILIATES
|
| 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 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from typing import Literal, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from transformers import PreTrainedModel, PreTrainedTokenizer
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# TODO: Add Abstract Base Class if more formats are added
|
| 24 |
+
@dataclass
|
| 25 |
+
class ChatMlSpecialTokens:
|
| 26 |
+
"""Dataclass for special tokens used in ChatML, including system, user, assistant, bos, eos, and pad tokens."""
|
| 27 |
+
|
| 28 |
+
bos_token: str = "<|im_start|>"
|
| 29 |
+
eos_token: str = "<|im_end|>"
|
| 30 |
+
pad_token: str = "<|im_end|>"
|
| 31 |
+
|
| 32 |
+
@property
|
| 33 |
+
def system(self):
|
| 34 |
+
return f"{self.bos_token}system"
|
| 35 |
+
|
| 36 |
+
@property
|
| 37 |
+
def user(self):
|
| 38 |
+
return f"{self.bos_token}user"
|
| 39 |
+
|
| 40 |
+
@property
|
| 41 |
+
def assistant(self):
|
| 42 |
+
return f"{self.bos_token}assistant"
|
| 43 |
+
|
| 44 |
+
@property
|
| 45 |
+
def chat_template(self):
|
| 46 |
+
return (
|
| 47 |
+
"{% for message in messages %}"
|
| 48 |
+
f"{{{{'{self.bos_token}' + message['role'] + '\n' + message['content'] + '{self.eos_token}' + '\n'}}}}"
|
| 49 |
+
"{% endfor %}"
|
| 50 |
+
"{% if add_generation_prompt %}"
|
| 51 |
+
f"{{{{ '{self.assistant}\n' }}}}"
|
| 52 |
+
"{% endif %}"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
FORMAT_MAPPING = {"chatml": ChatMlSpecialTokens}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def setup_chat_format(
|
| 60 |
+
model: PreTrainedModel,
|
| 61 |
+
tokenizer: PreTrainedTokenizer,
|
| 62 |
+
format: Optional[Literal["chatml"]] = "chatml",
|
| 63 |
+
resize_to_multiple_of: Optional[int] = None,
|
| 64 |
+
) -> Tuple[PreTrainedModel, PreTrainedTokenizer]:
|
| 65 |
+
"""
|
| 66 |
+
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.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
model (`~transformers.PreTrainedModel`): The model to be modified.
|
| 70 |
+
tokenizer (`~transformers.PreTrainedTokenizer`): The tokenizer to be modified.
|
| 71 |
+
format (`Optional[Literal["chatml"]]`): The format to be set. Defaults to "chatml".
|
| 72 |
+
resize_to_multiple_of (`Optional[int]`): Number to resize the embedding layer to. Defaults to None.
|
| 73 |
+
Returns:
|
| 74 |
+
model (`~transformers.PreTrainedModel`): The modified model.
|
| 75 |
+
tokenizer (`~transformers.PreTrainedTokenizer`): The modified tokenizer.
|
| 76 |
+
"""
|
| 77 |
+
# check if format available and retrieve
|
| 78 |
+
if format not in FORMAT_MAPPING:
|
| 79 |
+
raise ValueError(f"Format {format} not available. Please use one of {FORMAT_MAPPING.keys()}")
|
| 80 |
+
|
| 81 |
+
chat_format = FORMAT_MAPPING[format]()
|
| 82 |
+
|
| 83 |
+
# set special tokens and them
|
| 84 |
+
tokenizer.eos_token = chat_format.eos_token
|
| 85 |
+
tokenizer.pad_token = chat_format.pad_token
|
| 86 |
+
tokenizer.bos_token = chat_format.bos_token
|
| 87 |
+
tokenizer.add_special_tokens({"additional_special_tokens": [chat_format.bos_token, chat_format.eos_token]})
|
| 88 |
+
# set chat format for tokenizer
|
| 89 |
+
tokenizer.chat_template = chat_format.chat_template
|
| 90 |
+
|
| 91 |
+
# resize embedding layer to a multiple of 64, https://x.com/karpathy/status/1621578354024677377
|
| 92 |
+
model.resize_token_embeddings(
|
| 93 |
+
len(tokenizer), pad_to_multiple_of=resize_to_multiple_of if resize_to_multiple_of is not None else None
|
| 94 |
+
)
|
| 95 |
+
# Make sure to update the generation config to use the new eos & bos token
|
| 96 |
+
if getattr(model, "generation_config", None) is not None:
|
| 97 |
+
model.generation_config.bos_token_id = tokenizer.bos_token_id
|
| 98 |
+
model.generation_config.eos_token_id = tokenizer.eos_token_id
|
| 99 |
+
model.generation_config.pad_token_id = tokenizer.pad_token_id
|
| 100 |
+
|
| 101 |
+
return model, tokenizer
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/__init__.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
if is_diffusers_available():
|
| 36 |
+
from .ddpo_trainer import DDPOTrainer
|
| 37 |
+
|
| 38 |
+
from .dpo_trainer import DPOTrainer
|
| 39 |
+
from .iterative_sft_trainer import IterativeSFTTrainer
|
| 40 |
+
from .model_config import ModelConfig
|
| 41 |
+
from .ppo_config import PPOConfig
|
| 42 |
+
from .ppo_trainer import PPOTrainer
|
| 43 |
+
from .reward_config import RewardConfig
|
| 44 |
+
from .reward_trainer import RewardTrainer, compute_accuracy
|
| 45 |
+
from .sft_trainer import SFTTrainer
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/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")
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/ddpo_config.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 NVIDIA CORPORATION & AFFILIATES
|
| 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 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
import warnings
|
| 20 |
+
from dataclasses import dataclass, field
|
| 21 |
+
from typing import Literal, Optional
|
| 22 |
+
|
| 23 |
+
from ..core import flatten_dict
|
| 24 |
+
from ..import_utils import is_bitsandbytes_available, is_torchvision_available
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class DDPOConfig:
|
| 29 |
+
"""
|
| 30 |
+
Configuration class for DDPOTrainer
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
# common parameters
|
| 34 |
+
exp_name: str = os.path.basename(sys.argv[0])[: -len(".py")]
|
| 35 |
+
"""the name of this experiment (by default is the file name without the extension name)"""
|
| 36 |
+
run_name: Optional[str] = ""
|
| 37 |
+
"""Run name for wandb logging and checkpoint saving."""
|
| 38 |
+
seed: int = 0
|
| 39 |
+
"""Seed value for random generations"""
|
| 40 |
+
log_with: Optional[Literal["wandb", "tensorboard"]] = None
|
| 41 |
+
"""Log with either 'wandb' or 'tensorboard', check https://huggingface.co/docs/accelerate/usage_guides/tracking for more details"""
|
| 42 |
+
tracker_kwargs: dict = field(default_factory=dict)
|
| 43 |
+
"""Keyword arguments for the tracker (e.g. wandb_project)"""
|
| 44 |
+
accelerator_kwargs: dict = field(default_factory=dict)
|
| 45 |
+
"""Keyword arguments for the accelerator"""
|
| 46 |
+
project_kwargs: dict = field(default_factory=dict)
|
| 47 |
+
"""Keyword arguments for the accelerator project config (e.g. `logging_dir`)"""
|
| 48 |
+
tracker_project_name: str = "trl"
|
| 49 |
+
"""Name of project to use for tracking"""
|
| 50 |
+
logdir: str = "logs"
|
| 51 |
+
"""Top-level logging directory for checkpoint saving."""
|
| 52 |
+
|
| 53 |
+
# hyperparameters
|
| 54 |
+
num_epochs: int = 100
|
| 55 |
+
"""Number of epochs to train."""
|
| 56 |
+
save_freq: int = 1
|
| 57 |
+
"""Number of epochs between saving model checkpoints."""
|
| 58 |
+
num_checkpoint_limit: int = 5
|
| 59 |
+
"""Number of checkpoints to keep before overwriting old ones."""
|
| 60 |
+
mixed_precision: str = "fp16"
|
| 61 |
+
"""Mixed precision training."""
|
| 62 |
+
allow_tf32: bool = True
|
| 63 |
+
"""Allow tf32 on Ampere GPUs."""
|
| 64 |
+
resume_from: Optional[str] = ""
|
| 65 |
+
"""Resume training from a checkpoint."""
|
| 66 |
+
sample_num_steps: int = 50
|
| 67 |
+
"""Number of sampler inference steps."""
|
| 68 |
+
sample_eta: float = 1.0
|
| 69 |
+
"""Eta parameter for the DDIM sampler."""
|
| 70 |
+
sample_guidance_scale: float = 5.0
|
| 71 |
+
"""Classifier-free guidance weight."""
|
| 72 |
+
sample_batch_size: int = 1
|
| 73 |
+
"""Batch size (per GPU!) to use for sampling."""
|
| 74 |
+
sample_num_batches_per_epoch: int = 2
|
| 75 |
+
"""Number of batches to sample per epoch."""
|
| 76 |
+
train_batch_size: int = 1
|
| 77 |
+
"""Batch size (per GPU!) to use for training."""
|
| 78 |
+
train_use_8bit_adam: bool = False
|
| 79 |
+
"""Whether to use the 8bit Adam optimizer from bitsandbytes."""
|
| 80 |
+
train_learning_rate: float = 3e-4
|
| 81 |
+
"""Learning rate."""
|
| 82 |
+
train_adam_beta1: float = 0.9
|
| 83 |
+
"""Adam beta1."""
|
| 84 |
+
train_adam_beta2: float = 0.999
|
| 85 |
+
"""Adam beta2."""
|
| 86 |
+
train_adam_weight_decay: float = 1e-4
|
| 87 |
+
"""Adam weight decay."""
|
| 88 |
+
train_adam_epsilon: float = 1e-8
|
| 89 |
+
"""Adam epsilon."""
|
| 90 |
+
train_gradient_accumulation_steps: int = 1
|
| 91 |
+
"""Number of gradient accumulation steps."""
|
| 92 |
+
train_max_grad_norm: float = 1.0
|
| 93 |
+
"""Maximum gradient norm for gradient clipping."""
|
| 94 |
+
train_num_inner_epochs: int = 1
|
| 95 |
+
"""Number of inner epochs per outer epoch."""
|
| 96 |
+
train_cfg: bool = True
|
| 97 |
+
"""Whether or not to use classifier-free guidance during training."""
|
| 98 |
+
train_adv_clip_max: float = 5
|
| 99 |
+
"""Clip advantages to the range."""
|
| 100 |
+
train_clip_range: float = 1e-4
|
| 101 |
+
"""The PPO clip range."""
|
| 102 |
+
train_timestep_fraction: float = 1.0
|
| 103 |
+
"""The fraction of timesteps to train on."""
|
| 104 |
+
per_prompt_stat_tracking: bool = False
|
| 105 |
+
"""Whether to track statistics for each prompt separately."""
|
| 106 |
+
per_prompt_stat_tracking_buffer_size: int = 16
|
| 107 |
+
"""Number of reward values to store in the buffer for each prompt."""
|
| 108 |
+
per_prompt_stat_tracking_min_count: int = 16
|
| 109 |
+
"""The minimum number of reward values to store in the buffer."""
|
| 110 |
+
async_reward_computation: bool = False
|
| 111 |
+
"""Whether to compute rewards asynchronously."""
|
| 112 |
+
max_workers: int = 2
|
| 113 |
+
"""The maximum number of workers to use for async reward computation."""
|
| 114 |
+
negative_prompts: Optional[str] = ""
|
| 115 |
+
"""Comma-separated list of prompts to use as negative examples."""
|
| 116 |
+
|
| 117 |
+
def to_dict(self):
|
| 118 |
+
output_dict = {}
|
| 119 |
+
for key, value in self.__dict__.items():
|
| 120 |
+
output_dict[key] = value
|
| 121 |
+
return flatten_dict(output_dict)
|
| 122 |
+
|
| 123 |
+
def __post_init__(self):
|
| 124 |
+
if self.log_with not in ["wandb", "tensorboard"]:
|
| 125 |
+
warnings.warn(
|
| 126 |
+
"Accelerator tracking only supports image logging if `log_with` is set to 'wandb' or 'tensorboard'."
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
if self.log_with == "wandb" and not is_torchvision_available():
|
| 130 |
+
warnings.warn("Wandb image logging requires torchvision to be installed")
|
| 131 |
+
|
| 132 |
+
if self.train_use_8bit_adam and not is_bitsandbytes_available():
|
| 133 |
+
raise ImportError(
|
| 134 |
+
"You need to install bitsandbytes to use 8bit Adam. "
|
| 135 |
+
"You can install it with `pip install bitsandbytes`."
|
| 136 |
+
)
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/ddpo_trainer.py
ADDED
|
@@ -0,0 +1,628 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 DDPO-pytorch authors (Kevin Black), metric-space, 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 |
+
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 |
+
logger = get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
MODEL_CARD_TEMPLATE = """---
|
| 36 |
+
license: apache-2.0
|
| 37 |
+
tags:
|
| 38 |
+
- trl
|
| 39 |
+
- ddpo
|
| 40 |
+
- diffusers
|
| 41 |
+
- reinforcement-learning
|
| 42 |
+
- text-to-image
|
| 43 |
+
- stable-diffusion
|
| 44 |
+
---
|
| 45 |
+
|
| 46 |
+
# {model_name}
|
| 47 |
+
|
| 48 |
+
This is a diffusion model that has been fine-tuned with reinforcement learning to
|
| 49 |
+
guide the model outputs according to a value, function, or human feedback. The model can be used for image generation conditioned with text.
|
| 50 |
+
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class DDPOTrainer(BaseTrainer):
|
| 55 |
+
"""
|
| 56 |
+
The DDPOTrainer uses Deep Diffusion Policy Optimization to optimise diffusion models.
|
| 57 |
+
Note, this trainer is heavily inspired by the work here: https://github.com/kvablack/ddpo-pytorch
|
| 58 |
+
As of now only Stable Diffusion based pipelines are supported
|
| 59 |
+
|
| 60 |
+
Attributes:
|
| 61 |
+
**config** (`DDPOConfig`) -- Configuration object for DDPOTrainer. Check the documentation of `PPOConfig` for more
|
| 62 |
+
details.
|
| 63 |
+
**reward_function** (Callable[[torch.Tensor, Tuple[str], Tuple[Any]], torch.Tensor]) -- Reward function to be used
|
| 64 |
+
**prompt_function** (Callable[[], Tuple[str, Any]]) -- Function to generate prompts to guide model
|
| 65 |
+
**sd_pipeline** (`DDPOStableDiffusionPipeline`) -- Stable Diffusion pipeline to be used for training.
|
| 66 |
+
**image_samples_hook** (Optional[Callable[[Any, Any, Any], Any]]) -- Hook to be called to log images
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
_tag_names = ["trl", "ddpo"]
|
| 70 |
+
|
| 71 |
+
def __init__(
|
| 72 |
+
self,
|
| 73 |
+
config: DDPOConfig,
|
| 74 |
+
reward_function: Callable[[torch.Tensor, Tuple[str], Tuple[Any]], torch.Tensor],
|
| 75 |
+
prompt_function: Callable[[], Tuple[str, Any]],
|
| 76 |
+
sd_pipeline: DDPOStableDiffusionPipeline,
|
| 77 |
+
image_samples_hook: Optional[Callable[[Any, Any, Any], Any]] = None,
|
| 78 |
+
):
|
| 79 |
+
if image_samples_hook is None:
|
| 80 |
+
warn("No image_samples_hook provided; no images will be logged")
|
| 81 |
+
|
| 82 |
+
self.prompt_fn = prompt_function
|
| 83 |
+
self.reward_fn = reward_function
|
| 84 |
+
self.config = config
|
| 85 |
+
self.image_samples_callback = image_samples_hook
|
| 86 |
+
|
| 87 |
+
accelerator_project_config = ProjectConfiguration(**self.config.project_kwargs)
|
| 88 |
+
|
| 89 |
+
if self.config.resume_from:
|
| 90 |
+
self.config.resume_from = os.path.normpath(os.path.expanduser(self.config.resume_from))
|
| 91 |
+
if "checkpoint_" not in os.path.basename(self.config.resume_from):
|
| 92 |
+
# get the most recent checkpoint in this directory
|
| 93 |
+
checkpoints = list(
|
| 94 |
+
filter(
|
| 95 |
+
lambda x: "checkpoint_" in x,
|
| 96 |
+
os.listdir(self.config.resume_from),
|
| 97 |
+
)
|
| 98 |
+
)
|
| 99 |
+
if len(checkpoints) == 0:
|
| 100 |
+
raise ValueError(f"No checkpoints found in {self.config.resume_from}")
|
| 101 |
+
checkpoint_numbers = sorted([int(x.split("_")[-1]) for x in checkpoints])
|
| 102 |
+
self.config.resume_from = os.path.join(
|
| 103 |
+
self.config.resume_from,
|
| 104 |
+
f"checkpoint_{checkpoint_numbers[-1]}",
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
accelerator_project_config.iteration = checkpoint_numbers[-1] + 1
|
| 108 |
+
|
| 109 |
+
# number of timesteps within each trajectory to train on
|
| 110 |
+
self.num_train_timesteps = int(self.config.sample_num_steps * self.config.train_timestep_fraction)
|
| 111 |
+
|
| 112 |
+
self.accelerator = Accelerator(
|
| 113 |
+
log_with=self.config.log_with,
|
| 114 |
+
mixed_precision=self.config.mixed_precision,
|
| 115 |
+
project_config=accelerator_project_config,
|
| 116 |
+
# we always accumulate gradients across timesteps; we want config.train.gradient_accumulation_steps to be the
|
| 117 |
+
# number of *samples* we accumulate across, so we need to multiply by the number of training timesteps to get
|
| 118 |
+
# the total number of optimizer steps to accumulate across.
|
| 119 |
+
gradient_accumulation_steps=self.config.train_gradient_accumulation_steps * self.num_train_timesteps,
|
| 120 |
+
**self.config.accelerator_kwargs,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
is_okay, message = self._config_check()
|
| 124 |
+
if not is_okay:
|
| 125 |
+
raise ValueError(message)
|
| 126 |
+
|
| 127 |
+
is_using_tensorboard = config.log_with is not None and config.log_with == "tensorboard"
|
| 128 |
+
|
| 129 |
+
if self.accelerator.is_main_process:
|
| 130 |
+
self.accelerator.init_trackers(
|
| 131 |
+
self.config.tracker_project_name,
|
| 132 |
+
config=dict(ddpo_trainer_config=config.to_dict()) if not is_using_tensorboard else config.to_dict(),
|
| 133 |
+
init_kwargs=self.config.tracker_kwargs,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
logger.info(f"\n{config}")
|
| 137 |
+
|
| 138 |
+
set_seed(self.config.seed, device_specific=True)
|
| 139 |
+
|
| 140 |
+
self.sd_pipeline = sd_pipeline
|
| 141 |
+
|
| 142 |
+
self.sd_pipeline.set_progress_bar_config(
|
| 143 |
+
position=1,
|
| 144 |
+
disable=not self.accelerator.is_local_main_process,
|
| 145 |
+
leave=False,
|
| 146 |
+
desc="Timestep",
|
| 147 |
+
dynamic_ncols=True,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
# For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
|
| 151 |
+
# as these weights are only used for inference, keeping weights in full precision is not required.
|
| 152 |
+
if self.accelerator.mixed_precision == "fp16":
|
| 153 |
+
inference_dtype = torch.float16
|
| 154 |
+
elif self.accelerator.mixed_precision == "bf16":
|
| 155 |
+
inference_dtype = torch.bfloat16
|
| 156 |
+
else:
|
| 157 |
+
inference_dtype = torch.float32
|
| 158 |
+
|
| 159 |
+
self.sd_pipeline.vae.to(self.accelerator.device, dtype=inference_dtype)
|
| 160 |
+
self.sd_pipeline.text_encoder.to(self.accelerator.device, dtype=inference_dtype)
|
| 161 |
+
self.sd_pipeline.unet.to(self.accelerator.device, dtype=inference_dtype)
|
| 162 |
+
|
| 163 |
+
trainable_layers = self.sd_pipeline.get_trainable_layers()
|
| 164 |
+
|
| 165 |
+
self.accelerator.register_save_state_pre_hook(self._save_model_hook)
|
| 166 |
+
self.accelerator.register_load_state_pre_hook(self._load_model_hook)
|
| 167 |
+
|
| 168 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 169 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 170 |
+
if self.config.allow_tf32:
|
| 171 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 172 |
+
|
| 173 |
+
self.optimizer = self._setup_optimizer(
|
| 174 |
+
trainable_layers.parameters() if not isinstance(trainable_layers, list) else trainable_layers
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
self.neg_prompt_embed = self.sd_pipeline.text_encoder(
|
| 178 |
+
self.sd_pipeline.tokenizer(
|
| 179 |
+
[""] if self.config.negative_prompts is None else self.config.negative_prompts,
|
| 180 |
+
return_tensors="pt",
|
| 181 |
+
padding="max_length",
|
| 182 |
+
truncation=True,
|
| 183 |
+
max_length=self.sd_pipeline.tokenizer.model_max_length,
|
| 184 |
+
).input_ids.to(self.accelerator.device)
|
| 185 |
+
)[0]
|
| 186 |
+
|
| 187 |
+
if config.per_prompt_stat_tracking:
|
| 188 |
+
self.stat_tracker = PerPromptStatTracker(
|
| 189 |
+
config.per_prompt_stat_tracking_buffer_size,
|
| 190 |
+
config.per_prompt_stat_tracking_min_count,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
# NOTE: for some reason, autocast is necessary for non-lora training but for lora training it isn't necessary and it uses
|
| 194 |
+
# more memory
|
| 195 |
+
self.autocast = self.sd_pipeline.autocast or self.accelerator.autocast
|
| 196 |
+
|
| 197 |
+
if hasattr(self.sd_pipeline, "use_lora") and self.sd_pipeline.use_lora:
|
| 198 |
+
unet, self.optimizer = self.accelerator.prepare(trainable_layers, self.optimizer)
|
| 199 |
+
self.trainable_layers = list(filter(lambda p: p.requires_grad, unet.parameters()))
|
| 200 |
+
else:
|
| 201 |
+
self.trainable_layers, self.optimizer = self.accelerator.prepare(trainable_layers, self.optimizer)
|
| 202 |
+
|
| 203 |
+
if self.config.async_reward_computation:
|
| 204 |
+
self.executor = futures.ThreadPoolExecutor(max_workers=config.max_workers)
|
| 205 |
+
|
| 206 |
+
if config.resume_from:
|
| 207 |
+
logger.info(f"Resuming from {config.resume_from}")
|
| 208 |
+
self.accelerator.load_state(config.resume_from)
|
| 209 |
+
self.first_epoch = int(config.resume_from.split("_")[-1]) + 1
|
| 210 |
+
else:
|
| 211 |
+
self.first_epoch = 0
|
| 212 |
+
|
| 213 |
+
def compute_rewards(self, prompt_image_pairs, is_async=False):
|
| 214 |
+
if not is_async:
|
| 215 |
+
rewards = []
|
| 216 |
+
for images, prompts, prompt_metadata in prompt_image_pairs:
|
| 217 |
+
reward, reward_metadata = self.reward_fn(images, prompts, prompt_metadata)
|
| 218 |
+
rewards.append(
|
| 219 |
+
(
|
| 220 |
+
torch.as_tensor(reward, device=self.accelerator.device),
|
| 221 |
+
reward_metadata,
|
| 222 |
+
)
|
| 223 |
+
)
|
| 224 |
+
else:
|
| 225 |
+
rewards = self.executor.map(lambda x: self.reward_fn(*x), prompt_image_pairs)
|
| 226 |
+
rewards = [
|
| 227 |
+
(torch.as_tensor(reward.result(), device=self.accelerator.device), reward_metadata.result())
|
| 228 |
+
for reward, reward_metadata in rewards
|
| 229 |
+
]
|
| 230 |
+
|
| 231 |
+
return zip(*rewards)
|
| 232 |
+
|
| 233 |
+
def step(self, epoch: int, global_step: int):
|
| 234 |
+
"""
|
| 235 |
+
Perform a single step of training.
|
| 236 |
+
|
| 237 |
+
Args:
|
| 238 |
+
epoch (int): The current epoch.
|
| 239 |
+
global_step (int): The current global step.
|
| 240 |
+
|
| 241 |
+
Side Effects:
|
| 242 |
+
- Model weights are updated
|
| 243 |
+
- Logs the statistics to the accelerator trackers.
|
| 244 |
+
- If `self.image_samples_callback` is not None, it will be called with the prompt_image_pairs, global_step, and the accelerator tracker.
|
| 245 |
+
|
| 246 |
+
Returns:
|
| 247 |
+
global_step (int): The updated global step.
|
| 248 |
+
|
| 249 |
+
"""
|
| 250 |
+
samples, prompt_image_data = self._generate_samples(
|
| 251 |
+
iterations=self.config.sample_num_batches_per_epoch,
|
| 252 |
+
batch_size=self.config.sample_batch_size,
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# collate samples into dict where each entry has shape (num_batches_per_epoch * sample.batch_size, ...)
|
| 256 |
+
samples = {k: torch.cat([s[k] for s in samples]) for k in samples[0].keys()}
|
| 257 |
+
rewards, rewards_metadata = self.compute_rewards(
|
| 258 |
+
prompt_image_data, is_async=self.config.async_reward_computation
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
for i, image_data in enumerate(prompt_image_data):
|
| 262 |
+
image_data.extend([rewards[i], rewards_metadata[i]])
|
| 263 |
+
|
| 264 |
+
if self.image_samples_callback is not None:
|
| 265 |
+
self.image_samples_callback(prompt_image_data, global_step, self.accelerator.trackers[0])
|
| 266 |
+
|
| 267 |
+
rewards = torch.cat(rewards)
|
| 268 |
+
rewards = self.accelerator.gather(rewards).cpu().numpy()
|
| 269 |
+
|
| 270 |
+
self.accelerator.log(
|
| 271 |
+
{
|
| 272 |
+
"reward": rewards,
|
| 273 |
+
"epoch": epoch,
|
| 274 |
+
"reward_mean": rewards.mean(),
|
| 275 |
+
"reward_std": rewards.std(),
|
| 276 |
+
},
|
| 277 |
+
step=global_step,
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
if self.config.per_prompt_stat_tracking:
|
| 281 |
+
# gather the prompts across processes
|
| 282 |
+
prompt_ids = self.accelerator.gather(samples["prompt_ids"]).cpu().numpy()
|
| 283 |
+
prompts = self.sd_pipeline.tokenizer.batch_decode(prompt_ids, skip_special_tokens=True)
|
| 284 |
+
advantages = self.stat_tracker.update(prompts, rewards)
|
| 285 |
+
else:
|
| 286 |
+
advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-8)
|
| 287 |
+
|
| 288 |
+
# ungather advantages; keep the entries corresponding to the samples on this process
|
| 289 |
+
samples["advantages"] = (
|
| 290 |
+
torch.as_tensor(advantages)
|
| 291 |
+
.reshape(self.accelerator.num_processes, -1)[self.accelerator.process_index]
|
| 292 |
+
.to(self.accelerator.device)
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
del samples["prompt_ids"]
|
| 296 |
+
|
| 297 |
+
total_batch_size, num_timesteps = samples["timesteps"].shape
|
| 298 |
+
|
| 299 |
+
for inner_epoch in range(self.config.train_num_inner_epochs):
|
| 300 |
+
# shuffle samples along batch dimension
|
| 301 |
+
perm = torch.randperm(total_batch_size, device=self.accelerator.device)
|
| 302 |
+
samples = {k: v[perm] for k, v in samples.items()}
|
| 303 |
+
|
| 304 |
+
# shuffle along time dimension independently for each sample
|
| 305 |
+
# still trying to understand the code below
|
| 306 |
+
perms = torch.stack(
|
| 307 |
+
[torch.randperm(num_timesteps, device=self.accelerator.device) for _ in range(total_batch_size)]
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
for key in ["timesteps", "latents", "next_latents", "log_probs"]:
|
| 311 |
+
samples[key] = samples[key][
|
| 312 |
+
torch.arange(total_batch_size, device=self.accelerator.device)[:, None],
|
| 313 |
+
perms,
|
| 314 |
+
]
|
| 315 |
+
|
| 316 |
+
original_keys = samples.keys()
|
| 317 |
+
original_values = samples.values()
|
| 318 |
+
# rebatch them as user defined train_batch_size is different from sample_batch_size
|
| 319 |
+
reshaped_values = [v.reshape(-1, self.config.train_batch_size, *v.shape[1:]) for v in original_values]
|
| 320 |
+
|
| 321 |
+
# Transpose the list of original values
|
| 322 |
+
transposed_values = zip(*reshaped_values)
|
| 323 |
+
# Create new dictionaries for each row of transposed values
|
| 324 |
+
samples_batched = [dict(zip(original_keys, row_values)) for row_values in transposed_values]
|
| 325 |
+
|
| 326 |
+
self.sd_pipeline.unet.train()
|
| 327 |
+
global_step = self._train_batched_samples(inner_epoch, epoch, global_step, samples_batched)
|
| 328 |
+
# ensure optimization step at the end of the inner epoch
|
| 329 |
+
if not self.accelerator.sync_gradients:
|
| 330 |
+
raise ValueError(
|
| 331 |
+
"Optimization step should have been performed by this point. Please check calculated gradient accumulation settings."
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
if epoch != 0 and epoch % self.config.save_freq == 0 and self.accelerator.is_main_process:
|
| 335 |
+
self.accelerator.save_state()
|
| 336 |
+
|
| 337 |
+
return global_step
|
| 338 |
+
|
| 339 |
+
def calculate_loss(self, latents, timesteps, next_latents, log_probs, advantages, embeds):
|
| 340 |
+
"""
|
| 341 |
+
Calculate the loss for a batch of an unpacked sample
|
| 342 |
+
|
| 343 |
+
Args:
|
| 344 |
+
latents (torch.Tensor):
|
| 345 |
+
The latents sampled from the diffusion model, shape: [batch_size, num_channels_latents, height, width]
|
| 346 |
+
timesteps (torch.Tensor):
|
| 347 |
+
The timesteps sampled from the diffusion model, shape: [batch_size]
|
| 348 |
+
next_latents (torch.Tensor):
|
| 349 |
+
The next latents sampled from the diffusion model, shape: [batch_size, num_channels_latents, height, width]
|
| 350 |
+
log_probs (torch.Tensor):
|
| 351 |
+
The log probabilities of the latents, shape: [batch_size]
|
| 352 |
+
advantages (torch.Tensor):
|
| 353 |
+
The advantages of the latents, shape: [batch_size]
|
| 354 |
+
embeds (torch.Tensor):
|
| 355 |
+
The embeddings of the prompts, shape: [2*batch_size or batch_size, ...]
|
| 356 |
+
Note: the "or" is because if train_cfg is True, the expectation is that negative prompts are concatenated to the embeds
|
| 357 |
+
|
| 358 |
+
Returns:
|
| 359 |
+
loss (torch.Tensor), approx_kl (torch.Tensor), clipfrac (torch.Tensor)
|
| 360 |
+
(all of these are of shape (1,))
|
| 361 |
+
"""
|
| 362 |
+
with self.autocast():
|
| 363 |
+
if self.config.train_cfg:
|
| 364 |
+
noise_pred = self.sd_pipeline.unet(
|
| 365 |
+
torch.cat([latents] * 2),
|
| 366 |
+
torch.cat([timesteps] * 2),
|
| 367 |
+
embeds,
|
| 368 |
+
).sample
|
| 369 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 370 |
+
noise_pred = noise_pred_uncond + self.config.sample_guidance_scale * (
|
| 371 |
+
noise_pred_text - noise_pred_uncond
|
| 372 |
+
)
|
| 373 |
+
else:
|
| 374 |
+
noise_pred = self.sd_pipeline.unet(
|
| 375 |
+
latents,
|
| 376 |
+
timesteps,
|
| 377 |
+
embeds,
|
| 378 |
+
).sample
|
| 379 |
+
# compute the log prob of next_latents given latents under the current model
|
| 380 |
+
|
| 381 |
+
scheduler_step_output = self.sd_pipeline.scheduler_step(
|
| 382 |
+
noise_pred,
|
| 383 |
+
timesteps,
|
| 384 |
+
latents,
|
| 385 |
+
eta=self.config.sample_eta,
|
| 386 |
+
prev_sample=next_latents,
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
log_prob = scheduler_step_output.log_probs
|
| 390 |
+
|
| 391 |
+
advantages = torch.clamp(
|
| 392 |
+
advantages,
|
| 393 |
+
-self.config.train_adv_clip_max,
|
| 394 |
+
self.config.train_adv_clip_max,
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
ratio = torch.exp(log_prob - log_probs)
|
| 398 |
+
|
| 399 |
+
loss = self.loss(advantages, self.config.train_clip_range, ratio)
|
| 400 |
+
|
| 401 |
+
approx_kl = 0.5 * torch.mean((log_prob - log_probs) ** 2)
|
| 402 |
+
|
| 403 |
+
clipfrac = torch.mean((torch.abs(ratio - 1.0) > self.config.train_clip_range).float())
|
| 404 |
+
|
| 405 |
+
return loss, approx_kl, clipfrac
|
| 406 |
+
|
| 407 |
+
def loss(
|
| 408 |
+
self,
|
| 409 |
+
advantages: torch.Tensor,
|
| 410 |
+
clip_range: float,
|
| 411 |
+
ratio: torch.Tensor,
|
| 412 |
+
):
|
| 413 |
+
unclipped_loss = -advantages * ratio
|
| 414 |
+
clipped_loss = -advantages * torch.clamp(
|
| 415 |
+
ratio,
|
| 416 |
+
1.0 - clip_range,
|
| 417 |
+
1.0 + clip_range,
|
| 418 |
+
)
|
| 419 |
+
return torch.mean(torch.maximum(unclipped_loss, clipped_loss))
|
| 420 |
+
|
| 421 |
+
def _setup_optimizer(self, trainable_layers_parameters):
|
| 422 |
+
if self.config.train_use_8bit_adam:
|
| 423 |
+
import bitsandbytes
|
| 424 |
+
|
| 425 |
+
optimizer_cls = bitsandbytes.optim.AdamW8bit
|
| 426 |
+
else:
|
| 427 |
+
optimizer_cls = torch.optim.AdamW
|
| 428 |
+
|
| 429 |
+
return optimizer_cls(
|
| 430 |
+
trainable_layers_parameters,
|
| 431 |
+
lr=self.config.train_learning_rate,
|
| 432 |
+
betas=(self.config.train_adam_beta1, self.config.train_adam_beta2),
|
| 433 |
+
weight_decay=self.config.train_adam_weight_decay,
|
| 434 |
+
eps=self.config.train_adam_epsilon,
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
def _save_model_hook(self, models, weights, output_dir):
|
| 438 |
+
self.sd_pipeline.save_checkpoint(models, weights, output_dir)
|
| 439 |
+
weights.pop() # ensures that accelerate doesn't try to handle saving of the model
|
| 440 |
+
|
| 441 |
+
def _load_model_hook(self, models, input_dir):
|
| 442 |
+
self.sd_pipeline.load_checkpoint(models, input_dir)
|
| 443 |
+
models.pop() # ensures that accelerate doesn't try to handle loading of the model
|
| 444 |
+
|
| 445 |
+
def _generate_samples(self, iterations, batch_size):
|
| 446 |
+
"""
|
| 447 |
+
Generate samples from the model
|
| 448 |
+
|
| 449 |
+
Args:
|
| 450 |
+
iterations (int): Number of iterations to generate samples for
|
| 451 |
+
batch_size (int): Batch size to use for sampling
|
| 452 |
+
|
| 453 |
+
Returns:
|
| 454 |
+
samples (List[Dict[str, torch.Tensor]]), prompt_image_pairs (List[List[Any]])
|
| 455 |
+
"""
|
| 456 |
+
samples = []
|
| 457 |
+
prompt_image_pairs = []
|
| 458 |
+
self.sd_pipeline.unet.eval()
|
| 459 |
+
|
| 460 |
+
sample_neg_prompt_embeds = self.neg_prompt_embed.repeat(batch_size, 1, 1)
|
| 461 |
+
|
| 462 |
+
for _ in range(iterations):
|
| 463 |
+
prompts, prompt_metadata = zip(*[self.prompt_fn() for _ in range(batch_size)])
|
| 464 |
+
|
| 465 |
+
prompt_ids = self.sd_pipeline.tokenizer(
|
| 466 |
+
prompts,
|
| 467 |
+
return_tensors="pt",
|
| 468 |
+
padding="max_length",
|
| 469 |
+
truncation=True,
|
| 470 |
+
max_length=self.sd_pipeline.tokenizer.model_max_length,
|
| 471 |
+
).input_ids.to(self.accelerator.device)
|
| 472 |
+
prompt_embeds = self.sd_pipeline.text_encoder(prompt_ids)[0]
|
| 473 |
+
|
| 474 |
+
with self.autocast():
|
| 475 |
+
sd_output = self.sd_pipeline(
|
| 476 |
+
prompt_embeds=prompt_embeds,
|
| 477 |
+
negative_prompt_embeds=sample_neg_prompt_embeds,
|
| 478 |
+
num_inference_steps=self.config.sample_num_steps,
|
| 479 |
+
guidance_scale=self.config.sample_guidance_scale,
|
| 480 |
+
eta=self.config.sample_eta,
|
| 481 |
+
output_type="pt",
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
images = sd_output.images
|
| 485 |
+
latents = sd_output.latents
|
| 486 |
+
log_probs = sd_output.log_probs
|
| 487 |
+
|
| 488 |
+
latents = torch.stack(latents, dim=1) # (batch_size, num_steps + 1, ...)
|
| 489 |
+
log_probs = torch.stack(log_probs, dim=1) # (batch_size, num_steps, 1)
|
| 490 |
+
timesteps = self.sd_pipeline.scheduler.timesteps.repeat(batch_size, 1) # (batch_size, num_steps)
|
| 491 |
+
|
| 492 |
+
samples.append(
|
| 493 |
+
{
|
| 494 |
+
"prompt_ids": prompt_ids,
|
| 495 |
+
"prompt_embeds": prompt_embeds,
|
| 496 |
+
"timesteps": timesteps,
|
| 497 |
+
"latents": latents[:, :-1], # each entry is the latent before timestep t
|
| 498 |
+
"next_latents": latents[:, 1:], # each entry is the latent after timestep t
|
| 499 |
+
"log_probs": log_probs,
|
| 500 |
+
"negative_prompt_embeds": sample_neg_prompt_embeds,
|
| 501 |
+
}
|
| 502 |
+
)
|
| 503 |
+
prompt_image_pairs.append([images, prompts, prompt_metadata])
|
| 504 |
+
|
| 505 |
+
return samples, prompt_image_pairs
|
| 506 |
+
|
| 507 |
+
def _train_batched_samples(self, inner_epoch, epoch, global_step, batched_samples):
|
| 508 |
+
"""
|
| 509 |
+
Train on a batch of samples. Main training segment
|
| 510 |
+
|
| 511 |
+
Args:
|
| 512 |
+
inner_epoch (int): The current inner epoch
|
| 513 |
+
epoch (int): The current epoch
|
| 514 |
+
global_step (int): The current global step
|
| 515 |
+
batched_samples (List[Dict[str, torch.Tensor]]): The batched samples to train on
|
| 516 |
+
|
| 517 |
+
Side Effects:
|
| 518 |
+
- Model weights are updated
|
| 519 |
+
- Logs the statistics to the accelerator trackers.
|
| 520 |
+
|
| 521 |
+
Returns:
|
| 522 |
+
global_step (int): The updated global step
|
| 523 |
+
"""
|
| 524 |
+
info = defaultdict(list)
|
| 525 |
+
for i, sample in enumerate(batched_samples):
|
| 526 |
+
if self.config.train_cfg:
|
| 527 |
+
# concat negative prompts to sample prompts to avoid two forward passes
|
| 528 |
+
embeds = torch.cat([sample["negative_prompt_embeds"], sample["prompt_embeds"]])
|
| 529 |
+
else:
|
| 530 |
+
embeds = sample["prompt_embeds"]
|
| 531 |
+
|
| 532 |
+
for j in range(self.num_train_timesteps):
|
| 533 |
+
with self.accelerator.accumulate(self.sd_pipeline.unet):
|
| 534 |
+
loss, approx_kl, clipfrac = self.calculate_loss(
|
| 535 |
+
sample["latents"][:, j],
|
| 536 |
+
sample["timesteps"][:, j],
|
| 537 |
+
sample["next_latents"][:, j],
|
| 538 |
+
sample["log_probs"][:, j],
|
| 539 |
+
sample["advantages"],
|
| 540 |
+
embeds,
|
| 541 |
+
)
|
| 542 |
+
info["approx_kl"].append(approx_kl)
|
| 543 |
+
info["clipfrac"].append(clipfrac)
|
| 544 |
+
info["loss"].append(loss)
|
| 545 |
+
|
| 546 |
+
self.accelerator.backward(loss)
|
| 547 |
+
if self.accelerator.sync_gradients:
|
| 548 |
+
self.accelerator.clip_grad_norm_(
|
| 549 |
+
self.trainable_layers.parameters()
|
| 550 |
+
if not isinstance(self.trainable_layers, list)
|
| 551 |
+
else self.trainable_layers,
|
| 552 |
+
self.config.train_max_grad_norm,
|
| 553 |
+
)
|
| 554 |
+
self.optimizer.step()
|
| 555 |
+
self.optimizer.zero_grad()
|
| 556 |
+
|
| 557 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 558 |
+
if self.accelerator.sync_gradients:
|
| 559 |
+
# log training-related stuff
|
| 560 |
+
info = {k: torch.mean(torch.stack(v)) for k, v in info.items()}
|
| 561 |
+
info = self.accelerator.reduce(info, reduction="mean")
|
| 562 |
+
info.update({"epoch": epoch, "inner_epoch": inner_epoch})
|
| 563 |
+
self.accelerator.log(info, step=global_step)
|
| 564 |
+
global_step += 1
|
| 565 |
+
info = defaultdict(list)
|
| 566 |
+
return global_step
|
| 567 |
+
|
| 568 |
+
def _config_check(self) -> Tuple[bool, str]:
|
| 569 |
+
samples_per_epoch = (
|
| 570 |
+
self.config.sample_batch_size * self.accelerator.num_processes * self.config.sample_num_batches_per_epoch
|
| 571 |
+
)
|
| 572 |
+
total_train_batch_size = (
|
| 573 |
+
self.config.train_batch_size
|
| 574 |
+
* self.accelerator.num_processes
|
| 575 |
+
* self.config.train_gradient_accumulation_steps
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
if not self.config.sample_batch_size >= self.config.train_batch_size:
|
| 579 |
+
return (
|
| 580 |
+
False,
|
| 581 |
+
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})",
|
| 582 |
+
)
|
| 583 |
+
if not self.config.sample_batch_size % self.config.train_batch_size == 0:
|
| 584 |
+
return (
|
| 585 |
+
False,
|
| 586 |
+
f"Sample batch size ({self.config.sample_batch_size}) must be divisible by the train batch size ({self.config.train_batch_size})",
|
| 587 |
+
)
|
| 588 |
+
if not samples_per_epoch % total_train_batch_size == 0:
|
| 589 |
+
return (
|
| 590 |
+
False,
|
| 591 |
+
f"Number of samples per epoch ({samples_per_epoch}) must be divisible by the total train batch size ({total_train_batch_size})",
|
| 592 |
+
)
|
| 593 |
+
return True, ""
|
| 594 |
+
|
| 595 |
+
def train(self, epochs: Optional[int] = None):
|
| 596 |
+
"""
|
| 597 |
+
Train the model for a given number of epochs
|
| 598 |
+
"""
|
| 599 |
+
global_step = 0
|
| 600 |
+
if epochs is None:
|
| 601 |
+
epochs = self.config.num_epochs
|
| 602 |
+
for epoch in range(self.first_epoch, epochs):
|
| 603 |
+
global_step = self.step(epoch, global_step)
|
| 604 |
+
|
| 605 |
+
def create_model_card(self, path: str, model_name: Optional[str] = "TRL DDPO Model") -> None:
|
| 606 |
+
"""Creates and saves a model card for a TRL model.
|
| 607 |
+
|
| 608 |
+
Args:
|
| 609 |
+
path (`str`): The path to save the model card to.
|
| 610 |
+
model_name (`str`, *optional*): The name of the model, defaults to `TRL DDPO Model`.
|
| 611 |
+
"""
|
| 612 |
+
try:
|
| 613 |
+
user = whoami()["name"]
|
| 614 |
+
# handle the offline case
|
| 615 |
+
except: # noqa
|
| 616 |
+
warnings.warn("Cannot retrieve user information assuming you are running in offline mode.")
|
| 617 |
+
return
|
| 618 |
+
|
| 619 |
+
if not os.path.exists(path):
|
| 620 |
+
os.makedirs(path)
|
| 621 |
+
|
| 622 |
+
model_card_content = MODEL_CARD_TEMPLATE.format(model_name=model_name, model_id=f"{user}/{path}")
|
| 623 |
+
with open(os.path.join(path, "README.md"), "w", encoding="utf-8") as f:
|
| 624 |
+
f.write(model_card_content)
|
| 625 |
+
|
| 626 |
+
def _save_pretrained(self, save_directory):
|
| 627 |
+
self.sd_pipeline.save_pretrained(save_directory)
|
| 628 |
+
self.create_model_card(save_directory)
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/dpo_trainer.py
ADDED
|
@@ -0,0 +1,1309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ed 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 |
+
if is_peft_available():
|
| 54 |
+
from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
if is_wandb_available():
|
| 58 |
+
import wandb
|
| 59 |
+
|
| 60 |
+
if is_deepspeed_available():
|
| 61 |
+
import deepspeed
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class DPOTrainer(Trainer):
|
| 65 |
+
r"""
|
| 66 |
+
Initialize DPOTrainer.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
model (`transformers.PreTrainedModel`):
|
| 70 |
+
The model to train, preferably an `AutoModelForSequenceClassification`.
|
| 71 |
+
ref_model (`PreTrainedModelWrapper`):
|
| 72 |
+
Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no
|
| 73 |
+
reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized.
|
| 74 |
+
beta (`float`, defaults to 0.1):
|
| 75 |
+
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.
|
| 76 |
+
label_smoothing (`float`, defaults to 0):
|
| 77 |
+
The robust DPO label smoothing parameter from the [cDPO](https://ericmitchell.ai/cdpo.pdf) report that should be between 0 and 0.5.
|
| 78 |
+
loss_type (`str`, defaults to `"sigmoid"`):
|
| 79 |
+
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).
|
| 80 |
+
args (`transformers.TrainingArguments`):
|
| 81 |
+
The arguments to use for training.
|
| 82 |
+
data_collator (`transformers.DataCollator`):
|
| 83 |
+
The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used
|
| 84 |
+
which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences.
|
| 85 |
+
label_pad_token_id (`int`, defaults to `-100`):
|
| 86 |
+
The label pad token id. This argument is required if you want to use the default data collator.
|
| 87 |
+
padding_value (`int`, defaults to `0`):
|
| 88 |
+
The padding value if it is different to the tokenizer's pad_token_id.
|
| 89 |
+
truncation_mode (`str`, defaults to `keep_end`):
|
| 90 |
+
The truncation mode to use, either `keep_end` or `keep_start`. This argument is required if you want to use the default data collator.
|
| 91 |
+
train_dataset (`datasets.Dataset`):
|
| 92 |
+
The dataset to use for training.
|
| 93 |
+
eval_dataset (`datasets.Dataset`):
|
| 94 |
+
The dataset to use for evaluation.
|
| 95 |
+
tokenizer (`transformers.PreTrainedTokenizerBase`):
|
| 96 |
+
The tokenizer to use for training. This argument is required if you want to use the default data collator.
|
| 97 |
+
model_init (`Callable[[], transformers.PreTrainedModel]`):
|
| 98 |
+
The model initializer to use for training. If None is specified, the default model initializer will be used.
|
| 99 |
+
callbacks (`List[transformers.TrainerCallback]`):
|
| 100 |
+
The callbacks to use for training.
|
| 101 |
+
optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
|
| 102 |
+
The optimizer and scheduler to use for training.
|
| 103 |
+
preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
|
| 104 |
+
The function to use to preprocess the logits before computing the metrics.
|
| 105 |
+
max_length (`int`, defaults to `None`):
|
| 106 |
+
The maximum length of the sequences in the batch. This argument is required if you want to use the default data collator.
|
| 107 |
+
max_prompt_length (`int`, defaults to `None`):
|
| 108 |
+
The maximum length of the prompt. This argument is required if you want to use the default data collator.
|
| 109 |
+
max_target_length (`int`, defaults to `None`):
|
| 110 |
+
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.
|
| 111 |
+
peft_config (`Dict`, defaults to `None`):
|
| 112 |
+
The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model.
|
| 113 |
+
is_encoder_decoder (`Optional[bool]`, `optional`, defaults to `None`):
|
| 114 |
+
If no model is provided, we need to know if the model_init returns an encoder-decoder.
|
| 115 |
+
disable_dropout (`bool`, defaults to `True`):
|
| 116 |
+
Whether or not to disable dropouts in `model` and `ref_model`.
|
| 117 |
+
generate_during_eval (`bool`, defaults to `False`):
|
| 118 |
+
Whether to sample and log generations during evaluation step.
|
| 119 |
+
compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*):
|
| 120 |
+
The function to use to compute the metrics. Must take a `EvalPrediction` and return
|
| 121 |
+
a dictionary string to metric values.
|
| 122 |
+
precompute_ref_log_probs (`bool`, defaults to `False`):
|
| 123 |
+
Flag to precompute reference model log probabilities and evaluation datasets. This is useful if you want to train
|
| 124 |
+
without the reference model and reduce the total GPU memory needed.
|
| 125 |
+
dataset_num_proc (`Optional[int]`, *optional*):
|
| 126 |
+
The number of workers to use to tokenize the data. Defaults to None.
|
| 127 |
+
model_init_kwargs (`Optional[Dict]`, *optional*):
|
| 128 |
+
Dict of Optional kwargs to pass when instantiating the model from a string
|
| 129 |
+
ref_model_init_kwargs (`Optional[Dict]`, *optional*):
|
| 130 |
+
Dict of Optional kwargs to pass when instantiating the ref model from a string
|
| 131 |
+
model_adapter_name (`str`, defaults to `None`):
|
| 132 |
+
Name of the train target PEFT adapter, when using LoRA with multiple adapters.
|
| 133 |
+
ref_adapter_name (`str`, defaults to `None`):
|
| 134 |
+
Name of the reference PEFT adapter, when using LoRA with multiple adapters.
|
| 135 |
+
reference_free (`bool`):
|
| 136 |
+
If True, we ignore the _provided_ reference model and implicitly use a reference model that assigns equal probability to all responses.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
_tag_names = ["trl", "dpo"]
|
| 140 |
+
|
| 141 |
+
def __init__(
|
| 142 |
+
self,
|
| 143 |
+
model: Optional[Union[PreTrainedModel, nn.Module, str]] = None,
|
| 144 |
+
ref_model: Optional[Union[PreTrainedModel, nn.Module, str]] = None,
|
| 145 |
+
dpo_alpha: float = 1.0,
|
| 146 |
+
beta: float = 0.1,
|
| 147 |
+
gamma: float = 0.1,
|
| 148 |
+
label_smoothing: float = 0,
|
| 149 |
+
loss_type: Literal["sigmoid", "hinge", "ipo", "kto_pair"] = "sigmoid",
|
| 150 |
+
args: Optional[TrainingArguments] = None,
|
| 151 |
+
data_collator: Optional[DataCollator] = None,
|
| 152 |
+
label_pad_token_id: int = -100,
|
| 153 |
+
padding_value: Optional[int] = None,
|
| 154 |
+
truncation_mode: str = "keep_end",
|
| 155 |
+
train_dataset: Optional[Dataset] = None,
|
| 156 |
+
eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None,
|
| 157 |
+
tokenizer: Optional[PreTrainedTokenizerBase] = None,
|
| 158 |
+
model_init: Optional[Callable[[], PreTrainedModel]] = None,
|
| 159 |
+
callbacks: Optional[List[TrainerCallback]] = None,
|
| 160 |
+
optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
|
| 161 |
+
preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
|
| 162 |
+
max_length: Optional[int] = None,
|
| 163 |
+
max_prompt_length: Optional[int] = None,
|
| 164 |
+
max_target_length: Optional[int] = None,
|
| 165 |
+
peft_config: Optional[Dict] = None,
|
| 166 |
+
is_encoder_decoder: Optional[bool] = None,
|
| 167 |
+
disable_dropout: bool = True,
|
| 168 |
+
generate_during_eval: bool = False,
|
| 169 |
+
compute_metrics: Optional[Callable[[EvalLoopOutput], Dict]] = None,
|
| 170 |
+
precompute_ref_log_probs: bool = False,
|
| 171 |
+
dataset_num_proc: Optional[int] = None,
|
| 172 |
+
model_init_kwargs: Optional[Dict] = None,
|
| 173 |
+
ref_model_init_kwargs: Optional[Dict] = None,
|
| 174 |
+
model_adapter_name: Optional[str] = None,
|
| 175 |
+
ref_adapter_name: Optional[str] = None,
|
| 176 |
+
reference_free: bool = False,
|
| 177 |
+
):
|
| 178 |
+
if model_init_kwargs is None:
|
| 179 |
+
model_init_kwargs = {}
|
| 180 |
+
elif not isinstance(model, str):
|
| 181 |
+
raise ValueError("You passed model_kwargs to the DPOTrainer. But your model is already instantiated.")
|
| 182 |
+
|
| 183 |
+
if ref_model_init_kwargs is None:
|
| 184 |
+
ref_model_init_kwargs = {}
|
| 185 |
+
elif not isinstance(ref_model, str):
|
| 186 |
+
raise ValueError(
|
| 187 |
+
"You passed ref_model_kwargs to the DPOTrainer. But your ref_model is already instantiated."
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
if isinstance(model, str):
|
| 191 |
+
warnings.warn(
|
| 192 |
+
"You passed a model_id to the DPOTrainer. This will automatically create an "
|
| 193 |
+
"`AutoModelForCausalLM` or a `PeftModel` (if you passed a `peft_config`) for you."
|
| 194 |
+
)
|
| 195 |
+
model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs)
|
| 196 |
+
|
| 197 |
+
if isinstance(ref_model, str):
|
| 198 |
+
warnings.warn(
|
| 199 |
+
"You passed a ref model_id to the DPOTrainer. This will automatically create an "
|
| 200 |
+
"`AutoModelForCausalLM`"
|
| 201 |
+
)
|
| 202 |
+
ref_model = AutoModelForCausalLM.from_pretrained(ref_model, **ref_model_init_kwargs)
|
| 203 |
+
|
| 204 |
+
# Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16`
|
| 205 |
+
# has been called in order to properly call autocast if needed.
|
| 206 |
+
self._peft_has_been_casted_to_bf16 = False
|
| 207 |
+
|
| 208 |
+
# model already loaded, skipped this part.
|
| 209 |
+
# if not is_peft_available() and peft_config is not None:
|
| 210 |
+
# raise ValueError(
|
| 211 |
+
# "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models"
|
| 212 |
+
# )
|
| 213 |
+
# elif is_peft_available() and peft_config is not None:
|
| 214 |
+
# # if model is a peft model and we have a peft_config, we merge and unload it first
|
| 215 |
+
# if isinstance(model, PeftModel):
|
| 216 |
+
# model = model.merge_and_unload()
|
| 217 |
+
|
| 218 |
+
# if ref_model is not None:
|
| 219 |
+
# raise ValueError(
|
| 220 |
+
# "You passed both a ref_model and a peft_config. For training PEFT adapters with DPO there is no need to pass a reference"
|
| 221 |
+
# " model. Please pass `ref_model=None` in case you want to train PEFT adapters."
|
| 222 |
+
# )
|
| 223 |
+
|
| 224 |
+
# if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False):
|
| 225 |
+
# _support_gc_kwargs = hasattr(
|
| 226 |
+
# args, "gradient_checkpointing_kwargs"
|
| 227 |
+
# ) and "gradient_checkpointing_kwargs" in list(
|
| 228 |
+
# inspect.signature(prepare_model_for_kbit_training).parameters
|
| 229 |
+
# )
|
| 230 |
+
|
| 231 |
+
# preprare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing}
|
| 232 |
+
|
| 233 |
+
# if _support_gc_kwargs:
|
| 234 |
+
# preprare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs
|
| 235 |
+
|
| 236 |
+
# model = prepare_model_for_kbit_training(model, **preprare_model_kwargs)
|
| 237 |
+
# elif getattr(args, "gradient_checkpointing", False):
|
| 238 |
+
# # For backward compatibility with older versions of transformers
|
| 239 |
+
# if hasattr(model, "enable_input_require_grads"):
|
| 240 |
+
# model.enable_input_require_grads()
|
| 241 |
+
# else:
|
| 242 |
+
|
| 243 |
+
# def make_inputs_require_grad(module, input, output):
|
| 244 |
+
# output.requires_grad_(True)
|
| 245 |
+
|
| 246 |
+
# model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
| 247 |
+
|
| 248 |
+
# # get peft model with the given config
|
| 249 |
+
# model = get_peft_model(model, peft_config)
|
| 250 |
+
# if args.bf16 and getattr(model, "is_loaded_in_4bit", False):
|
| 251 |
+
# peft_module_casting_to_bf16(model)
|
| 252 |
+
# # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager
|
| 253 |
+
# self._peft_has_been_casted_to_bf16 = True
|
| 254 |
+
|
| 255 |
+
# For models that use gradient_checkpoiting, we need to attach a hook that enables input
|
| 256 |
+
# to explicitly have `requires_grad=True`, otherwise training will either silently
|
| 257 |
+
# fail or completely fail.
|
| 258 |
+
# elif getattr(args, "gradient_checkpointing", False):
|
| 259 |
+
# # For backward compatibility with older versions of transformers
|
| 260 |
+
# if hasattr(model, "enable_input_require_grads"):
|
| 261 |
+
# model.enable_input_require_grads()
|
| 262 |
+
# else:
|
| 263 |
+
|
| 264 |
+
# def make_inputs_require_grad(module, input, output):
|
| 265 |
+
# output.requires_grad_(True)
|
| 266 |
+
|
| 267 |
+
# model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
| 268 |
+
|
| 269 |
+
if generate_during_eval and not is_wandb_available():
|
| 270 |
+
raise ValueError(
|
| 271 |
+
"`generate_during_eval=True` requires Weights and Biases to be installed."
|
| 272 |
+
" Please install `wandb` to resolve."
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
if model is not None:
|
| 276 |
+
self.is_encoder_decoder = model.config.is_encoder_decoder
|
| 277 |
+
elif is_encoder_decoder is None:
|
| 278 |
+
raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.")
|
| 279 |
+
else:
|
| 280 |
+
self.is_encoder_decoder = is_encoder_decoder
|
| 281 |
+
|
| 282 |
+
self.is_peft_model = is_peft_available() and isinstance(model, PeftModel)
|
| 283 |
+
self.model_adapter_name = model_adapter_name
|
| 284 |
+
self.ref_adapter_name = ref_adapter_name
|
| 285 |
+
self.reference_free = reference_free
|
| 286 |
+
|
| 287 |
+
if ref_model:
|
| 288 |
+
self.ref_model = ref_model
|
| 289 |
+
elif self.is_peft_model or precompute_ref_log_probs:
|
| 290 |
+
# The `model` with adapters turned off will be used as the reference model
|
| 291 |
+
self.ref_model = None
|
| 292 |
+
else:
|
| 293 |
+
self.ref_model = create_reference_model(model)
|
| 294 |
+
|
| 295 |
+
if tokenizer is None:
|
| 296 |
+
raise ValueError("tokenizer must be specified to tokenize a DPO dataset.")
|
| 297 |
+
if max_length is None:
|
| 298 |
+
warnings.warn(
|
| 299 |
+
"`max_length` is not set in the DPOTrainer's init"
|
| 300 |
+
" it will default to `512` by default, but you should do it yourself in the future.",
|
| 301 |
+
UserWarning,
|
| 302 |
+
)
|
| 303 |
+
max_length = 512
|
| 304 |
+
if max_prompt_length is None:
|
| 305 |
+
warnings.warn(
|
| 306 |
+
"`max_prompt_length` is not set in the DPOTrainer's init"
|
| 307 |
+
" it will default to `128` by default, but you should do it yourself in the future.",
|
| 308 |
+
UserWarning,
|
| 309 |
+
)
|
| 310 |
+
max_prompt_length = 128
|
| 311 |
+
|
| 312 |
+
if max_target_length is None and self.is_encoder_decoder:
|
| 313 |
+
warnings.warn(
|
| 314 |
+
"When using an encoder decoder architecture, you should set `max_target_length` in the DPOTrainer's init"
|
| 315 |
+
" it will default to `128` by default, but you should do it yourself in the future.",
|
| 316 |
+
UserWarning,
|
| 317 |
+
)
|
| 318 |
+
max_target_length = 128
|
| 319 |
+
|
| 320 |
+
if data_collator is None:
|
| 321 |
+
data_collator = DPODataCollatorWithPadding(
|
| 322 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 323 |
+
label_pad_token_id=label_pad_token_id,
|
| 324 |
+
is_encoder_decoder=self.is_encoder_decoder,
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
if args.remove_unused_columns:
|
| 328 |
+
args.remove_unused_columns = False
|
| 329 |
+
# warn users
|
| 330 |
+
warnings.warn(
|
| 331 |
+
"When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments"
|
| 332 |
+
" we have set it for you, but you should do it yourself in the future.",
|
| 333 |
+
UserWarning,
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
self.use_dpo_data_collator = True
|
| 337 |
+
else:
|
| 338 |
+
self.use_dpo_data_collator = False
|
| 339 |
+
|
| 340 |
+
if disable_dropout:
|
| 341 |
+
disable_dropout_in_model(model)
|
| 342 |
+
if self.ref_model is not None:
|
| 343 |
+
disable_dropout_in_model(self.ref_model)
|
| 344 |
+
|
| 345 |
+
self.max_length = max_length
|
| 346 |
+
self.generate_during_eval = generate_during_eval
|
| 347 |
+
self.label_pad_token_id = label_pad_token_id
|
| 348 |
+
self.padding_value = padding_value if padding_value is not None else tokenizer.pad_token_id
|
| 349 |
+
self.max_prompt_length = max_prompt_length
|
| 350 |
+
self.truncation_mode = truncation_mode
|
| 351 |
+
self.max_target_length = max_target_length
|
| 352 |
+
self.tokenizer = tokenizer
|
| 353 |
+
self.precompute_ref_log_probs = precompute_ref_log_probs
|
| 354 |
+
|
| 355 |
+
# Since ref_logs are precomputed on the first call to get_train/eval_dataloader
|
| 356 |
+
# keep track of first called to avoid computation of future calls
|
| 357 |
+
self._precomputed_train_ref_log_probs = False
|
| 358 |
+
self._precomputed_eval_ref_log_probs = False
|
| 359 |
+
|
| 360 |
+
if loss_type in ["hinge", "ipo", "kto_pair"] and label_smoothing > 0:
|
| 361 |
+
warnings.warn(
|
| 362 |
+
"You are using a loss type that does not support label smoothing. Ignoring label_smoothing parameter."
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
self.dpo_alpha = dpo_alpha
|
| 366 |
+
self.beta = beta
|
| 367 |
+
self.gamma = gamma
|
| 368 |
+
self.label_smoothing = label_smoothing
|
| 369 |
+
self.loss_type = loss_type
|
| 370 |
+
|
| 371 |
+
self._stored_metrics = defaultdict(lambda: defaultdict(list))
|
| 372 |
+
|
| 373 |
+
self.dataset_num_proc = dataset_num_proc
|
| 374 |
+
|
| 375 |
+
# Compute that only on the main process for faster data processing.
|
| 376 |
+
# see: https://github.com/huggingface/trl/pull/1255
|
| 377 |
+
# with PartialState().local_main_process_first():
|
| 378 |
+
# # tokenize the dataset
|
| 379 |
+
# train_dataset = train_dataset.map(self.tokenize_row, num_proc=self.dataset_num_proc)
|
| 380 |
+
# if eval_dataset is not None:
|
| 381 |
+
# eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=self.dataset_num_proc)
|
| 382 |
+
|
| 383 |
+
super().__init__(
|
| 384 |
+
model=model,
|
| 385 |
+
args=args,
|
| 386 |
+
data_collator=data_collator,
|
| 387 |
+
train_dataset=train_dataset,
|
| 388 |
+
eval_dataset=eval_dataset,
|
| 389 |
+
tokenizer=tokenizer,
|
| 390 |
+
model_init=model_init,
|
| 391 |
+
compute_metrics=compute_metrics,
|
| 392 |
+
callbacks=callbacks,
|
| 393 |
+
optimizers=optimizers,
|
| 394 |
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
if not hasattr(self, "accelerator"):
|
| 398 |
+
raise AttributeError(
|
| 399 |
+
"Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`."
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
# Deepspeed Zero-3 does not support precompute_ref_log_probs
|
| 403 |
+
if self.is_deepspeed_enabled:
|
| 404 |
+
if self.accelerator.state.deepspeed_plugin.zero_stage == 3 and self.precompute_ref_log_probs:
|
| 405 |
+
raise ValueError(
|
| 406 |
+
"You cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`."
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
if self.ref_model is None:
|
| 410 |
+
if not (self.is_peft_model or self.precompute_ref_log_probs):
|
| 411 |
+
raise ValueError(
|
| 412 |
+
"No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`"
|
| 413 |
+
)
|
| 414 |
+
else:
|
| 415 |
+
if self.is_deepspeed_enabled:
|
| 416 |
+
self.ref_model = self._prepare_deepspeed(self.ref_model)
|
| 417 |
+
else:
|
| 418 |
+
self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
|
| 419 |
+
|
| 420 |
+
def _prepare_deepspeed(self, model: PreTrainedModelWrapper):
|
| 421 |
+
# Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473
|
| 422 |
+
deepspeed_plugin = self.accelerator.state.deepspeed_plugin
|
| 423 |
+
config_kwargs = deepcopy(deepspeed_plugin.deepspeed_config)
|
| 424 |
+
|
| 425 |
+
if model is not None:
|
| 426 |
+
if hasattr(model, "config"):
|
| 427 |
+
hidden_size = (
|
| 428 |
+
max(model.config.hidden_sizes)
|
| 429 |
+
if getattr(model.config, "hidden_sizes", None)
|
| 430 |
+
else getattr(model.config, "hidden_size", None)
|
| 431 |
+
)
|
| 432 |
+
if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3:
|
| 433 |
+
# Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0`
|
| 434 |
+
# This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081
|
| 435 |
+
config_kwargs.update(
|
| 436 |
+
{
|
| 437 |
+
"zero_optimization.reduce_bucket_size": hidden_size * hidden_size,
|
| 438 |
+
"zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size,
|
| 439 |
+
"zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size,
|
| 440 |
+
}
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
# If ZeRO-3 is used, we shard both the active and reference model.
|
| 444 |
+
# Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO disabled (stage 0)
|
| 445 |
+
if config_kwargs["zero_optimization"]["stage"] != 3:
|
| 446 |
+
config_kwargs["zero_optimization"]["stage"] = 0
|
| 447 |
+
model, *_ = deepspeed.initialize(model=model, config=config_kwargs)
|
| 448 |
+
model.eval()
|
| 449 |
+
return model
|
| 450 |
+
|
| 451 |
+
def get_train_dataloader(self) -> DataLoader:
|
| 452 |
+
"""
|
| 453 |
+
Returns the training [`~torch.utils.data.DataLoader`].
|
| 454 |
+
|
| 455 |
+
Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`.
|
| 456 |
+
"""
|
| 457 |
+
|
| 458 |
+
if self.precompute_ref_log_probs and not self._precomputed_train_ref_log_probs:
|
| 459 |
+
dataloader_params = {
|
| 460 |
+
"batch_size": self.args.per_device_train_batch_size,
|
| 461 |
+
"collate_fn": self.data_collator,
|
| 462 |
+
"num_workers": self.args.dataloader_num_workers,
|
| 463 |
+
"pin_memory": self.args.dataloader_pin_memory,
|
| 464 |
+
"shuffle": False,
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
# prepare dataloader
|
| 468 |
+
data_loader = self.accelerator.prepare(DataLoader(self.train_dataset, **dataloader_params))
|
| 469 |
+
|
| 470 |
+
reference_chosen_logps = []
|
| 471 |
+
reference_rejected_logps = []
|
| 472 |
+
for padded_batch in tqdm(iterable=data_loader, desc="Train dataset reference log probs"):
|
| 473 |
+
reference_chosen_logp, reference_rejected_logp = self.compute_reference_log_probs(padded_batch)
|
| 474 |
+
reference_chosen_logp, reference_rejected_logp = self.accelerator.gather_for_metrics(
|
| 475 |
+
(reference_chosen_logp, reference_rejected_logp)
|
| 476 |
+
)
|
| 477 |
+
reference_chosen_logps.append(reference_chosen_logp.cpu())
|
| 478 |
+
reference_rejected_logps.append(reference_rejected_logp.cpu())
|
| 479 |
+
|
| 480 |
+
all_reference_chosen_logps = torch.cat(reference_chosen_logps).float().numpy()
|
| 481 |
+
all_reference_rejected_logps = torch.cat(reference_rejected_logps).float().numpy()
|
| 482 |
+
|
| 483 |
+
self.train_dataset = self.train_dataset.add_column(
|
| 484 |
+
name="reference_chosen_logps", column=all_reference_chosen_logps
|
| 485 |
+
)
|
| 486 |
+
self.train_dataset = self.train_dataset.add_column(
|
| 487 |
+
name="reference_rejected_logps", column=all_reference_rejected_logps
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
self._precomputed_train_ref_log_probs = True
|
| 491 |
+
|
| 492 |
+
return super().get_train_dataloader()
|
| 493 |
+
|
| 494 |
+
def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader:
|
| 495 |
+
"""
|
| 496 |
+
Returns the evaluation [`~torch.utils.data.DataLoader`].
|
| 497 |
+
|
| 498 |
+
Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`.
|
| 499 |
+
|
| 500 |
+
Args:
|
| 501 |
+
eval_dataset (`torch.utils.data.Dataset`, *optional*):
|
| 502 |
+
If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted
|
| 503 |
+
by the `model.forward()` method are automatically removed. It must implement `__len__`.
|
| 504 |
+
"""
|
| 505 |
+
if eval_dataset is None and self.eval_dataset is None:
|
| 506 |
+
raise ValueError("Trainer: evaluation requires an eval_dataset.")
|
| 507 |
+
eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset
|
| 508 |
+
|
| 509 |
+
if self.precompute_ref_log_probs and not self._precomputed_eval_ref_log_probs:
|
| 510 |
+
dataloader_params = {
|
| 511 |
+
"batch_size": self.args.per_device_eval_batch_size,
|
| 512 |
+
"collate_fn": self.data_collator,
|
| 513 |
+
"num_workers": self.args.dataloader_num_workers,
|
| 514 |
+
"pin_memory": self.args.dataloader_pin_memory,
|
| 515 |
+
"shuffle": False,
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
# prepare dataloader
|
| 519 |
+
data_loader = self.accelerator.prepare(DataLoader(eval_dataset, **dataloader_params))
|
| 520 |
+
|
| 521 |
+
reference_chosen_logps = []
|
| 522 |
+
reference_rejected_logps = []
|
| 523 |
+
for padded_batch in tqdm(iterable=data_loader, desc="Eval dataset reference log probs"):
|
| 524 |
+
reference_chosen_logp, reference_rejected_logp = self.compute_reference_log_probs(padded_batch)
|
| 525 |
+
reference_chosen_logp, reference_rejected_logp = self.accelerator.gather_for_metrics(
|
| 526 |
+
(reference_chosen_logp, reference_rejected_logp)
|
| 527 |
+
)
|
| 528 |
+
reference_chosen_logps.append(reference_chosen_logp.cpu())
|
| 529 |
+
reference_rejected_logps.append(reference_rejected_logp.cpu())
|
| 530 |
+
|
| 531 |
+
all_reference_chosen_logps = torch.cat(reference_chosen_logps).float().numpy()
|
| 532 |
+
all_reference_rejected_logps = torch.cat(reference_rejected_logps).float().numpy()
|
| 533 |
+
|
| 534 |
+
eval_dataset = eval_dataset.add_column(name="reference_chosen_logps", column=all_reference_chosen_logps)
|
| 535 |
+
eval_dataset = eval_dataset.add_column(name="reference_rejected_logps", column=all_reference_rejected_logps)
|
| 536 |
+
|
| 537 |
+
# Save calculated reference_chosen_logps and reference_rejected_logps to the eval_dataset for subsequent runs
|
| 538 |
+
if self.eval_dataset is not None:
|
| 539 |
+
self.eval_dataset = eval_dataset
|
| 540 |
+
self._precomputed_eval_ref_log_probs = True
|
| 541 |
+
|
| 542 |
+
return super().get_eval_dataloader(eval_dataset=eval_dataset)
|
| 543 |
+
|
| 544 |
+
def build_tokenized_answer(self, prompt, answer):
|
| 545 |
+
"""
|
| 546 |
+
Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`.
|
| 547 |
+
It does ensure `enc(a + b) = enc(a) + enc(a + b)[len(enc(a)):]`.
|
| 548 |
+
Reference:
|
| 549 |
+
https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
|
| 550 |
+
"""
|
| 551 |
+
|
| 552 |
+
full_tokenized = self.tokenizer(prompt + answer, add_special_tokens=False)
|
| 553 |
+
prompt_input_ids = self.tokenizer(prompt, add_special_tokens=False)["input_ids"]
|
| 554 |
+
|
| 555 |
+
answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :]
|
| 556 |
+
answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :]
|
| 557 |
+
|
| 558 |
+
# Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]`
|
| 559 |
+
full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids])
|
| 560 |
+
|
| 561 |
+
# Prepare input tokens for token by token comparison
|
| 562 |
+
full_input_ids = np.array(full_tokenized["input_ids"])
|
| 563 |
+
|
| 564 |
+
if len(full_input_ids) != len(full_concat_input_ids):
|
| 565 |
+
raise ValueError("Prompt input ids and answer input ids should have the same length.")
|
| 566 |
+
|
| 567 |
+
# On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens
|
| 568 |
+
# can be merged together when tokenizing prompt+answer. This could result
|
| 569 |
+
# on the last token from the prompt being different when tokenized on its own
|
| 570 |
+
# vs when done as prompt+answer.
|
| 571 |
+
response_token_ids_start_idx = len(prompt_input_ids)
|
| 572 |
+
|
| 573 |
+
# If tokenized prompt is different than both prompt+answer, then it means the
|
| 574 |
+
# last token has changed due to merging.
|
| 575 |
+
if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]:
|
| 576 |
+
response_token_ids_start_idx -= 1
|
| 577 |
+
|
| 578 |
+
prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx]
|
| 579 |
+
prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx]
|
| 580 |
+
|
| 581 |
+
if len(prompt_input_ids) != len(prompt_attention_mask):
|
| 582 |
+
raise ValueError("Prompt input ids and attention mask should have the same length.")
|
| 583 |
+
|
| 584 |
+
answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:]
|
| 585 |
+
answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:]
|
| 586 |
+
|
| 587 |
+
return dict(
|
| 588 |
+
prompt_input_ids=prompt_input_ids,
|
| 589 |
+
prompt_attention_mask=prompt_attention_mask,
|
| 590 |
+
input_ids=answer_input_ids,
|
| 591 |
+
attention_mask=answer_attention_mask,
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
def tokenize_row(self, feature, model: Optional[Union[PreTrainedModel, nn.Module]] = None) -> Dict:
|
| 595 |
+
"""Tokenize a single row from a DPO specific dataset.
|
| 596 |
+
|
| 597 |
+
At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation
|
| 598 |
+
in case the prompt + chosen or prompt + rejected responses is/are too long. First
|
| 599 |
+
we truncate the prompt; if we're still too long, we truncate the chosen/rejected.
|
| 600 |
+
|
| 601 |
+
We also create the labels for the chosen/rejected responses, which are of length equal to
|
| 602 |
+
the sum of the length of the prompt and the chosen/rejected response, with
|
| 603 |
+
label_pad_token_id for the prompt tokens.
|
| 604 |
+
"""
|
| 605 |
+
batch = {}
|
| 606 |
+
prompt = feature["prompt"]
|
| 607 |
+
chosen = feature["chosen"]
|
| 608 |
+
rejected = feature["rejected"]
|
| 609 |
+
|
| 610 |
+
if not self.is_encoder_decoder:
|
| 611 |
+
# Check issues below for more details
|
| 612 |
+
# 1. https://github.com/huggingface/trl/issues/907
|
| 613 |
+
# 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
|
| 614 |
+
# 3. https://github.com/LianjiaTech/BELLE/issues/337
|
| 615 |
+
|
| 616 |
+
if not isinstance(prompt, str):
|
| 617 |
+
raise ValueError(f"prompt should be an str but got {type(prompt)}")
|
| 618 |
+
prompt_tokens = self.tokenizer(prompt, add_special_tokens=False)
|
| 619 |
+
prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()}
|
| 620 |
+
|
| 621 |
+
if not isinstance(chosen, str):
|
| 622 |
+
raise ValueError(f"chosen should be an str but got {type(chosen)}")
|
| 623 |
+
chosen_tokens = self.build_tokenized_answer(prompt, chosen)
|
| 624 |
+
|
| 625 |
+
if not isinstance(rejected, str):
|
| 626 |
+
raise ValueError(f"rejected should be an str but got {type(rejected)}")
|
| 627 |
+
rejected_tokens = self.build_tokenized_answer(prompt, rejected)
|
| 628 |
+
|
| 629 |
+
# Last prompt token might get merged by tokenizer and
|
| 630 |
+
# it should not be included for generation if that happens
|
| 631 |
+
prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"])
|
| 632 |
+
|
| 633 |
+
chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"])
|
| 634 |
+
rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"])
|
| 635 |
+
prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids)
|
| 636 |
+
|
| 637 |
+
for k, v in prompt_tokens.items():
|
| 638 |
+
prompt_tokens[k] = v[:prompt_len_input_ids]
|
| 639 |
+
|
| 640 |
+
# Make sure prompts only have one different token at most an
|
| 641 |
+
# and length only differs by 1 at most
|
| 642 |
+
num_diff_tokens = sum(
|
| 643 |
+
[a != b for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"])]
|
| 644 |
+
)
|
| 645 |
+
num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids)
|
| 646 |
+
if num_diff_tokens > 1 or num_diff_len > 1:
|
| 647 |
+
raise ValueError(
|
| 648 |
+
"Chosen and rejected prompt_input_ids might only differ on the "
|
| 649 |
+
"last token due to tokenizer merge ops."
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
# add BOS token to head of prompt
|
| 653 |
+
prompt_tokens["prompt_input_ids"] = [self.tokenizer.bos_token_id] + prompt_tokens["prompt_input_ids"]
|
| 654 |
+
chosen_tokens["prompt_input_ids"] = [self.tokenizer.bos_token_id] + chosen_tokens["prompt_input_ids"]
|
| 655 |
+
rejected_tokens["prompt_input_ids"] = [self.tokenizer.bos_token_id] + rejected_tokens["prompt_input_ids"]
|
| 656 |
+
|
| 657 |
+
prompt_tokens["prompt_attention_mask"] = [1] + prompt_tokens["prompt_attention_mask"]
|
| 658 |
+
chosen_tokens["prompt_attention_mask"] = [1] + chosen_tokens["prompt_attention_mask"]
|
| 659 |
+
rejected_tokens["prompt_attention_mask"] = [1] + rejected_tokens["prompt_attention_mask"]
|
| 660 |
+
|
| 661 |
+
# add EOS token to end of answer
|
| 662 |
+
chosen_tokens["input_ids"].append(self.tokenizer.eos_token_id)
|
| 663 |
+
chosen_tokens["attention_mask"].append(1)
|
| 664 |
+
|
| 665 |
+
rejected_tokens["input_ids"].append(self.tokenizer.eos_token_id)
|
| 666 |
+
rejected_tokens["attention_mask"].append(1)
|
| 667 |
+
|
| 668 |
+
longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"]))
|
| 669 |
+
|
| 670 |
+
# if combined sequence is too long, truncate the prompt
|
| 671 |
+
for answer_tokens in [chosen_tokens, rejected_tokens, prompt_tokens]:
|
| 672 |
+
if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length:
|
| 673 |
+
if self.truncation_mode == "keep_start":
|
| 674 |
+
for k in ["prompt_input_ids", "prompt_attention_mask"]:
|
| 675 |
+
answer_tokens[k] = answer_tokens[k][: self.max_prompt_length]
|
| 676 |
+
elif self.truncation_mode == "keep_end":
|
| 677 |
+
for k in ["prompt_input_ids", "prompt_attention_mask"]:
|
| 678 |
+
answer_tokens[k] = answer_tokens[k][-self.max_prompt_length :]
|
| 679 |
+
else:
|
| 680 |
+
raise ValueError(f"Unknown truncation mode: {self.truncation_mode}")
|
| 681 |
+
|
| 682 |
+
# if that's still too long, truncate the response
|
| 683 |
+
for answer_tokens in [chosen_tokens, rejected_tokens]:
|
| 684 |
+
if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length:
|
| 685 |
+
for k in ["input_ids", "attention_mask"]:
|
| 686 |
+
answer_tokens[k] = answer_tokens[k][: self.max_length - self.max_prompt_length]
|
| 687 |
+
|
| 688 |
+
# Create labels
|
| 689 |
+
chosen_sequence_tokens = {
|
| 690 |
+
k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"]
|
| 691 |
+
}
|
| 692 |
+
rejected_sequence_tokens = {
|
| 693 |
+
k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"]
|
| 694 |
+
}
|
| 695 |
+
chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:]
|
| 696 |
+
chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [
|
| 697 |
+
self.label_pad_token_id
|
| 698 |
+
] * len(chosen_tokens["prompt_input_ids"])
|
| 699 |
+
rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:]
|
| 700 |
+
rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [
|
| 701 |
+
self.label_pad_token_id
|
| 702 |
+
] * len(rejected_tokens["prompt_input_ids"])
|
| 703 |
+
|
| 704 |
+
for k, toks in {
|
| 705 |
+
"chosen_": chosen_sequence_tokens,
|
| 706 |
+
"rejected_": rejected_sequence_tokens,
|
| 707 |
+
"": prompt_tokens,
|
| 708 |
+
}.items():
|
| 709 |
+
for type_key, tokens in toks.items():
|
| 710 |
+
if type_key == "token_type_ids":
|
| 711 |
+
continue
|
| 712 |
+
batch[f"{k}{type_key}"] = tokens
|
| 713 |
+
|
| 714 |
+
else:
|
| 715 |
+
chosen_tokens = self.tokenizer(
|
| 716 |
+
chosen, truncation=True, max_length=self.max_target_length, add_special_tokens=True
|
| 717 |
+
)
|
| 718 |
+
rejected_tokens = self.tokenizer(
|
| 719 |
+
rejected, truncation=True, max_length=self.max_target_length, add_special_tokens=True
|
| 720 |
+
)
|
| 721 |
+
prompt_tokens = self.tokenizer(
|
| 722 |
+
prompt, truncation=True, max_length=self.max_prompt_length, add_special_tokens=True
|
| 723 |
+
)
|
| 724 |
+
|
| 725 |
+
batch["chosen_labels"] = chosen_tokens["input_ids"]
|
| 726 |
+
batch["rejected_labels"] = rejected_tokens["input_ids"]
|
| 727 |
+
batch["prompt_input_ids"] = prompt_tokens["input_ids"]
|
| 728 |
+
batch["prompt_attention_mask"] = prompt_tokens["attention_mask"]
|
| 729 |
+
|
| 730 |
+
if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"):
|
| 731 |
+
batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(
|
| 732 |
+
labels=batch["rejected_labels"]
|
| 733 |
+
)
|
| 734 |
+
batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(
|
| 735 |
+
labels=batch["chosen_labels"]
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
return batch
|
| 739 |
+
|
| 740 |
+
@contextmanager
|
| 741 |
+
def null_ref_context(self):
|
| 742 |
+
"""Context manager for handling null reference model (that is, peft adapter manipulation)."""
|
| 743 |
+
with self.accelerator.unwrap_model(
|
| 744 |
+
self.model
|
| 745 |
+
).disable_adapter() if self.is_peft_model and not self.ref_adapter_name else nullcontext():
|
| 746 |
+
if self.ref_adapter_name:
|
| 747 |
+
self.model.set_adapter(self.ref_adapter_name)
|
| 748 |
+
yield
|
| 749 |
+
if self.ref_adapter_name:
|
| 750 |
+
self.model.set_adapter(self.model_adapter_name or "default")
|
| 751 |
+
|
| 752 |
+
def compute_reference_log_probs(self, padded_batch: Dict) -> Dict:
|
| 753 |
+
"""Computes log probabilities of the reference model for a single padded batch of a DPO specific dataset."""
|
| 754 |
+
compte_ref_context_manager = torch.cuda.amp.autocast if self._peft_has_been_casted_to_bf16 else nullcontext
|
| 755 |
+
|
| 756 |
+
# compute reference logps
|
| 757 |
+
with torch.no_grad(), compte_ref_context_manager():
|
| 758 |
+
if self.ref_model is None:
|
| 759 |
+
with self.null_ref_context():
|
| 760 |
+
(
|
| 761 |
+
reference_chosen_logps,
|
| 762 |
+
reference_rejected_logps,
|
| 763 |
+
_,
|
| 764 |
+
_,
|
| 765 |
+
) = self.concatenated_forward(self.model, padded_batch)
|
| 766 |
+
else:
|
| 767 |
+
(
|
| 768 |
+
reference_chosen_logps,
|
| 769 |
+
reference_rejected_logps,
|
| 770 |
+
_,
|
| 771 |
+
_,
|
| 772 |
+
) = self.concatenated_forward(self.ref_model, padded_batch)
|
| 773 |
+
|
| 774 |
+
return reference_chosen_logps, reference_rejected_logps
|
| 775 |
+
|
| 776 |
+
@staticmethod
|
| 777 |
+
def concatenated_inputs(
|
| 778 |
+
batch: Dict[str, Union[List, torch.LongTensor]],
|
| 779 |
+
is_encoder_decoder: bool = False,
|
| 780 |
+
label_pad_token_id: int = -100,
|
| 781 |
+
padding_value: int = 0,
|
| 782 |
+
device: Optional[torch.device] = None,
|
| 783 |
+
) -> Dict[str, torch.LongTensor]:
|
| 784 |
+
"""Concatenate the chosen and rejected inputs into a single tensor.
|
| 785 |
+
|
| 786 |
+
Args:
|
| 787 |
+
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).
|
| 788 |
+
is_encoder_decoder: Whether the model is an encoder-decoder model.
|
| 789 |
+
label_pad_token_id: The label pad token id.
|
| 790 |
+
padding_value: The padding value to use for the concatenated inputs_ids.
|
| 791 |
+
device: The device for the concatenated inputs.
|
| 792 |
+
|
| 793 |
+
Returns:
|
| 794 |
+
A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'.
|
| 795 |
+
"""
|
| 796 |
+
concatenated_batch = {}
|
| 797 |
+
|
| 798 |
+
if is_encoder_decoder:
|
| 799 |
+
max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1])
|
| 800 |
+
else:
|
| 801 |
+
max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1])
|
| 802 |
+
|
| 803 |
+
for k in batch:
|
| 804 |
+
if k.startswith("chosen") and isinstance(batch[k], torch.Tensor):
|
| 805 |
+
if "labels" in k or is_encoder_decoder:
|
| 806 |
+
pad_value = label_pad_token_id
|
| 807 |
+
elif k.endswith("_input_ids"):
|
| 808 |
+
pad_value = padding_value
|
| 809 |
+
elif k.endswith("_attention_mask"):
|
| 810 |
+
pad_value = 0
|
| 811 |
+
concatenated_key = k.replace("chosen", "concatenated")
|
| 812 |
+
concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value)
|
| 813 |
+
for k in batch:
|
| 814 |
+
if k.startswith("rejected") and isinstance(batch[k], torch.Tensor):
|
| 815 |
+
if "labels" in k or is_encoder_decoder:
|
| 816 |
+
pad_value = label_pad_token_id
|
| 817 |
+
elif k.endswith("_input_ids"):
|
| 818 |
+
pad_value = padding_value
|
| 819 |
+
elif k.endswith("_attention_mask"):
|
| 820 |
+
pad_value = 0
|
| 821 |
+
concatenated_key = k.replace("rejected", "concatenated")
|
| 822 |
+
concatenated_batch[concatenated_key] = torch.cat(
|
| 823 |
+
(
|
| 824 |
+
concatenated_batch[concatenated_key],
|
| 825 |
+
pad_to_length(batch[k], max_length, pad_value=pad_value),
|
| 826 |
+
),
|
| 827 |
+
dim=0,
|
| 828 |
+
).to(device=device)
|
| 829 |
+
|
| 830 |
+
if is_encoder_decoder:
|
| 831 |
+
concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device)
|
| 832 |
+
concatenated_batch["concatenated_attention_mask"] = (
|
| 833 |
+
batch["prompt_attention_mask"].repeat(2, 1).to(device=device)
|
| 834 |
+
)
|
| 835 |
+
repeated_list = torch.cat(batch["images"] + batch["images"], dim=0)
|
| 836 |
+
concatenated_batch["concatenated_images"] = repeated_list
|
| 837 |
+
return concatenated_batch
|
| 838 |
+
|
| 839 |
+
def dpo_loss(
|
| 840 |
+
self,
|
| 841 |
+
policy_chosen_logps: torch.FloatTensor,
|
| 842 |
+
policy_rejected_logps: torch.FloatTensor,
|
| 843 |
+
reference_chosen_logps: torch.FloatTensor,
|
| 844 |
+
reference_rejected_logps: torch.FloatTensor,
|
| 845 |
+
) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
|
| 846 |
+
"""Compute the DPO loss for a batch of policy and reference model log probabilities.
|
| 847 |
+
|
| 848 |
+
Args:
|
| 849 |
+
policy_chosen_logps: Log probabilities of the policy model for the chosen responses. Shape: (batch_size,)
|
| 850 |
+
policy_rejected_logps: Log probabilities of the policy model for the rejected responses. Shape: (batch_size,)
|
| 851 |
+
reference_chosen_logps: Log probabilities of the reference model for the chosen responses. Shape: (batch_size,)
|
| 852 |
+
reference_rejected_logps: Log probabilities of the reference model for the rejected responses. Shape: (batch_size,)
|
| 853 |
+
|
| 854 |
+
Returns:
|
| 855 |
+
A tuple of three tensors: (losses, chosen_rewards, rejected_rewards).
|
| 856 |
+
The losses tensor contains the DPO loss for each example in the batch.
|
| 857 |
+
The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively.
|
| 858 |
+
"""
|
| 859 |
+
pi_logratios = policy_chosen_logps - policy_rejected_logps
|
| 860 |
+
if self.reference_free:
|
| 861 |
+
ref_logratios = torch.tensor([0], dtype=pi_logratios.dtype, device=pi_logratios.device)
|
| 862 |
+
else:
|
| 863 |
+
ref_logratios = reference_chosen_logps - reference_rejected_logps
|
| 864 |
+
|
| 865 |
+
pi_logratios = pi_logratios.to(self.accelerator.device)
|
| 866 |
+
ref_logratios = ref_logratios.to(self.accelerator.device)
|
| 867 |
+
logits = pi_logratios - ref_logratios
|
| 868 |
+
# print(f"pi log ratios: {pi_logratios}")
|
| 869 |
+
# print(f"ref log ratios: {ref_logratios}")
|
| 870 |
+
# print(f"logits: {logits}")
|
| 871 |
+
# The beta is a temperature parameter for the DPO loss, typically something in the range of 0.1 to 0.5.
|
| 872 |
+
# We ignore the reference model as beta -> 0. The label_smoothing parameter encodes our uncertainty about the labels and
|
| 873 |
+
# calculates a conservative DPO loss.
|
| 874 |
+
if self.loss_type == "sigmoid":
|
| 875 |
+
losses = (
|
| 876 |
+
-F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing)
|
| 877 |
+
- F.logsigmoid(-self.beta * logits) * self.label_smoothing
|
| 878 |
+
)
|
| 879 |
+
elif self.loss_type == "hinge":
|
| 880 |
+
losses = torch.relu(1 - self.beta * logits)
|
| 881 |
+
elif self.loss_type == "ipo":
|
| 882 |
+
# eqn (17) of the paper where beta is the regularization parameter for the IPO loss, denoted by tau in the paper.
|
| 883 |
+
losses = (logits - 1 / (2 * self.beta)) ** 2
|
| 884 |
+
elif self.loss_type == "kto_pair":
|
| 885 |
+
# eqn (7) of the HALOs paper
|
| 886 |
+
chosen_KL = (policy_chosen_logps - reference_chosen_logps).mean().clamp(min=0)
|
| 887 |
+
rejected_KL = (policy_rejected_logps - reference_rejected_logps).mean().clamp(min=0)
|
| 888 |
+
|
| 889 |
+
chosen_logratios = policy_chosen_logps - reference_chosen_logps
|
| 890 |
+
rejected_logratios = policy_rejected_logps - reference_rejected_logps
|
| 891 |
+
# As described in the KTO report, the KL term for chosen (rejected) is estimated using the rejected (chosen) half.
|
| 892 |
+
losses = torch.cat(
|
| 893 |
+
(
|
| 894 |
+
1 - F.sigmoid(self.beta * (chosen_logratios - rejected_KL)),
|
| 895 |
+
1 - F.sigmoid(self.beta * (chosen_KL - rejected_logratios)),
|
| 896 |
+
),
|
| 897 |
+
0,
|
| 898 |
+
)
|
| 899 |
+
else:
|
| 900 |
+
raise ValueError(
|
| 901 |
+
f"Unknown loss type: {self.loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'kto_pair']"
|
| 902 |
+
)
|
| 903 |
+
|
| 904 |
+
chosen_rewards = (
|
| 905 |
+
self.beta
|
| 906 |
+
* (
|
| 907 |
+
policy_chosen_logps.to(self.accelerator.device) - reference_chosen_logps.to(self.accelerator.device)
|
| 908 |
+
).detach()
|
| 909 |
+
)
|
| 910 |
+
rejected_rewards = (
|
| 911 |
+
self.beta
|
| 912 |
+
* (
|
| 913 |
+
policy_rejected_logps.to(self.accelerator.device) - reference_rejected_logps.to(self.accelerator.device)
|
| 914 |
+
).detach()
|
| 915 |
+
)
|
| 916 |
+
|
| 917 |
+
return losses, chosen_rewards, rejected_rewards
|
| 918 |
+
|
| 919 |
+
@staticmethod
|
| 920 |
+
def get_batch_logps(
|
| 921 |
+
logits: torch.FloatTensor,
|
| 922 |
+
labels: torch.LongTensor,
|
| 923 |
+
average_log_prob: bool = False,
|
| 924 |
+
label_pad_token_id: int = -100,
|
| 925 |
+
is_encoder_decoder: bool = False,
|
| 926 |
+
) -> torch.FloatTensor:
|
| 927 |
+
"""Compute the log probabilities of the given labels under the given logits.
|
| 928 |
+
|
| 929 |
+
Args:
|
| 930 |
+
logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size)
|
| 931 |
+
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)
|
| 932 |
+
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.
|
| 933 |
+
label_pad_token_id: The label pad token id.
|
| 934 |
+
is_encoder_decoder: Whether the model is an encoder-decoder model.
|
| 935 |
+
|
| 936 |
+
Returns:
|
| 937 |
+
A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the given logits.
|
| 938 |
+
"""
|
| 939 |
+
if logits.shape[:-1] != labels.shape:
|
| 940 |
+
raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.")
|
| 941 |
+
|
| 942 |
+
if not is_encoder_decoder:
|
| 943 |
+
labels = labels[:, 1:].clone()
|
| 944 |
+
logits = logits[:, :-1, :]
|
| 945 |
+
loss_mask = labels != label_pad_token_id
|
| 946 |
+
|
| 947 |
+
# dummy token; we'll ignore the losses on these tokens later
|
| 948 |
+
labels[labels == label_pad_token_id] = 0
|
| 949 |
+
|
| 950 |
+
per_token_logps = torch.gather(logits.log_softmax(-1), dim=2, index=labels.unsqueeze(2)).squeeze(2)
|
| 951 |
+
|
| 952 |
+
if average_log_prob:
|
| 953 |
+
return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1)
|
| 954 |
+
else:
|
| 955 |
+
return (per_token_logps * loss_mask).sum(-1)
|
| 956 |
+
|
| 957 |
+
def get_sft_loss(self, logits, labels):
|
| 958 |
+
# Shift so that tokens < n predict n
|
| 959 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 960 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 961 |
+
# Flatten the tokens
|
| 962 |
+
loss_fct = nn.CrossEntropyLoss()
|
| 963 |
+
shift_logits = shift_logits.view(-1, shift_logits.size(-1))
|
| 964 |
+
shift_labels = shift_labels.view(-1)
|
| 965 |
+
# Enable model/pipeline parallelism
|
| 966 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
| 967 |
+
loss = loss_fct(shift_logits, shift_labels)
|
| 968 |
+
return loss
|
| 969 |
+
|
| 970 |
+
def concatenated_forward(
|
| 971 |
+
self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]]
|
| 972 |
+
) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
|
| 973 |
+
"""Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together.
|
| 974 |
+
|
| 975 |
+
We do this to avoid doing two forward passes, because it's faster for FSDP.
|
| 976 |
+
"""
|
| 977 |
+
concatenated_batch = self.concatenated_inputs(
|
| 978 |
+
batch,
|
| 979 |
+
is_encoder_decoder=self.is_encoder_decoder,
|
| 980 |
+
label_pad_token_id=self.label_pad_token_id,
|
| 981 |
+
padding_value=self.padding_value,
|
| 982 |
+
device=self.accelerator.device,
|
| 983 |
+
)
|
| 984 |
+
len_chosen = batch["chosen_labels"].shape[0]
|
| 985 |
+
|
| 986 |
+
all_logits, new_labels = model(
|
| 987 |
+
concatenated_batch["concatenated_input_ids"],
|
| 988 |
+
attention_mask=concatenated_batch["concatenated_attention_mask"],
|
| 989 |
+
labels=concatenated_batch["concatenated_labels"],
|
| 990 |
+
images=concatenated_batch["concatenated_images"],
|
| 991 |
+
use_cache=False,
|
| 992 |
+
dpo_forward=True,
|
| 993 |
+
)
|
| 994 |
+
all_logits = all_logits.to(torch.float32)
|
| 995 |
+
all_logps = self.get_batch_logps(
|
| 996 |
+
all_logits,
|
| 997 |
+
new_labels,
|
| 998 |
+
average_log_prob=self.loss_type == "ipo",
|
| 999 |
+
is_encoder_decoder=self.is_encoder_decoder,
|
| 1000 |
+
label_pad_token_id=self.label_pad_token_id,
|
| 1001 |
+
)
|
| 1002 |
+
|
| 1003 |
+
chosen_logps = all_logps[:len_chosen]
|
| 1004 |
+
rejected_logps = all_logps[len_chosen:]
|
| 1005 |
+
|
| 1006 |
+
# don't count image embeds logits
|
| 1007 |
+
# loss_mask = new_labels != -100
|
| 1008 |
+
# logits = [all_logits[i][loss_mask[i]] for i in range(loss_mask.shape[0])]
|
| 1009 |
+
# chosen_logits = logits[:len_chosen]
|
| 1010 |
+
# rejected_logits = logits[len_chosen:]
|
| 1011 |
+
# chosen_logits = [l.detach().cpu().mean() for l in chosen_logits]
|
| 1012 |
+
# rejected_logits = [l.detach().cpu().mean() for l in rejected_logits]
|
| 1013 |
+
# chosen_logits = sum(chosen_logits)/len_chosen
|
| 1014 |
+
# rejected_logits = sum(rejected_logits)/len_chosen
|
| 1015 |
+
|
| 1016 |
+
chosen_logits = all_logits[:len_chosen]
|
| 1017 |
+
rejected_logits = all_logits[len_chosen:]
|
| 1018 |
+
|
| 1019 |
+
chosen_labels = new_labels[:len_chosen]
|
| 1020 |
+
rejected_labels = new_labels[len_chosen:]
|
| 1021 |
+
|
| 1022 |
+
return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_labels, rejected_labels)
|
| 1023 |
+
|
| 1024 |
+
def get_batch_loss_metrics(
|
| 1025 |
+
self,
|
| 1026 |
+
model,
|
| 1027 |
+
batch: Dict[str, Union[List, torch.LongTensor]],
|
| 1028 |
+
train_eval: Literal["train", "eval"] = "train",
|
| 1029 |
+
):
|
| 1030 |
+
"""Compute the DPO loss and other metrics for the given batch of inputs for train or test.
|
| 1031 |
+
CHANGE: 1. add sft loss
|
| 1032 |
+
2. all gather metrics
|
| 1033 |
+
"""
|
| 1034 |
+
metrics = {}
|
| 1035 |
+
|
| 1036 |
+
(
|
| 1037 |
+
policy_chosen_logps,
|
| 1038 |
+
policy_rejected_logps,
|
| 1039 |
+
policy_chosen_logits,
|
| 1040 |
+
policy_rejected_logits,
|
| 1041 |
+
chosen_labels,
|
| 1042 |
+
rejected_labels,
|
| 1043 |
+
) = self.concatenated_forward(model, batch)
|
| 1044 |
+
|
| 1045 |
+
# if reference_chosen_logps and reference_rejected_logps in batch use them, otherwise use the reference model
|
| 1046 |
+
if "reference_chosen_logps" in batch and "reference_rejected_logps" in batch:
|
| 1047 |
+
reference_chosen_logps = batch["reference_chosen_logps"]
|
| 1048 |
+
reference_rejected_logps = batch["reference_rejected_logps"]
|
| 1049 |
+
else:
|
| 1050 |
+
with torch.no_grad():
|
| 1051 |
+
if self.ref_model is None:
|
| 1052 |
+
with self.null_ref_context():
|
| 1053 |
+
(reference_chosen_logps, reference_rejected_logps,) = self.concatenated_forward(
|
| 1054 |
+
self.model, batch
|
| 1055 |
+
)[:2]
|
| 1056 |
+
else:
|
| 1057 |
+
(reference_chosen_logps, reference_rejected_logps,) = self.concatenated_forward(
|
| 1058 |
+
self.ref_model, batch
|
| 1059 |
+
)[:2]
|
| 1060 |
+
|
| 1061 |
+
unscaled_dpo_losses, chosen_rewards, rejected_rewards = self.dpo_loss(
|
| 1062 |
+
policy_chosen_logps,
|
| 1063 |
+
policy_rejected_logps,
|
| 1064 |
+
reference_chosen_logps,
|
| 1065 |
+
reference_rejected_logps,
|
| 1066 |
+
)
|
| 1067 |
+
unscaled_dpo_losses = unscaled_dpo_losses.mean()
|
| 1068 |
+
dpo_losses = unscaled_dpo_losses * self.dpo_alpha
|
| 1069 |
+
unscaled_sft_loss = self.get_sft_loss(policy_chosen_logits, chosen_labels)
|
| 1070 |
+
sft_loss = unscaled_sft_loss * self.gamma
|
| 1071 |
+
|
| 1072 |
+
# print(sft_loss.shape, dpo_losses.shape)
|
| 1073 |
+
losses = dpo_losses + sft_loss
|
| 1074 |
+
# losses = sft_loss # sft only
|
| 1075 |
+
# losses = dpo_losses # dpo only
|
| 1076 |
+
reward_accuracies = (chosen_rewards > rejected_rewards).float()
|
| 1077 |
+
|
| 1078 |
+
def all_gather_tensor(tensor):
|
| 1079 |
+
if torch.distributed.is_available() and torch.distributed.is_initialized():
|
| 1080 |
+
tensor = tensor.detach()
|
| 1081 |
+
gathered_tensor = [torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())]
|
| 1082 |
+
torch.distributed.all_gather(gathered_tensor, tensor)
|
| 1083 |
+
tensor = torch.cat(gathered_tensor, dim=0)
|
| 1084 |
+
# else:
|
| 1085 |
+
# print('not distributed')
|
| 1086 |
+
return tensor
|
| 1087 |
+
|
| 1088 |
+
# gather chosen_rewards across devices
|
| 1089 |
+
chosen_rewards = all_gather_tensor(chosen_rewards)
|
| 1090 |
+
rejected_rewards = all_gather_tensor(rejected_rewards)
|
| 1091 |
+
reward_accuracies = all_gather_tensor(reward_accuracies)
|
| 1092 |
+
policy_chosen_logps = all_gather_tensor(policy_chosen_logps)
|
| 1093 |
+
policy_rejected_logps = all_gather_tensor(policy_rejected_logps)
|
| 1094 |
+
reference_chosen_logps = all_gather_tensor(reference_chosen_logps)
|
| 1095 |
+
reference_rejected_logps = all_gather_tensor(reference_rejected_logps)
|
| 1096 |
+
|
| 1097 |
+
prefix = "eval_" if train_eval == "eval" else ""
|
| 1098 |
+
metrics[f"{prefix}losses/dpo"] = unscaled_dpo_losses.cpu()
|
| 1099 |
+
metrics[f"{prefix}losses/sft"] = unscaled_sft_loss.cpu()
|
| 1100 |
+
metrics[f"{prefix}losses/total"] = losses.cpu()
|
| 1101 |
+
metrics[f"{prefix}rewards/chosen"] = chosen_rewards.mean().cpu()
|
| 1102 |
+
metrics[f"{prefix}rewards/rejected"] = rejected_rewards.mean().cpu()
|
| 1103 |
+
metrics[f"{prefix}rewards/accuracies"] = reward_accuracies.mean().cpu()
|
| 1104 |
+
metrics[f"{prefix}rewards/margins"] = (chosen_rewards - rejected_rewards).mean().cpu()
|
| 1105 |
+
# policy logps
|
| 1106 |
+
metrics[f"{prefix}logps/rejected"] = policy_rejected_logps.detach().mean().cpu()
|
| 1107 |
+
metrics[f"{prefix}logps/chosen"] = policy_chosen_logps.detach().mean().cpu()
|
| 1108 |
+
# policy logits (exclude image tokens)
|
| 1109 |
+
# metrics[f"{prefix}logits/rejected"] =policy_rejected_logits
|
| 1110 |
+
# metrics[f"{prefix}logits/chosen"] = policy_chosen_logits
|
| 1111 |
+
# reference logps
|
| 1112 |
+
metrics[f"{prefix}ref_logps/rejected"] = reference_rejected_logps.mean().cpu()
|
| 1113 |
+
metrics[f"{prefix}ref_logps/chosen"] = reference_chosen_logps.mean().cpu()
|
| 1114 |
+
|
| 1115 |
+
# metrics all pick .4 digits
|
| 1116 |
+
# for k in metrics:
|
| 1117 |
+
# metrics[k] = round(metrics[k].item(), 4)
|
| 1118 |
+
|
| 1119 |
+
return losses, metrics
|
| 1120 |
+
|
| 1121 |
+
def compute_loss(
|
| 1122 |
+
self,
|
| 1123 |
+
model: Union[PreTrainedModel, nn.Module],
|
| 1124 |
+
inputs: Dict[str, Union[torch.Tensor, Any]],
|
| 1125 |
+
return_outputs=False,
|
| 1126 |
+
) -> Union[torch.Tensor, Tuple[torch.Tensor, Dict[str, torch.Tensor]]]:
|
| 1127 |
+
if not self.use_dpo_data_collator:
|
| 1128 |
+
warnings.warn(
|
| 1129 |
+
"compute_loss is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than "
|
| 1130 |
+
"DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator"
|
| 1131 |
+
)
|
| 1132 |
+
|
| 1133 |
+
compute_loss_context_manager = torch.cuda.amp.autocast if self._peft_has_been_casted_to_bf16 else nullcontext
|
| 1134 |
+
|
| 1135 |
+
with compute_loss_context_manager():
|
| 1136 |
+
loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train")
|
| 1137 |
+
|
| 1138 |
+
# force log the metrics
|
| 1139 |
+
self.store_metrics(metrics, train_eval="train")
|
| 1140 |
+
|
| 1141 |
+
if return_outputs:
|
| 1142 |
+
return (loss, metrics)
|
| 1143 |
+
return loss
|
| 1144 |
+
|
| 1145 |
+
def get_batch_samples(self, model, batch: Dict[str, torch.LongTensor]) -> Tuple[str, str]:
|
| 1146 |
+
"""Generate samples from the model and reference model for the given batch of inputs."""
|
| 1147 |
+
|
| 1148 |
+
# If one uses `generate_during_eval` with peft + bf16, we need to explictly call generate with
|
| 1149 |
+
# the torch cuda amp context manager as some hidden states are silently casted to full precision.
|
| 1150 |
+
generate_context_manager = nullcontext if not self._peft_has_been_casted_to_bf16 else torch.cuda.amp.autocast
|
| 1151 |
+
|
| 1152 |
+
with generate_context_manager():
|
| 1153 |
+
policy_output = model.generate(
|
| 1154 |
+
input_ids=batch["prompt_input_ids"],
|
| 1155 |
+
attention_mask=batch["prompt_attention_mask"],
|
| 1156 |
+
max_length=self.max_length,
|
| 1157 |
+
do_sample=True,
|
| 1158 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 1159 |
+
)
|
| 1160 |
+
|
| 1161 |
+
# if reference_output in batch use that otherwise use the reference model
|
| 1162 |
+
if "reference_output" in batch:
|
| 1163 |
+
reference_output = batch["reference_output"]
|
| 1164 |
+
else:
|
| 1165 |
+
if self.ref_model is None:
|
| 1166 |
+
with self.null_ref_context():
|
| 1167 |
+
reference_output = self.model.generate(
|
| 1168 |
+
input_ids=batch["prompt_input_ids"],
|
| 1169 |
+
attention_mask=batch["prompt_attention_mask"],
|
| 1170 |
+
max_length=self.max_length,
|
| 1171 |
+
do_sample=True,
|
| 1172 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 1173 |
+
)
|
| 1174 |
+
else:
|
| 1175 |
+
reference_output = self.ref_model.generate(
|
| 1176 |
+
input_ids=batch["prompt_input_ids"],
|
| 1177 |
+
attention_mask=batch["prompt_attention_mask"],
|
| 1178 |
+
max_length=self.max_length,
|
| 1179 |
+
do_sample=True,
|
| 1180 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 1181 |
+
)
|
| 1182 |
+
|
| 1183 |
+
policy_output = pad_to_length(policy_output, self.max_length, self.tokenizer.pad_token_id)
|
| 1184 |
+
policy_output_decoded = self.tokenizer.batch_decode(policy_output, skip_special_tokens=True)
|
| 1185 |
+
|
| 1186 |
+
reference_output = pad_to_length(reference_output, self.max_length, self.tokenizer.pad_token_id)
|
| 1187 |
+
reference_output_decoded = self.tokenizer.batch_decode(reference_output, skip_special_tokens=True)
|
| 1188 |
+
|
| 1189 |
+
return policy_output_decoded, reference_output_decoded
|
| 1190 |
+
|
| 1191 |
+
def prediction_step(
|
| 1192 |
+
self,
|
| 1193 |
+
model: Union[PreTrainedModel, nn.Module],
|
| 1194 |
+
inputs: Dict[str, Union[torch.Tensor, Any]],
|
| 1195 |
+
prediction_loss_only: bool,
|
| 1196 |
+
ignore_keys: Optional[List[str]] = None,
|
| 1197 |
+
):
|
| 1198 |
+
if not self.use_dpo_data_collator:
|
| 1199 |
+
warnings.warn(
|
| 1200 |
+
"prediction_step is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than "
|
| 1201 |
+
"DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator"
|
| 1202 |
+
)
|
| 1203 |
+
if ignore_keys is None:
|
| 1204 |
+
if hasattr(model, "config"):
|
| 1205 |
+
ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", [])
|
| 1206 |
+
else:
|
| 1207 |
+
ignore_keys = []
|
| 1208 |
+
|
| 1209 |
+
prediction_context_manager = torch.cuda.amp.autocast if self._peft_has_been_casted_to_bf16 else nullcontext
|
| 1210 |
+
|
| 1211 |
+
with torch.no_grad(), prediction_context_manager():
|
| 1212 |
+
loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval")
|
| 1213 |
+
|
| 1214 |
+
# force log the metrics
|
| 1215 |
+
self.store_metrics(metrics, train_eval="eval")
|
| 1216 |
+
|
| 1217 |
+
if prediction_loss_only:
|
| 1218 |
+
return (loss.detach(), None, None)
|
| 1219 |
+
|
| 1220 |
+
# logits for the chosen and rejected samples from model
|
| 1221 |
+
logits_dict = {
|
| 1222 |
+
"eval_logits/chosen": metrics["eval_logits/chosen"],
|
| 1223 |
+
"eval_logits/rejected": metrics["eval_logits/rejected"],
|
| 1224 |
+
}
|
| 1225 |
+
logits = tuple(v.unsqueeze(dim=0) for k, v in logits_dict.items() if k not in ignore_keys)
|
| 1226 |
+
logits = torch.stack(logits).mean(axis=1).to(self.accelerator.device)
|
| 1227 |
+
labels = torch.zeros(logits.shape[0], device=self.accelerator.device)
|
| 1228 |
+
|
| 1229 |
+
return (loss.detach(), logits, labels)
|
| 1230 |
+
|
| 1231 |
+
def store_metrics(self, metrics: Dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None:
|
| 1232 |
+
for key, value in metrics.items():
|
| 1233 |
+
self._stored_metrics[train_eval][key].append(value)
|
| 1234 |
+
|
| 1235 |
+
def evaluation_loop(
|
| 1236 |
+
self,
|
| 1237 |
+
dataloader: DataLoader,
|
| 1238 |
+
description: str,
|
| 1239 |
+
prediction_loss_only: Optional[bool] = None,
|
| 1240 |
+
ignore_keys: Optional[List[str]] = None,
|
| 1241 |
+
metric_key_prefix: str = "eval",
|
| 1242 |
+
) -> EvalLoopOutput:
|
| 1243 |
+
"""
|
| 1244 |
+
Overriding built-in evaluation loop to store metrics for each batch.
|
| 1245 |
+
Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`.
|
| 1246 |
+
|
| 1247 |
+
Works both with or without labels.
|
| 1248 |
+
"""
|
| 1249 |
+
|
| 1250 |
+
# Sample and save to game log if requested (for one batch to save time)
|
| 1251 |
+
if self.generate_during_eval:
|
| 1252 |
+
# Generate random indices within the range of the total number of samples
|
| 1253 |
+
num_samples = len(dataloader.dataset)
|
| 1254 |
+
random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size)
|
| 1255 |
+
|
| 1256 |
+
# Use dataloader.dataset.select to get the random batch without iterating over the DataLoader
|
| 1257 |
+
random_batch_dataset = dataloader.dataset.select(random_indices)
|
| 1258 |
+
random_batch = self.data_collator(random_batch_dataset)
|
| 1259 |
+
random_batch = self._prepare_inputs(random_batch)
|
| 1260 |
+
|
| 1261 |
+
policy_output_decoded, ref_output_decoded = self.get_batch_samples(self.model, random_batch)
|
| 1262 |
+
|
| 1263 |
+
self.log(
|
| 1264 |
+
{
|
| 1265 |
+
"game_log": wandb.Table(
|
| 1266 |
+
columns=["Prompt", "Policy", "Ref Model"],
|
| 1267 |
+
rows=[
|
| 1268 |
+
[prompt, pol[len(prompt) :], ref[len(prompt) :]]
|
| 1269 |
+
for prompt, pol, ref in zip(
|
| 1270 |
+
random_batch["prompt"], policy_output_decoded, ref_output_decoded
|
| 1271 |
+
)
|
| 1272 |
+
],
|
| 1273 |
+
)
|
| 1274 |
+
}
|
| 1275 |
+
)
|
| 1276 |
+
self.state.log_history.pop()
|
| 1277 |
+
|
| 1278 |
+
# Base evaluation
|
| 1279 |
+
initial_output = super().evaluation_loop(
|
| 1280 |
+
dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix
|
| 1281 |
+
)
|
| 1282 |
+
|
| 1283 |
+
return initial_output
|
| 1284 |
+
|
| 1285 |
+
def log(self, logs: Dict[str, float]) -> None:
|
| 1286 |
+
"""
|
| 1287 |
+
Log `logs` on the various objects watching training, including stored metrics.
|
| 1288 |
+
|
| 1289 |
+
Args:
|
| 1290 |
+
logs (`Dict[str, float]`):
|
| 1291 |
+
The values to log.
|
| 1292 |
+
"""
|
| 1293 |
+
# logs either has 'loss' or 'eval_loss'
|
| 1294 |
+
train_eval = "train" if "loss" in logs else "eval"
|
| 1295 |
+
# Add averaged stored metrics to logs
|
| 1296 |
+
for key, metrics in self._stored_metrics[train_eval].items():
|
| 1297 |
+
logs[key] = torch.tensor(metrics).mean().item()
|
| 1298 |
+
del self._stored_metrics[train_eval]
|
| 1299 |
+
return super().log(logs)
|
| 1300 |
+
|
| 1301 |
+
@wraps(Trainer.push_to_hub)
|
| 1302 |
+
def push_to_hub(self, commit_message: Optional[str] = "End of training", blocking: bool = True, **kwargs) -> str:
|
| 1303 |
+
"""
|
| 1304 |
+
Overwrite the `push_to_hub` method in order to force-add the tag "sft" when pushing the
|
| 1305 |
+
model on the Hub. Please refer to `~transformers.Trainer.push_to_hub` for more details.
|
| 1306 |
+
"""
|
| 1307 |
+
kwargs = trl_sanitze_kwargs_for_tagging(model=self.model, tag_names=self._tag_names, kwargs=kwargs)
|
| 1308 |
+
|
| 1309 |
+
return super().push_to_hub(commit_message=commit_message, blocking=blocking, **kwargs)
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/iterative_sft_trainer.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 warnings
|
| 15 |
+
from typing import Callable, Dict, List, Optional, Tuple, Union
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from datasets import Dataset
|
| 19 |
+
from torch.utils.data import DataLoader
|
| 20 |
+
from transformers import (
|
| 21 |
+
DataCollator,
|
| 22 |
+
DataCollatorForLanguageModeling,
|
| 23 |
+
DataCollatorForSeq2Seq,
|
| 24 |
+
PreTrainedModel,
|
| 25 |
+
PreTrainedTokenizerBase,
|
| 26 |
+
Trainer,
|
| 27 |
+
TrainingArguments,
|
| 28 |
+
)
|
| 29 |
+
from transformers.trainer_utils import EvalLoopOutput
|
| 30 |
+
|
| 31 |
+
from ..core import PPODecorators
|
| 32 |
+
from ..import_utils import is_peft_available
|
| 33 |
+
|
| 34 |
+
if is_peft_available():
|
| 35 |
+
from peft import PeftModel
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class IterativeSFTTrainer(Trainer):
|
| 39 |
+
"""
|
| 40 |
+
The IterativeSFTTrainer can be used to finetune models with methods that requires some steps between optimization.
|
| 41 |
+
|
| 42 |
+
Attributes:
|
| 43 |
+
**model** (`PreTrainedModel`) -- Model to be optimized, either an 'AutoModelForCausalLM' or an 'AutoModelForSeq2SeqLM'.
|
| 44 |
+
Check the documentation of `PreTrainedModel` for more details.
|
| 45 |
+
**args** (`transformers.TrainingArguments`): -- The arguments to use for training.
|
| 46 |
+
**tokenizer** (`PreTrainedTokenizerBase`) -- Tokenizer to be used for encoding the
|
| 47 |
+
data. Check the documentation of `transformers.PreTrainedTokenizer` and
|
| 48 |
+
`transformers.PreTrainedTokenizerFast` for more details.
|
| 49 |
+
**optimizers** (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): -- The optimizer and scheduler to use for training.
|
| 50 |
+
**data_collator** (Union[DataCollatorForLanguageModeling, DataCollatorForSeq2Seq], *optional*) -- Data collator to be used for training and
|
| 51 |
+
passed along the dataloader.
|
| 52 |
+
**eval_dataset** (`datasets.Dataset`): The dataset to use for evaluation.
|
| 53 |
+
**max_length** (`int`, defaults to `None`): -- The maximum length of the input.
|
| 54 |
+
**truncation_mode** (`str`, defaults to `keep_end`): -- The truncation mode to use, either `keep_end` or `keep_start`.
|
| 55 |
+
**preprocess_logits_for_metrics** (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): -- The function to use to preprocess the logits before computing the metrics.
|
| 56 |
+
**compute_metrics** (`Callable[[EvalPrediction], Dict]`, *optional*): -- The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to metric values.
|
| 57 |
+
**optimize_device_cache ** (`bool`, *optional*, defaults to `False`) -- Optimize CUDA cache for slightly more memory-efficient training.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def __init__(
|
| 61 |
+
self,
|
| 62 |
+
model: PreTrainedModel = None,
|
| 63 |
+
args: TrainingArguments = None,
|
| 64 |
+
tokenizer: PreTrainedTokenizerBase = None,
|
| 65 |
+
optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (
|
| 66 |
+
None,
|
| 67 |
+
None,
|
| 68 |
+
),
|
| 69 |
+
data_collator: Optional[DataCollator] = None,
|
| 70 |
+
eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None,
|
| 71 |
+
max_length: Optional[int] = None,
|
| 72 |
+
truncation_mode: Optional[str] = "keep_end",
|
| 73 |
+
preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
|
| 74 |
+
compute_metrics: Optional[Callable[[EvalLoopOutput], Dict]] = None,
|
| 75 |
+
optimize_device_cache: Optional[bool] = False,
|
| 76 |
+
):
|
| 77 |
+
# Step 0: check positional arguments validity
|
| 78 |
+
if not isinstance(tokenizer, (PreTrainedTokenizerBase)):
|
| 79 |
+
raise ValueError(
|
| 80 |
+
f"tokenizer must be a PreTrainedTokenizerBase like a PreTrainedTokenizer or a PreTrainedTokenizerFast, got {type(tokenizer)}"
|
| 81 |
+
)
|
| 82 |
+
if not isinstance(model, PreTrainedModel):
|
| 83 |
+
raise ValueError(f"model must be a PreTrainedModel, got {type(model)}")
|
| 84 |
+
if not model.can_generate():
|
| 85 |
+
warnings.warn(
|
| 86 |
+
f"The current model class {type(model)} is not compatible with `.generate()`"
|
| 87 |
+
"Please make sure that this is intended."
|
| 88 |
+
)
|
| 89 |
+
if optimizers[1] is None and args.max_steps == -1:
|
| 90 |
+
raise ValueError(
|
| 91 |
+
"When no scheduler is provided, you need to set the total number of training steps to perform `max_steps`"
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
self.is_encoder_decoder = getattr(model.config, "is_encoder_decoder", False)
|
| 95 |
+
self.is_peft_model = is_peft_available() and isinstance(model, PeftModel)
|
| 96 |
+
|
| 97 |
+
self.tokenizer = tokenizer
|
| 98 |
+
|
| 99 |
+
if data_collator is None:
|
| 100 |
+
if self.is_encoder_decoder:
|
| 101 |
+
warnings.warn(
|
| 102 |
+
"No data collator is provided. Using 'DataCollatorForSeq2Seq' with"
|
| 103 |
+
"'labels_pad_token_id' set to '-100' and 'pad_to_multiple_of' set to 8."
|
| 104 |
+
)
|
| 105 |
+
self.data_collator = DataCollatorForSeq2Seq(tokenizer, label_pad_token_id=-100, pad_to_multiple_of=8)
|
| 106 |
+
else:
|
| 107 |
+
warnings.warn("No data collator is provided. Using 'DataCollatorForLanguageModeling'")
|
| 108 |
+
self.data_collator = DataCollatorForLanguageModeling(self.tokenizer, mlm=False)
|
| 109 |
+
else:
|
| 110 |
+
self.data_collator = data_collator
|
| 111 |
+
|
| 112 |
+
self.max_length = max_length
|
| 113 |
+
self.truncation_mode = truncation_mode
|
| 114 |
+
self.optimize_device_cache = optimize_device_cache
|
| 115 |
+
|
| 116 |
+
super().__init__(
|
| 117 |
+
model=model,
|
| 118 |
+
args=args,
|
| 119 |
+
data_collator=self.data_collator,
|
| 120 |
+
eval_dataset=eval_dataset,
|
| 121 |
+
tokenizer=tokenizer,
|
| 122 |
+
compute_metrics=compute_metrics,
|
| 123 |
+
optimizers=optimizers,
|
| 124 |
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
self.create_optimizer_and_scheduler(self.args.max_steps)
|
| 128 |
+
|
| 129 |
+
# prepare model, optimizer and lr_scheduler
|
| 130 |
+
self.model, self.optimizer, self.lr_scheduler = self.accelerator.prepare(
|
| 131 |
+
self.model, self.optimizer, self.lr_scheduler
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
self.tokenizer.truncation_side = "left" if self.truncation_mode == "keep_end" else "right"
|
| 135 |
+
|
| 136 |
+
if not hasattr(self, "accelerator"):
|
| 137 |
+
raise AttributeError(
|
| 138 |
+
"Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`."
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
PPODecorators.optimize_device_cache = self.optimize_device_cache
|
| 142 |
+
|
| 143 |
+
def prepare_model_inputs(self, input_ids: torch.Tensor, attention_mask: torch.Tensor, labels: torch.Tensor):
|
| 144 |
+
if attention_mask is None:
|
| 145 |
+
attention_mask = [torch.ones_like(ids) for ids in input_ids]
|
| 146 |
+
|
| 147 |
+
if self.is_encoder_decoder:
|
| 148 |
+
input_data = self.data_collator(
|
| 149 |
+
[
|
| 150 |
+
{"input_ids": ids, "attention_mask": att, "labels": lab}
|
| 151 |
+
for ids, att, lab in zip(input_ids, attention_mask, labels)
|
| 152 |
+
]
|
| 153 |
+
).to(self.model.device)
|
| 154 |
+
|
| 155 |
+
input_data.pop("decoder_input_ids", None) # This is directly computed inside the model
|
| 156 |
+
|
| 157 |
+
input_data["labels"][input_data["labels"] == self.tokenizer.pad_token_id] = -100
|
| 158 |
+
|
| 159 |
+
else:
|
| 160 |
+
input_data = self.data_collator(
|
| 161 |
+
[{"input_ids": ids, "attention_mask": att} for ids, att in zip(input_ids, attention_mask)]
|
| 162 |
+
).to(self.model.device)
|
| 163 |
+
|
| 164 |
+
# truncate in case the user has provided input_ids, attention_mask and labels
|
| 165 |
+
if self.max_length is not None:
|
| 166 |
+
if self.truncation_mode == "keep_start":
|
| 167 |
+
input_data = {k: v[: self.max_length] for k, v in input_data.items()}
|
| 168 |
+
elif self.truncation_mode == "keep_end":
|
| 169 |
+
input_data = {k: v[-self.max_length :] for k, v in input_data.items()}
|
| 170 |
+
else:
|
| 171 |
+
raise ValueError(f"Unknown truncation mode: {self.truncation_mode}")
|
| 172 |
+
|
| 173 |
+
return input_data
|
| 174 |
+
|
| 175 |
+
@staticmethod
|
| 176 |
+
def _step_safety_checker(
|
| 177 |
+
input_ids: List[torch.LongTensor],
|
| 178 |
+
attention_mask: List[torch.LongTensor],
|
| 179 |
+
labels: List[torch.LongTensor],
|
| 180 |
+
texts: List[str],
|
| 181 |
+
texts_labels: List[str],
|
| 182 |
+
):
|
| 183 |
+
"""
|
| 184 |
+
Check if the input data is valid for training.
|
| 185 |
+
|
| 186 |
+
Args:
|
| 187 |
+
input_ids (List[`torch.LongTensor`]):
|
| 188 |
+
List of tensors containing the input_ids
|
| 189 |
+
attention_mask (List[`torch.LongTensor`]):
|
| 190 |
+
List of tensors containing the attention_mask
|
| 191 |
+
labels (List[`torch.FloatTensor`]):
|
| 192 |
+
List of tensors containing the labels
|
| 193 |
+
texts (List[`str`]):
|
| 194 |
+
List of string containing the text input.
|
| 195 |
+
texts_labels (List[`str`]):
|
| 196 |
+
List of string containing the text labels.
|
| 197 |
+
Returns:
|
| 198 |
+
`tuple`: The input data.
|
| 199 |
+
"""
|
| 200 |
+
if texts is None:
|
| 201 |
+
if attention_mask is None:
|
| 202 |
+
for name, tensor_list in zip(["input_ids", "labels"], [input_ids, labels]):
|
| 203 |
+
if not isinstance(tensor_list, list):
|
| 204 |
+
raise ValueError(f"{name} must be a list of tensors - got {type(tensor_list)}")
|
| 205 |
+
if not isinstance(tensor_list[0], torch.Tensor):
|
| 206 |
+
raise ValueError(f"Elements in {name} must be tensors - got {type(tensor_list[0])}")
|
| 207 |
+
else:
|
| 208 |
+
for name, tensor_list in zip(
|
| 209 |
+
["input_ids", "attention_mask", "labels"], [input_ids, attention_mask, labels]
|
| 210 |
+
):
|
| 211 |
+
if not isinstance(tensor_list, list):
|
| 212 |
+
raise ValueError(f"{name} must be a list of tensors - got {type(tensor_list)}")
|
| 213 |
+
if not isinstance(tensor_list[0], torch.Tensor):
|
| 214 |
+
raise ValueError(f"Elements in {name} must be tensors - got {type(tensor_list[0])}")
|
| 215 |
+
else:
|
| 216 |
+
if not isinstance(texts, list):
|
| 217 |
+
raise ValueError(f"'text' must be a list of strings - got {type(texts)}")
|
| 218 |
+
if not isinstance(texts[0], str):
|
| 219 |
+
raise ValueError(f"Elements in 'text' must be strings - got {type(texts[0])}")
|
| 220 |
+
if texts_labels is not None:
|
| 221 |
+
if not isinstance(texts_labels, list):
|
| 222 |
+
raise ValueError(f"'text_labels' must be a list of strings - got {type(texts_labels)}")
|
| 223 |
+
if not isinstance(texts_labels[0], str):
|
| 224 |
+
raise ValueError(f"Elements in 'text_labels' must be strings - got {type(texts_labels[0])}")
|
| 225 |
+
|
| 226 |
+
return input_ids, attention_mask, labels, texts, texts_labels
|
| 227 |
+
|
| 228 |
+
@PPODecorators.empty_device_cache()
|
| 229 |
+
def step(
|
| 230 |
+
self,
|
| 231 |
+
input_ids: Optional[List[torch.LongTensor]] = None,
|
| 232 |
+
attention_mask: Optional[List[torch.LongTensor]] = None,
|
| 233 |
+
labels: Optional[List[torch.LongTensor]] = None,
|
| 234 |
+
texts: Optional[List[str]] = None,
|
| 235 |
+
texts_labels: Optional[List[str]] = None,
|
| 236 |
+
):
|
| 237 |
+
"""
|
| 238 |
+
Run an optimisation step given a list of input_ids, attention_mask, and labels or a list of text and text_labels.
|
| 239 |
+
Args:
|
| 240 |
+
input_ids (List[`torch.LongTensor`]):
|
| 241 |
+
List of tensors containing the input_ids (if not provided, text will be used)
|
| 242 |
+
attention_mask (List[`torch.LongTensor`], , *optional*):
|
| 243 |
+
List of tensors containing the attention_mask
|
| 244 |
+
labels (List[`torch.FloatTensor`], *optional*):
|
| 245 |
+
List of tensors containing the labels (if set to None, will default to input_ids)
|
| 246 |
+
texts (List[`str`], *optional*):
|
| 247 |
+
List of strings containing the text input (if not provided, input_ids will directly be used)
|
| 248 |
+
texts_labels (List[`str`], *optional*):
|
| 249 |
+
List of strings containing the text labels (if set to None, will default to text)
|
| 250 |
+
Returns:
|
| 251 |
+
`dict[str, Any]`: A summary of the training statistics
|
| 252 |
+
"""
|
| 253 |
+
self.model.train()
|
| 254 |
+
|
| 255 |
+
if self.state.global_step == 0:
|
| 256 |
+
self.tr_loss = torch.tensor(0.0).to(self.args.device)
|
| 257 |
+
self._globalstep_last_logged = self.state.global_step
|
| 258 |
+
|
| 259 |
+
if input_ids is None and texts is None:
|
| 260 |
+
raise ValueError("Step should include `input_ids` or `texts` as keyword arguments.")
|
| 261 |
+
elif input_ids is not None and texts is not None:
|
| 262 |
+
warnings.warn(
|
| 263 |
+
"Both 'input_ids' and 'texts' are provided. 'input_ids' will be overwritten using inputs provided by the 'texts' keyword argument."
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
if labels is None and texts_labels is None and self.is_encoder_decoder:
|
| 267 |
+
raise ValueError(
|
| 268 |
+
"No 'labels' or 'text_labels' are provided. When using an encoder-decoder architecture, 'labels' or 'text_labels' must be passed."
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
input_ids, attention_mask, labels, texts, texts_labels = self._step_safety_checker(
|
| 272 |
+
input_ids, attention_mask, labels, texts, texts_labels
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
if texts is not None:
|
| 276 |
+
model_inputs = self.tokenizer(
|
| 277 |
+
texts, max_length=self.max_length, truncation=True, padding=True, return_tensors="pt"
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
input_ids, attention_mask = model_inputs["input_ids"], model_inputs["attention_mask"]
|
| 281 |
+
|
| 282 |
+
if texts_labels is not None:
|
| 283 |
+
labels = self.tokenizer(
|
| 284 |
+
texts, max_length=self.max_length, truncation=True, padding=True, return_tensors="pt"
|
| 285 |
+
)["input_ids"]
|
| 286 |
+
|
| 287 |
+
if labels is None:
|
| 288 |
+
warnings.warn("No labels are provided. Setting labels to input_ids")
|
| 289 |
+
labels = input_ids
|
| 290 |
+
|
| 291 |
+
model_inputs = self.prepare_model_inputs(input_ids, attention_mask, labels)
|
| 292 |
+
|
| 293 |
+
model_inputs_names = list(model_inputs.keys())
|
| 294 |
+
|
| 295 |
+
batch_dict = {}
|
| 296 |
+
batch_dict.update(model_inputs)
|
| 297 |
+
|
| 298 |
+
def collator(data):
|
| 299 |
+
return_dict = dict()
|
| 300 |
+
for key in data[0]:
|
| 301 |
+
if key in ["input_ids", "attention_mask", "labels"]:
|
| 302 |
+
return_dict[key] = torch.stack([d[key] for d in data]).to(self.model.device)
|
| 303 |
+
return return_dict
|
| 304 |
+
|
| 305 |
+
batch_data = Dataset.from_dict(batch_dict)
|
| 306 |
+
batch_data.set_format("torch")
|
| 307 |
+
|
| 308 |
+
step_dataloader = DataLoader(
|
| 309 |
+
batch_data,
|
| 310 |
+
batch_size=self.args.per_device_train_batch_size,
|
| 311 |
+
shuffle=True,
|
| 312 |
+
collate_fn=collator,
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
for _, batch in enumerate(step_dataloader):
|
| 316 |
+
with self.accelerator.accumulate(self.model):
|
| 317 |
+
model_inputs = {k: batch[k] for k in model_inputs_names}
|
| 318 |
+
loss = self.compute_loss(self.model, model_inputs)
|
| 319 |
+
|
| 320 |
+
if self.args.n_gpu > 1:
|
| 321 |
+
loss = loss.mean()
|
| 322 |
+
|
| 323 |
+
tr_loss_step = loss.detach()
|
| 324 |
+
|
| 325 |
+
self.accelerator.backward(loss)
|
| 326 |
+
|
| 327 |
+
if self.accelerator.sync_gradients and self.args.max_grad_norm is not None:
|
| 328 |
+
self.accelerator.clip_grad_norm_(
|
| 329 |
+
self.model.parameters(),
|
| 330 |
+
self.args.max_grad_norm,
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
self.optimizer.step()
|
| 334 |
+
self.optimizer.zero_grad()
|
| 335 |
+
if self.lr_scheduler is not None:
|
| 336 |
+
self.lr_scheduler.step()
|
| 337 |
+
|
| 338 |
+
self.state.global_step += 1
|
| 339 |
+
|
| 340 |
+
# update stats etc
|
| 341 |
+
self.tr_loss += tr_loss_step
|
| 342 |
+
|
| 343 |
+
self._maybe_log_save_evaluate()
|
| 344 |
+
|
| 345 |
+
def _maybe_log_save_evaluate(self):
|
| 346 |
+
# check if eval is required
|
| 347 |
+
if self.args.eval_steps is not None:
|
| 348 |
+
if self.state.global_step % self.args.eval_steps == 0 and self.state.global_step != 0:
|
| 349 |
+
self.evaluate(self.eval_dataset)
|
| 350 |
+
|
| 351 |
+
# check if logging is required
|
| 352 |
+
if self.args.logging_steps is not None:
|
| 353 |
+
if self.state.global_step % self.args.logging_steps == 0 and self.state.global_step != 0:
|
| 354 |
+
logs: Dict[str, float] = {}
|
| 355 |
+
|
| 356 |
+
tr_loss_scalar = self._nested_gather(self.tr_loss).mean().item()
|
| 357 |
+
|
| 358 |
+
# reset tr_loss to zero
|
| 359 |
+
self.tr_loss -= self.tr_loss
|
| 360 |
+
|
| 361 |
+
logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)
|
| 362 |
+
logs["learning_rate"] = self._get_learning_rate()
|
| 363 |
+
|
| 364 |
+
self._globalstep_last_logged = self.state.global_step
|
| 365 |
+
|
| 366 |
+
self.log(logs)
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/model_config.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 NVIDIA CORPORATION & AFFILIATES
|
| 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 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass, field
|
| 18 |
+
from typing import List, Optional
|
| 19 |
+
|
| 20 |
+
from ..core import flatten_dict
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class ModelConfig:
|
| 25 |
+
"""
|
| 26 |
+
Arguments which define the model and tokenizer to load.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
model_name_or_path: Optional[str] = field(
|
| 30 |
+
default=None,
|
| 31 |
+
metadata={"help": ("The model checkpoint for weights initialization.")},
|
| 32 |
+
)
|
| 33 |
+
model_revision: str = field(
|
| 34 |
+
default="main",
|
| 35 |
+
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
|
| 36 |
+
)
|
| 37 |
+
torch_dtype: Optional[str] = field(
|
| 38 |
+
default=None,
|
| 39 |
+
metadata={
|
| 40 |
+
"help": (
|
| 41 |
+
"Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the "
|
| 42 |
+
"dtype will be automatically derived from the model's weights."
|
| 43 |
+
),
|
| 44 |
+
"choices": ["auto", "bfloat16", "float16", "float32"],
|
| 45 |
+
},
|
| 46 |
+
)
|
| 47 |
+
trust_remote_code: bool = field(default=False, metadata={"help": "Trust remote code when loading a model."})
|
| 48 |
+
attn_implementation: Optional[str] = field(
|
| 49 |
+
default=None,
|
| 50 |
+
metadata={
|
| 51 |
+
"help": (
|
| 52 |
+
"Which attention implementation to use; you can run --attn_implementation=flash_attention_2, in which case you must install this manually by running `pip install flash-attn --no-build-isolation`"
|
| 53 |
+
)
|
| 54 |
+
},
|
| 55 |
+
)
|
| 56 |
+
use_peft: bool = field(
|
| 57 |
+
default=False,
|
| 58 |
+
metadata={"help": ("Whether to use PEFT or not for training.")},
|
| 59 |
+
)
|
| 60 |
+
lora_r: Optional[int] = field(
|
| 61 |
+
default=16,
|
| 62 |
+
metadata={"help": ("LoRA R value.")},
|
| 63 |
+
)
|
| 64 |
+
lora_alpha: Optional[int] = field(
|
| 65 |
+
default=32,
|
| 66 |
+
metadata={"help": ("LoRA alpha.")},
|
| 67 |
+
)
|
| 68 |
+
lora_dropout: Optional[float] = field(
|
| 69 |
+
default=0.05,
|
| 70 |
+
metadata={"help": ("LoRA dropout.")},
|
| 71 |
+
)
|
| 72 |
+
lora_target_modules: Optional[List[str]] = field(
|
| 73 |
+
default=None,
|
| 74 |
+
metadata={"help": ("LoRA target modules.")},
|
| 75 |
+
)
|
| 76 |
+
lora_modules_to_save: Optional[List[str]] = field(
|
| 77 |
+
default=None,
|
| 78 |
+
metadata={"help": ("Model layers to unfreeze & train")},
|
| 79 |
+
)
|
| 80 |
+
load_in_8bit: bool = field(
|
| 81 |
+
default=False, metadata={"help": "use 8 bit precision for the base model - works only with LoRA"}
|
| 82 |
+
)
|
| 83 |
+
load_in_4bit: bool = field(
|
| 84 |
+
default=False, metadata={"help": "use 4 bit precision for the base model - works only with LoRA"}
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
bnb_4bit_quant_type: Optional[str] = field(
|
| 88 |
+
default="nf4", metadata={"help": "precise the quantization type (fp4 or nf4)"}
|
| 89 |
+
)
|
| 90 |
+
use_bnb_nested_quant: bool = field(default=False, metadata={"help": "use nested quantization"})
|
| 91 |
+
|
| 92 |
+
def to_dict(self):
|
| 93 |
+
output_dict = {}
|
| 94 |
+
for key, value in self.__dict__.items():
|
| 95 |
+
output_dict[key] = value
|
| 96 |
+
return flatten_dict(output_dict)
|
| 97 |
+
|
| 98 |
+
def __post_init__(self):
|
| 99 |
+
if self.load_in_8bit and self.load_in_4bit:
|
| 100 |
+
raise ValueError("You can't use 8 bit and 4 bit precision at the same time")
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/ppo_config.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 os
|
| 16 |
+
import sys
|
| 17 |
+
import warnings
|
| 18 |
+
from dataclasses import dataclass, field
|
| 19 |
+
from typing import Literal, Optional
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import tyro
|
| 23 |
+
from typing_extensions import Annotated
|
| 24 |
+
|
| 25 |
+
from llava.trl.trainer.utils import exact_div
|
| 26 |
+
|
| 27 |
+
from ..core import flatten_dict
|
| 28 |
+
from ..import_utils import is_wandb_available
|
| 29 |
+
|
| 30 |
+
JSONDict = Annotated[Optional[dict], tyro.conf.arg(metavar="JSON", constructor=json.loads)]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclass
|
| 34 |
+
class PPOConfig:
|
| 35 |
+
"""
|
| 36 |
+
Configuration class for PPOTrainer
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
# common parameters
|
| 40 |
+
exp_name: str = os.path.basename(sys.argv[0])[: -len(".py")]
|
| 41 |
+
"""the name of this experiment (by default is the file name without the extension name)"""
|
| 42 |
+
seed: int = 0
|
| 43 |
+
"""Seed value for random generations"""
|
| 44 |
+
log_with: Optional[Literal["wandb", "tensorboard"]] = None
|
| 45 |
+
"""Log with either 'wandb' or 'tensorboard', check https://huggingface.co/docs/accelerate/usage_guides/tracking for more details"""
|
| 46 |
+
task_name: Optional[str] = None
|
| 47 |
+
"""Name of task to use - used only for tracking purposes"""
|
| 48 |
+
model_name: Optional[str] = "gpt2"
|
| 49 |
+
"""Name of model to use - used only for tracking purposes"""
|
| 50 |
+
query_dataset: Optional[str] = "imdb"
|
| 51 |
+
"""Name of dataset to query - used only for tracking purposes"""
|
| 52 |
+
reward_model: Optional[str] = "sentiment-analysis:lvwerra/distilbert-imdb"
|
| 53 |
+
"""The reward model to use - used only for tracking purposes"""
|
| 54 |
+
remove_unused_columns: bool = True
|
| 55 |
+
"""Remove unused columns from the dataset if `datasets.Dataset` is used"""
|
| 56 |
+
tracker_kwargs: JSONDict = field(default_factory=dict)
|
| 57 |
+
"""Keyword arguments for the tracker (e.g. python ppo.py --tracker_kwargs='{"wandb": {"entity": "my_wandb_entity", "name": "my_exp_name"}}'"""
|
| 58 |
+
accelerator_kwargs: JSONDict = field(default_factory=dict)
|
| 59 |
+
"""Keyword arguments for the accelerator"""
|
| 60 |
+
project_kwargs: JSONDict = field(default_factory=dict)
|
| 61 |
+
"""Keyword arguments for the accelerator project config (e.g. `logging_dir`)"""
|
| 62 |
+
tracker_project_name: str = "trl"
|
| 63 |
+
"""Name of project to use for tracking"""
|
| 64 |
+
push_to_hub_if_best_kwargs: JSONDict = field(default_factory=dict)
|
| 65 |
+
"""Keyword arguments for pushing model to the hub during training (e.g. repo_id)"""
|
| 66 |
+
|
| 67 |
+
# hyperparameters
|
| 68 |
+
steps: int = 20000
|
| 69 |
+
"""Number of training steps"""
|
| 70 |
+
learning_rate: float = 1.41e-5
|
| 71 |
+
"""Adam learning rate"""
|
| 72 |
+
adap_kl_ctrl: bool = True
|
| 73 |
+
"""Use adaptive KL control, otherwise linear"""
|
| 74 |
+
init_kl_coef: Optional[float] = 0.2
|
| 75 |
+
"""Initial KL penalty coefficient (used for adaptive and linear control)"""
|
| 76 |
+
kl_penalty: Literal["kl", "abs", "mse", "full"] = "kl"
|
| 77 |
+
"""kl penalty options: 'kl': model_logp - ref_logp, 'abs': abs(kl), 'mse': mean squared error mse(kl) and 'full': the actual kl for all tokens in the distribution"""
|
| 78 |
+
target: Optional[float] = 6
|
| 79 |
+
"""Target KL value for adaptive KL control"""
|
| 80 |
+
horizon: Optional[float] = 10000
|
| 81 |
+
"""Horizon for adaptive KL control"""
|
| 82 |
+
gamma: float = 1
|
| 83 |
+
"""Gamma parameter for advantage calculation"""
|
| 84 |
+
lam: float = 0.95
|
| 85 |
+
"""Lambda parameter for advantage calculation"""
|
| 86 |
+
cliprange: float = 0.2
|
| 87 |
+
"""Range for clipping in PPO policy gradient loss"""
|
| 88 |
+
cliprange_value: float = 0.2
|
| 89 |
+
"""Range for clipping values in loss calculation"""
|
| 90 |
+
vf_coef: float = 0.1
|
| 91 |
+
"""Scaling factor for value loss"""
|
| 92 |
+
batch_size: int = 128
|
| 93 |
+
"""Number of samples per optimisation step"""
|
| 94 |
+
forward_batch_size: Optional[int] = None
|
| 95 |
+
"""DEPRECATED: use `mini_batch_size` instead, which does the same thing."""
|
| 96 |
+
mini_batch_size: int = 128
|
| 97 |
+
"""Number of samples optimized in each mini batch"""
|
| 98 |
+
gradient_accumulation_steps: int = 1
|
| 99 |
+
"""The number of gradient accumulation steps"""
|
| 100 |
+
world_size: tyro.conf.Suppress[int] = None
|
| 101 |
+
"""The world size for distributed training"""
|
| 102 |
+
ppo_epochs: int = 4
|
| 103 |
+
"""Number of optimisation epochs per batch of samples"""
|
| 104 |
+
max_grad_norm: Optional[float] = None
|
| 105 |
+
"""Maximum gradient norm for gradient clipping"""
|
| 106 |
+
optimize_cuda_cache: Optional[bool] = None
|
| 107 |
+
"""DEPRECATED: use `optimize_device_cache` instead, which does the same thing."""
|
| 108 |
+
optimize_device_cache: Optional[bool] = False
|
| 109 |
+
"""Optimize device cache for slightly more memory-efficient training"""
|
| 110 |
+
early_stopping: bool = False
|
| 111 |
+
"""Whether to stop the PPO optimization loop early is the KL too high"""
|
| 112 |
+
target_kl: float = 1
|
| 113 |
+
"""Stop early if we exceed this value by over 50%"""
|
| 114 |
+
compare_steps: int = 1
|
| 115 |
+
"""Number of steps between comparison of the current reward with the best seen so far"""
|
| 116 |
+
ratio_threshold: float = 10.0
|
| 117 |
+
"""Skip mini-batches with high PPO ratios that can cause loss spikes"""
|
| 118 |
+
use_score_scaling: bool = False
|
| 119 |
+
"""Use score scaling"""
|
| 120 |
+
use_score_norm: bool = False
|
| 121 |
+
"""Use score normalization. Only applicable if use_score_scaling is True"""
|
| 122 |
+
score_clip: Optional[float] = None
|
| 123 |
+
"""Score clipping"""
|
| 124 |
+
whiten_rewards: bool = False
|
| 125 |
+
"""Whiten the rewards before compute advantages"""
|
| 126 |
+
|
| 127 |
+
# computed hyperparameters at runtime; we use `tyro.conf.Suppress` to hide them from the help text
|
| 128 |
+
is_encoder_decoder: Optional[tyro.conf.Suppress[bool]] = None
|
| 129 |
+
"""TO BE FILLED In RUNTIME: Whether the model is an encoder-decoder model"""
|
| 130 |
+
is_peft_model: Optional[tyro.conf.Suppress[bool]] = None
|
| 131 |
+
"""TO BE FILLED In RUNTIME: Whether the model is a PEFT model"""
|
| 132 |
+
backward_batch_size: tyro.conf.Suppress[int] = None
|
| 133 |
+
"""TO BE FILLED In RUNTIME: Number of samples optimized in an `optimizer.step()` call"""
|
| 134 |
+
global_backward_batch_size: tyro.conf.Suppress[int] = None
|
| 135 |
+
"""TO BE FILLED In RUNTIME: the effective `backward_batch_size` across all processes"""
|
| 136 |
+
global_batch_size: tyro.conf.Suppress[int] = None
|
| 137 |
+
"""TO BE FILLED In RUNTIME: the effective `batch_size` across all processes"""
|
| 138 |
+
|
| 139 |
+
if optimize_cuda_cache is not None:
|
| 140 |
+
warnings.warn(
|
| 141 |
+
"The `optimize_cuda_cache` argument will be deprecated soon, please use `optimize_device_cache` instead."
|
| 142 |
+
)
|
| 143 |
+
optimize_device_cache = optimize_cuda_cache
|
| 144 |
+
else:
|
| 145 |
+
optimize_device_cache = False
|
| 146 |
+
|
| 147 |
+
def __post_init__(self):
|
| 148 |
+
if self.forward_batch_size is not None:
|
| 149 |
+
warnings.warn(
|
| 150 |
+
"Note that using `forward_batch_size` is deprecated, use `mini_batch_size` instead. By setting it you overwrite `mini_batch_size` which affects both the batch size during forward passes and also the mini batch size for PPO optimization."
|
| 151 |
+
)
|
| 152 |
+
self.mini_batch_size = self.forward_batch_size
|
| 153 |
+
|
| 154 |
+
self.backward_batch_size = self.mini_batch_size * self.gradient_accumulation_steps
|
| 155 |
+
exact_div(
|
| 156 |
+
self.batch_size,
|
| 157 |
+
self.backward_batch_size,
|
| 158 |
+
"`batch_size`",
|
| 159 |
+
"`mini_batch_size * gradient_accumulation_steps`",
|
| 160 |
+
"`batch_size` must be a multiple of `mini_batch_size * gradient_accumulation_steps`",
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# check if wandb is installed
|
| 164 |
+
if self.log_with == "wandb":
|
| 165 |
+
# raise error if wandb is not installed
|
| 166 |
+
if not is_wandb_available():
|
| 167 |
+
raise ImportError(
|
| 168 |
+
"Please install wandb to use wandb logging. You can do this by running `pip install wandb`."
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
self.total_ppo_epochs = int(np.ceil(self.steps / self.batch_size))
|
| 172 |
+
assert self.kl_penalty in ["kl", "abs", "mse", "full"]
|
| 173 |
+
|
| 174 |
+
def to_dict(self):
|
| 175 |
+
output_dict = {}
|
| 176 |
+
for key, value in self.__dict__.items():
|
| 177 |
+
output_dict[key] = value
|
| 178 |
+
return flatten_dict(output_dict)
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/ppo_trainer.py
ADDED
|
@@ -0,0 +1,1454 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
if is_deepspeed_available():
|
| 60 |
+
import deepspeed
|
| 61 |
+
|
| 62 |
+
MODEL_CARD_TEMPLATE = """---
|
| 63 |
+
license: apache-2.0
|
| 64 |
+
tags:
|
| 65 |
+
- trl
|
| 66 |
+
- ppo
|
| 67 |
+
- transformers
|
| 68 |
+
- reinforcement-learning
|
| 69 |
+
---
|
| 70 |
+
|
| 71 |
+
# {model_name}
|
| 72 |
+
|
| 73 |
+
This is a [TRL language model](https://github.com/huggingface/trl) that has been fine-tuned with reinforcement learning to
|
| 74 |
+
guide the model outputs according to a value, function, or human feedback. The model can be used for text generation.
|
| 75 |
+
|
| 76 |
+
## Usage
|
| 77 |
+
|
| 78 |
+
To use this model for inference, first install the TRL library:
|
| 79 |
+
|
| 80 |
+
```bash
|
| 81 |
+
python -m pip install trl
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
You can then generate text as follows:
|
| 85 |
+
|
| 86 |
+
```python
|
| 87 |
+
from transformers import pipeline
|
| 88 |
+
|
| 89 |
+
generator = pipeline("text-generation", model="{model_id}")
|
| 90 |
+
outputs = generator("Hello, my llama is cute")
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
If you want to use the model for training or to obtain the outputs from the value head, load the model as follows:
|
| 94 |
+
|
| 95 |
+
```python
|
| 96 |
+
from transformers import AutoTokenizer
|
| 97 |
+
from trl import AutoModelForCausalLMWithValueHead
|
| 98 |
+
|
| 99 |
+
tokenizer = AutoTokenizer.from_pretrained("{model_id}")
|
| 100 |
+
model = AutoModelForCausalLMWithValueHead.from_pretrained("{model_id}")
|
| 101 |
+
|
| 102 |
+
inputs = tokenizer("Hello, my llama is cute", return_tensors="pt")
|
| 103 |
+
outputs = model(**inputs, labels=inputs["input_ids"])
|
| 104 |
+
```
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class PPOTrainer(BaseTrainer):
|
| 109 |
+
"""
|
| 110 |
+
The PPOTrainer uses Proximal Policy Optimization to optimise language models.
|
| 111 |
+
Note, this trainer is heavily inspired by the original OpenAI learning to summarize work here:
|
| 112 |
+
https://github.com/openai/summarize-from-feedback
|
| 113 |
+
|
| 114 |
+
Attributes:
|
| 115 |
+
**config** (`PPOConfig`) -- Configuration object for PPOTrainer. Check the documentation of `PPOConfig` for more
|
| 116 |
+
details.
|
| 117 |
+
**model** (`PreTrainedModelWrapper`) -- Model to be optimized, Hugging Face transformer model with a value head.
|
| 118 |
+
Check the documentation of `PreTrainedModelWrapper` for more details.
|
| 119 |
+
**ref_model** (`PreTrainedModelWrapper`, *optional*) -- Reference model to be used for KL penalty, Hugging Face
|
| 120 |
+
transformer model with a casual language modelling head. Check the documentation of `PreTrainedModelWrapper`
|
| 121 |
+
for more details. If no reference model is provided, the trainer will create a reference model with the same
|
| 122 |
+
architecture as the model to be optimized with shared layers.
|
| 123 |
+
**tokenizer** (`PreTrainedTokenizerBase`) -- Tokenizer to be used for encoding the
|
| 124 |
+
data. Check the documentation of `transformers.PreTrainedTokenizer` and
|
| 125 |
+
`transformers.PreTrainedTokenizerFast` for more details.
|
| 126 |
+
**dataset** (Union[`torch.utils.data.Dataset`, `datasets.Dataset`], *optional*) -- PyTorch dataset or Hugging
|
| 127 |
+
Face dataset. This is used to create a PyTorch dataloader. If no dataset is provided, the dataloader must be
|
| 128 |
+
created outside the trainer users needs to design their own dataloader and make sure the batch
|
| 129 |
+
size that is used is the same as the one specified in the configuration object.
|
| 130 |
+
**optimizer** (`torch.optim.Optimizer`, *optional*) -- Optimizer to be used for training. If no optimizer is
|
| 131 |
+
provided, the trainer will create an Adam optimizer with the learning rate specified in the configuration
|
| 132 |
+
object.
|
| 133 |
+
**data_collator** (DataCollatorForLanguageModeling, *optional*) -- Data collator to be used for training and
|
| 134 |
+
passed along the dataloader
|
| 135 |
+
**num_shared_layers** (int, *optional*) -- Number of layers to be shared between the model and the reference
|
| 136 |
+
model, if no reference model is passed. If no number is provided, all the layers will be shared.
|
| 137 |
+
**lr_scheduler** (`torch.optim.lr_scheduler`, *optional*) -- Learning rate scheduler to be used for training.
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
_tag_names = ["trl", "ppo"]
|
| 141 |
+
|
| 142 |
+
def __init__(
|
| 143 |
+
self,
|
| 144 |
+
config: PPOConfig = None,
|
| 145 |
+
model: PreTrainedModelWrapper = None,
|
| 146 |
+
ref_model: Optional[PreTrainedModelWrapper] = None,
|
| 147 |
+
tokenizer: PreTrainedTokenizerBase = None,
|
| 148 |
+
dataset: Optional[Union[torch.utils.data.Dataset, Dataset]] = None,
|
| 149 |
+
optimizer: Optional[torch.optim.Optimizer] = None,
|
| 150 |
+
data_collator: Optional[typing.Callable] = None,
|
| 151 |
+
num_shared_layers: Optional[int] = None,
|
| 152 |
+
lr_scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None,
|
| 153 |
+
):
|
| 154 |
+
"""
|
| 155 |
+
Initialize PPOTrainer.
|
| 156 |
+
|
| 157 |
+
Args:
|
| 158 |
+
config (`PPOConfig`):
|
| 159 |
+
Configuration object for PPOTrainer. Check the documentation of `PPOConfig` for more details.
|
| 160 |
+
model (`PreTrainedModelWrapper`):
|
| 161 |
+
Hugging Face transformer model with a value head.
|
| 162 |
+
ref_model (`PreTrainedModelWrapper`):
|
| 163 |
+
Hugging Face transformer model with a casual language modelling head. Used for KL penalty
|
| 164 |
+
tokenizer (`transformers.PreTrainedTokenizerBase`):
|
| 165 |
+
Hugging Face tokenizer
|
| 166 |
+
dataset (Optional[Union[`torch.utils.data.Dataset`, `datasets.Dataset`]]):
|
| 167 |
+
PyTorch dataset or Hugging Face dataset. If a Hugging Face dataset is passed, the dataset
|
| 168 |
+
will be preprocessed by removing the columns that are not used by the model. If none is passed,
|
| 169 |
+
a warning will be raised in a multi-GPU setting.
|
| 170 |
+
optimizer (Optional[`torch.optim.Optimizer`]):
|
| 171 |
+
Optimizer used for training. If `None`, the `Adam` is used as default.
|
| 172 |
+
data_collator (Optional[function]):
|
| 173 |
+
Data collator function.
|
| 174 |
+
num_shared_layers (Optional[int]):
|
| 175 |
+
Number of shared layers between the model and the reference model. If `None`, all layers are shared.
|
| 176 |
+
used only if `ref_model` is `None`.
|
| 177 |
+
lr_scheduler (Optional[`torch.optim.lr_scheduler`]):
|
| 178 |
+
Learning rate scheduler used for training.
|
| 179 |
+
"""
|
| 180 |
+
super().__init__(config)
|
| 181 |
+
|
| 182 |
+
# initial seed for reproducible experiments
|
| 183 |
+
set_seed(config.seed)
|
| 184 |
+
|
| 185 |
+
# Step 0: check positional arguments validity
|
| 186 |
+
if not isinstance(config, PPOConfig):
|
| 187 |
+
raise ValueError(f"config must be a PPOConfig, got {type(config)}")
|
| 188 |
+
if not isinstance(tokenizer, (PreTrainedTokenizerBase)):
|
| 189 |
+
raise ValueError(
|
| 190 |
+
f"tokenizer must be a PreTrainedTokenizerBase like a PreTrainedTokenizer or a PreTrainedTokenizerFast, got {type(tokenizer)}"
|
| 191 |
+
)
|
| 192 |
+
if not isinstance(model, (SUPPORTED_ARCHITECTURES)):
|
| 193 |
+
raise ValueError(
|
| 194 |
+
f"model must be a PreTrainedModelWrapper, got {type(model)} - supported architectures are: {SUPPORTED_ARCHITECTURES}"
|
| 195 |
+
)
|
| 196 |
+
# Step 1: Initialize Accelerator
|
| 197 |
+
self.accelerator = Accelerator(
|
| 198 |
+
log_with=config.log_with,
|
| 199 |
+
gradient_accumulation_steps=config.gradient_accumulation_steps,
|
| 200 |
+
project_config=ProjectConfiguration(**config.project_kwargs),
|
| 201 |
+
**config.accelerator_kwargs,
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# Step 1.1 Runtime variables filled by the accelerator
|
| 205 |
+
config.world_size = self.accelerator.num_processes
|
| 206 |
+
config.global_backward_batch_size = config.backward_batch_size * config.world_size
|
| 207 |
+
config.global_batch_size = config.batch_size * config.world_size
|
| 208 |
+
|
| 209 |
+
self.model = model
|
| 210 |
+
self.model_params = filter(lambda p: p.requires_grad, self.model.parameters())
|
| 211 |
+
self.is_encoder_decoder = hasattr(self.model, "is_encoder_decoder")
|
| 212 |
+
self.is_peft_model = getattr(self.model, "is_peft_model", False)
|
| 213 |
+
config.is_encoder_decoder = self.is_encoder_decoder
|
| 214 |
+
config.is_peft_model = self.is_peft_model
|
| 215 |
+
|
| 216 |
+
is_using_tensorboard = config.log_with is not None and config.log_with == "tensorboard"
|
| 217 |
+
self.accelerator.init_trackers(
|
| 218 |
+
config.tracker_project_name,
|
| 219 |
+
config=dict(trl_ppo_trainer_config=config.to_dict()) if not is_using_tensorboard else config.to_dict(),
|
| 220 |
+
init_kwargs=config.tracker_kwargs,
|
| 221 |
+
)
|
| 222 |
+
self.is_using_text_environment = getattr(config, "use_text_environment", False)
|
| 223 |
+
|
| 224 |
+
if isinstance(ref_model, SUPPORTED_ARCHITECTURES):
|
| 225 |
+
self.ref_model = ref_model
|
| 226 |
+
if num_shared_layers is not None:
|
| 227 |
+
warnings.warn(
|
| 228 |
+
"num_shared_layers is ignored when ref_model is provided. Two different models are used for the "
|
| 229 |
+
"model and the reference model and no layers are shared.",
|
| 230 |
+
UserWarning,
|
| 231 |
+
)
|
| 232 |
+
elif ref_model is None and not self.is_peft_model:
|
| 233 |
+
self.ref_model = create_reference_model(self.model, num_shared_layers=num_shared_layers)
|
| 234 |
+
elif self.is_peft_model:
|
| 235 |
+
self.ref_model = None
|
| 236 |
+
else:
|
| 237 |
+
raise ValueError(
|
| 238 |
+
f"ref_model must be a PreTrainedModelWrapper or `None`, got {type(ref_model)} - supported "
|
| 239 |
+
f"architectures are: {SUPPORTED_ARCHITECTURES} "
|
| 240 |
+
)
|
| 241 |
+
self.optional_peft_ctx = (
|
| 242 |
+
self.accelerator.unwrap_model(self.model).pretrained_model.disable_adapter
|
| 243 |
+
if self.is_peft_model
|
| 244 |
+
else nullcontext
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
if not (isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast)):
|
| 248 |
+
raise ValueError(
|
| 249 |
+
"tokenizer must be a transformers.PreTrainedTokenizer or transformers.PreTrainedTokenizerFast"
|
| 250 |
+
)
|
| 251 |
+
self.tokenizer = tokenizer
|
| 252 |
+
|
| 253 |
+
if dataset is not None and not (isinstance(dataset, torch.utils.data.Dataset) or isinstance(dataset, Dataset)):
|
| 254 |
+
raise ValueError("dataset must be a torch.utils.data.Dataset or datasets.Dataset")
|
| 255 |
+
elif dataset is None:
|
| 256 |
+
warnings.warn(
|
| 257 |
+
"No dataset is provided. Make sure to set config.batch_size to the correct value before training.",
|
| 258 |
+
UserWarning,
|
| 259 |
+
)
|
| 260 |
+
self.dataset = dataset
|
| 261 |
+
self._signature_columns = None
|
| 262 |
+
if self.dataset is not None:
|
| 263 |
+
self.dataloader = self.prepare_dataloader(self.dataset, data_collator)
|
| 264 |
+
elif self.dataset is None and self.accelerator.num_processes > 1:
|
| 265 |
+
warnings.warn(
|
| 266 |
+
"No dataset is provided. In a multi-GPU setting, this will lead to an error. You should"
|
| 267 |
+
" prepare your dataloader yourself with `dataloader = ppo_trainer.accelerator.prepare(dataloader)`"
|
| 268 |
+
" and using `torch.utils.data.DataLoader`, or pass a dataset to the `PPOTrainer`. Please "
|
| 269 |
+
" refer to the documentation for more details.",
|
| 270 |
+
UserWarning,
|
| 271 |
+
)
|
| 272 |
+
self.dataloader = None
|
| 273 |
+
else:
|
| 274 |
+
self.dataloader = None
|
| 275 |
+
|
| 276 |
+
# Step 3: Initialize optimizer and data collator
|
| 277 |
+
self.data_collator = DataCollatorForLanguageModeling(self.tokenizer, mlm=False)
|
| 278 |
+
if optimizer is None:
|
| 279 |
+
self.optimizer = Adam(
|
| 280 |
+
filter(lambda p: p.requires_grad, self.model.parameters()),
|
| 281 |
+
lr=self.config.learning_rate,
|
| 282 |
+
)
|
| 283 |
+
else:
|
| 284 |
+
self.optimizer = optimizer
|
| 285 |
+
|
| 286 |
+
self.lr_scheduler = lr_scheduler
|
| 287 |
+
if self.lr_scheduler is not None:
|
| 288 |
+
lr_scheduler_class = (
|
| 289 |
+
torch.optim.lr_scheduler._LRScheduler
|
| 290 |
+
if not is_torch_greater_2_0()
|
| 291 |
+
else torch.optim.lr_scheduler.LRScheduler
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
if not isinstance(self.lr_scheduler, lr_scheduler_class):
|
| 295 |
+
raise ValueError(
|
| 296 |
+
"lr_scheduler must be a torch.optim.lr_scheduler._LRScheduler or torch.optim.lr_scheduler.LRScheduler (for torch >= 2.0)"
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
if self.config.adap_kl_ctrl:
|
| 300 |
+
self.kl_ctl = AdaptiveKLController(self.config.init_kl_coef, self.config.target, self.config.horizon)
|
| 301 |
+
else:
|
| 302 |
+
self.kl_ctl = FixedKLController(self.config.init_kl_coef)
|
| 303 |
+
|
| 304 |
+
# Safety checkers for DS integration
|
| 305 |
+
is_deepspeed_used = self.accelerator.distributed_type == "DEEPSPEED" and hasattr(
|
| 306 |
+
self.accelerator.state, "deepspeed_plugin"
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
(
|
| 310 |
+
self.model,
|
| 311 |
+
self.optimizer,
|
| 312 |
+
self.data_collator,
|
| 313 |
+
self.dataloader,
|
| 314 |
+
self.lr_scheduler,
|
| 315 |
+
) = self.accelerator.prepare(
|
| 316 |
+
self.model,
|
| 317 |
+
self.optimizer,
|
| 318 |
+
self.data_collator,
|
| 319 |
+
self.dataloader,
|
| 320 |
+
self.lr_scheduler,
|
| 321 |
+
)
|
| 322 |
+
if is_deepspeed_used:
|
| 323 |
+
# Quantized models are already set on the correct device
|
| 324 |
+
if not self.is_peft_model and not (
|
| 325 |
+
getattr(self.ref_model.pretrained_model, "is_loaded_in_8bit", False)
|
| 326 |
+
or getattr(self.ref_model.pretrained_model, "is_loaded_in_4bit", False)
|
| 327 |
+
):
|
| 328 |
+
self.ref_model = self._prepare_deepspeed(self.ref_model)
|
| 329 |
+
else:
|
| 330 |
+
self.ref_model = self.accelerator.prepare(self.ref_model)
|
| 331 |
+
|
| 332 |
+
# In a distributed setup, only logging needs to be performed on the main process
|
| 333 |
+
# check: https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html
|
| 334 |
+
# or: https://discuss.pytorch.org/t/use-distributed-data-parallel-correctly/82500/11
|
| 335 |
+
self.is_distributed = self.accelerator.num_processes > 1
|
| 336 |
+
|
| 337 |
+
# init the current step
|
| 338 |
+
self.current_step = 0
|
| 339 |
+
|
| 340 |
+
# init variables for pushing model to hub
|
| 341 |
+
if config.push_to_hub_if_best_kwargs:
|
| 342 |
+
if "repo_id" not in config.push_to_hub_if_best_kwargs:
|
| 343 |
+
raise ValueError("You have to specify repo_id in order to push the model to the hub!")
|
| 344 |
+
self.push_to_hub_kwargs = config.push_to_hub_if_best_kwargs
|
| 345 |
+
self.compare_step = 0
|
| 346 |
+
self.highest_reward = torch.tensor(-float("inf"))
|
| 347 |
+
|
| 348 |
+
# post process for PP
|
| 349 |
+
if not getattr(self.model, "is_sequential_parallel", False):
|
| 350 |
+
self.current_device = self.accelerator.device
|
| 351 |
+
else:
|
| 352 |
+
if is_xpu_available():
|
| 353 |
+
self.current_device = torch.device("xpu:0")
|
| 354 |
+
elif is_npu_available():
|
| 355 |
+
self.current_device = torch.device("npu:0")
|
| 356 |
+
else:
|
| 357 |
+
self.current_device = torch.device("cuda:0")
|
| 358 |
+
|
| 359 |
+
PPODecorators.optimize_device_cache = self.config.optimize_device_cache
|
| 360 |
+
|
| 361 |
+
self.running = RunningMoments(self.accelerator)
|
| 362 |
+
|
| 363 |
+
def _filter_kwargs(self, kwargs, target_func):
|
| 364 |
+
"""
|
| 365 |
+
filter the keyword arguments that are supported by the target function.
|
| 366 |
+
|
| 367 |
+
Args:
|
| 368 |
+
kwargs (dict):
|
| 369 |
+
Keyword arguments
|
| 370 |
+
target_func (function):
|
| 371 |
+
Target function
|
| 372 |
+
"""
|
| 373 |
+
return {k: v for k, v in kwargs.items() if k in inspect.signature(target_func).parameters.keys()}
|
| 374 |
+
|
| 375 |
+
def prepare_dataloader(self, dataset: Union[torch.utils.data.Dataset, Dataset], data_collator=None):
|
| 376 |
+
"""
|
| 377 |
+
Prepare the dataloader for training.
|
| 378 |
+
|
| 379 |
+
Args:
|
| 380 |
+
dataset (Union[`torch.utils.data.Dataset`, `datasets.Dataset`]):
|
| 381 |
+
PyTorch dataset or Hugging Face dataset. If a Hugging Face dataset is passed, the dataset
|
| 382 |
+
will be preprocessed by removing the columns that are not used by the model.
|
| 383 |
+
data_collator (Optional[function]):
|
| 384 |
+
Data collator function.
|
| 385 |
+
|
| 386 |
+
Returns:
|
| 387 |
+
`torch.utils.data.DataLoader`: PyTorch dataloader
|
| 388 |
+
"""
|
| 389 |
+
if isinstance(dataset, Dataset):
|
| 390 |
+
dataset = self._remove_unused_columns(dataset)
|
| 391 |
+
dataloader = torch.utils.data.DataLoader(
|
| 392 |
+
dataset,
|
| 393 |
+
batch_size=self.config.batch_size,
|
| 394 |
+
collate_fn=data_collator,
|
| 395 |
+
shuffle=True,
|
| 396 |
+
drop_last=True,
|
| 397 |
+
)
|
| 398 |
+
return dataloader
|
| 399 |
+
|
| 400 |
+
# Adapted from transformers.Trainer._set_signature_columns_if_needed
|
| 401 |
+
def _set_signature_columns_if_needed(self):
|
| 402 |
+
if self._signature_columns is None:
|
| 403 |
+
# Inspect model forward signature to keep only the arguments it accepts.
|
| 404 |
+
signature = inspect.signature(self.model.forward)
|
| 405 |
+
self._signature_columns = list(signature.parameters.keys())
|
| 406 |
+
# label => sentiment | we need query and response for logging purpose
|
| 407 |
+
self._signature_columns += ["label", "query", "response"]
|
| 408 |
+
|
| 409 |
+
# Adapted from transformers.Trainer._remove_unused_columns
|
| 410 |
+
def _remove_unused_columns(self, dataset: "Dataset"):
|
| 411 |
+
if not self.config.remove_unused_columns:
|
| 412 |
+
return dataset
|
| 413 |
+
self._set_signature_columns_if_needed()
|
| 414 |
+
signature_columns = self._signature_columns
|
| 415 |
+
|
| 416 |
+
ignored_columns = list(set(dataset.column_names) - set(signature_columns))
|
| 417 |
+
|
| 418 |
+
columns = [k for k in signature_columns if k in dataset.column_names]
|
| 419 |
+
|
| 420 |
+
if version.parse(datasets.__version__) < version.parse("1.4.0"):
|
| 421 |
+
dataset.set_format(
|
| 422 |
+
type=dataset.format["type"],
|
| 423 |
+
columns=columns,
|
| 424 |
+
format_kwargs=dataset.format["format_kwargs"],
|
| 425 |
+
)
|
| 426 |
+
return dataset
|
| 427 |
+
else:
|
| 428 |
+
return dataset.remove_columns(ignored_columns)
|
| 429 |
+
|
| 430 |
+
def generate(
|
| 431 |
+
self,
|
| 432 |
+
query_tensor: Union[torch.Tensor, List[torch.Tensor]],
|
| 433 |
+
length_sampler: Callable = None,
|
| 434 |
+
batch_size: int = 4,
|
| 435 |
+
return_prompt: bool = True,
|
| 436 |
+
generate_ref_response: bool = False,
|
| 437 |
+
**generation_kwargs,
|
| 438 |
+
):
|
| 439 |
+
"""
|
| 440 |
+
Generate response with the model given the query tensor.
|
| 441 |
+
call the `generate` method of the model.
|
| 442 |
+
|
| 443 |
+
Args:
|
| 444 |
+
query_tensor (`torch.LongTensor`):
|
| 445 |
+
A tensor of shape (`seq_len`) containing query tokens or a list of tensors of shape (`seq_len`).
|
| 446 |
+
length_sampler (`Callable`, *optional*):
|
| 447 |
+
Callable that returns the number of newly generated tokens.
|
| 448 |
+
batch_size (`int`, *optional):
|
| 449 |
+
Batch size used for generation, defaults to `4`.
|
| 450 |
+
return_prompt (`bool`, *optional*):
|
| 451 |
+
If set to `False` the prompt is not returned but only the newly generated tokens, defaults to `True`.
|
| 452 |
+
generate_ref_response (`bool`, *optional*):
|
| 453 |
+
If set to `True` the reference response is also generated, defaults to `False`.
|
| 454 |
+
generation_kwargs (dict[str, Any]):
|
| 455 |
+
Keyword arguments for generation.
|
| 456 |
+
|
| 457 |
+
Returns:
|
| 458 |
+
`torch.LongTensor`: A tensor of shape (`batch_size`, `gen_len`) containing response tokens.
|
| 459 |
+
"""
|
| 460 |
+
if generate_ref_response:
|
| 461 |
+
ref_model = self.model if self.is_peft_model else self.ref_model
|
| 462 |
+
if isinstance(query_tensor, List):
|
| 463 |
+
response = self._generate_batched(
|
| 464 |
+
self.model,
|
| 465 |
+
query_tensor,
|
| 466 |
+
length_sampler=length_sampler,
|
| 467 |
+
batch_size=batch_size,
|
| 468 |
+
return_prompt=return_prompt,
|
| 469 |
+
**generation_kwargs,
|
| 470 |
+
)
|
| 471 |
+
if generate_ref_response:
|
| 472 |
+
with self.optional_peft_ctx():
|
| 473 |
+
ref_response = self._generate_batched(
|
| 474 |
+
ref_model,
|
| 475 |
+
query_tensor,
|
| 476 |
+
length_sampler=length_sampler,
|
| 477 |
+
batch_size=batch_size,
|
| 478 |
+
return_prompt=return_prompt,
|
| 479 |
+
**generation_kwargs,
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
else:
|
| 483 |
+
if len(query_tensor.shape) == 2:
|
| 484 |
+
raise ValueError(
|
| 485 |
+
"query_tensor must be a tensor of shape (`seq_len`) or a list of tensors of shape (`seq_len`)"
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
if length_sampler is not None:
|
| 489 |
+
generation_kwargs["max_new_tokens"] = length_sampler()
|
| 490 |
+
response = self.accelerator.unwrap_model(self.model).generate(
|
| 491 |
+
input_ids=query_tensor.unsqueeze(dim=0), **generation_kwargs
|
| 492 |
+
)
|
| 493 |
+
if generate_ref_response:
|
| 494 |
+
with self.optional_peft_ctx():
|
| 495 |
+
ref_response = ref_model.generate(input_ids=query_tensor.unsqueeze(dim=0), **generation_kwargs)
|
| 496 |
+
|
| 497 |
+
if not return_prompt and not self.is_encoder_decoder:
|
| 498 |
+
response = response[:, query_tensor.shape[0] :]
|
| 499 |
+
if generate_ref_response:
|
| 500 |
+
ref_response = ref_response[:, query_tensor.shape[0] :]
|
| 501 |
+
|
| 502 |
+
if generate_ref_response:
|
| 503 |
+
return response, ref_response
|
| 504 |
+
return response
|
| 505 |
+
|
| 506 |
+
def _generate_batched(
|
| 507 |
+
self,
|
| 508 |
+
model: PreTrainedModelWrapper,
|
| 509 |
+
query_tensors: List[torch.Tensor],
|
| 510 |
+
length_sampler: Callable = None,
|
| 511 |
+
batch_size: int = 4,
|
| 512 |
+
return_prompt: bool = True,
|
| 513 |
+
pad_to_multiple_of: int = None,
|
| 514 |
+
remove_padding: bool = True,
|
| 515 |
+
**generation_kwargs,
|
| 516 |
+
):
|
| 517 |
+
outputs = []
|
| 518 |
+
|
| 519 |
+
padding_side_default = self.tokenizer.padding_side
|
| 520 |
+
if not self.is_encoder_decoder:
|
| 521 |
+
self.tokenizer.padding_side = "left"
|
| 522 |
+
|
| 523 |
+
# in case we have fewer examples than bs
|
| 524 |
+
batch_size = min(len(query_tensors), batch_size)
|
| 525 |
+
|
| 526 |
+
for i in range(0, len(query_tensors), batch_size):
|
| 527 |
+
if length_sampler is not None:
|
| 528 |
+
generation_kwargs["max_new_tokens"] = length_sampler()
|
| 529 |
+
|
| 530 |
+
# prevent overflow if query tensors are not even multiple of bs
|
| 531 |
+
end_index = min(len(query_tensors), i + batch_size)
|
| 532 |
+
|
| 533 |
+
batch = query_tensors[i:end_index]
|
| 534 |
+
batch_mask = [torch.ones_like(element) for element in batch]
|
| 535 |
+
inputs = {"input_ids": batch, "attention_mask": batch_mask}
|
| 536 |
+
|
| 537 |
+
padded_inputs = self.tokenizer.pad(
|
| 538 |
+
inputs,
|
| 539 |
+
padding=True,
|
| 540 |
+
max_length=None,
|
| 541 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 542 |
+
return_tensors="pt",
|
| 543 |
+
).to(self.current_device)
|
| 544 |
+
|
| 545 |
+
generations = self.accelerator.unwrap_model(model).generate(**padded_inputs, **generation_kwargs)
|
| 546 |
+
|
| 547 |
+
for generation, mask in zip(generations, padded_inputs["attention_mask"]):
|
| 548 |
+
if not self.is_encoder_decoder:
|
| 549 |
+
output = generation[(1 - mask).sum() :] # remove padding
|
| 550 |
+
else:
|
| 551 |
+
output = generation
|
| 552 |
+
|
| 553 |
+
if not return_prompt and not self.is_encoder_decoder:
|
| 554 |
+
output = output[(mask).sum() :] # remove prompt
|
| 555 |
+
|
| 556 |
+
if remove_padding and self.tokenizer.eos_token_id in output:
|
| 557 |
+
pad_mask = output == self.tokenizer.eos_token_id
|
| 558 |
+
pad_start = torch.nonzero(pad_mask, as_tuple=False)[0, 0].item()
|
| 559 |
+
output = output[: pad_start + 1] # keep the eos token at the end
|
| 560 |
+
|
| 561 |
+
outputs.append(output)
|
| 562 |
+
|
| 563 |
+
self.tokenizer.padding_side = padding_side_default
|
| 564 |
+
return outputs
|
| 565 |
+
|
| 566 |
+
def _step_safety_checker(
|
| 567 |
+
self,
|
| 568 |
+
batch_size: int,
|
| 569 |
+
queries: List[torch.LongTensor],
|
| 570 |
+
responses: List[torch.LongTensor],
|
| 571 |
+
scores: List[torch.FloatTensor],
|
| 572 |
+
masks: Optional[List[torch.LongTensor]] = None,
|
| 573 |
+
):
|
| 574 |
+
"""
|
| 575 |
+
Check if the input data is valid for training.
|
| 576 |
+
|
| 577 |
+
Args:
|
| 578 |
+
batch_size (int):
|
| 579 |
+
Batch size from the config file.
|
| 580 |
+
queries (List[`torch.LongTensor`]):
|
| 581 |
+
List of tensors containing the encoded queries of shape (`query_length`)
|
| 582 |
+
responses (List[`torch.LongTensor`]):
|
| 583 |
+
List of tensors containing the encoded responses of shape (`response_length`)
|
| 584 |
+
scores (List[`torch.FloatTensor`]):
|
| 585 |
+
List of tensors containing the scores.
|
| 586 |
+
masks (List[`torch.LongTensor`], *optional*):
|
| 587 |
+
list of optional tensors containing the masks of shape (`query_length` + `response_length`)
|
| 588 |
+
Returns:
|
| 589 |
+
`tuple`: The input processed data.
|
| 590 |
+
"""
|
| 591 |
+
for name, tensor_list in zip(["queries", "responses", "scores"], [queries, responses, scores]):
|
| 592 |
+
if not isinstance(tensor_list, list):
|
| 593 |
+
raise ValueError(f"{name} must be a list of tensors - got {type(tensor_list)}")
|
| 594 |
+
if not isinstance(tensor_list[0], torch.Tensor):
|
| 595 |
+
raise ValueError(f"Elements in {name} must be tensors - got {type(tensor_list[0])}")
|
| 596 |
+
if batch_size is not None and len(tensor_list) != batch_size:
|
| 597 |
+
raise ValueError(
|
| 598 |
+
f"Batch size ({batch_size}) does not match number of examples - but got {len(tensor_list)} for: {name}"
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
# add queries, scores and responses on the correct device
|
| 602 |
+
queries = [tensor.to(self.current_device) for tensor in queries]
|
| 603 |
+
responses = [tensor.to(self.current_device) for tensor in responses]
|
| 604 |
+
scores = [tensor.to(self.current_device) for tensor in scores]
|
| 605 |
+
masks = [tensor.to(self.current_device) for tensor in masks] if masks is not None else None
|
| 606 |
+
|
| 607 |
+
# squeeze scores if needed
|
| 608 |
+
for i, score in enumerate(scores):
|
| 609 |
+
if score.dim() > 1:
|
| 610 |
+
raise ValueError(f"Scores must be 1-dimensional - got {score.dim()} for {score}")
|
| 611 |
+
elif score.dim() == 1:
|
| 612 |
+
scores[i] = score.squeeze()
|
| 613 |
+
|
| 614 |
+
return queries, responses, scores, masks
|
| 615 |
+
|
| 616 |
+
@PPODecorators.empty_device_cache()
|
| 617 |
+
def step(
|
| 618 |
+
self,
|
| 619 |
+
queries: List[torch.LongTensor],
|
| 620 |
+
responses: List[torch.LongTensor],
|
| 621 |
+
scores: List[torch.FloatTensor],
|
| 622 |
+
response_masks: Optional[List[torch.LongTensor]] = None,
|
| 623 |
+
):
|
| 624 |
+
"""
|
| 625 |
+
Run a PPO optimisation step given a list of queries, model responses, and rewards.
|
| 626 |
+
|
| 627 |
+
Args:
|
| 628 |
+
queries (List[`torch.LongTensor`]):
|
| 629 |
+
List of tensors containing the encoded queries of shape (`query_length`)
|
| 630 |
+
responses (List[`torch.LongTensor`]):
|
| 631 |
+
List of tensors containing the encoded responses of shape (`response_length`)
|
| 632 |
+
scores (List[`torch.FloatTensor`]):
|
| 633 |
+
List of tensors containing the scores.
|
| 634 |
+
response_masks (List[`torch.FloatTensor`], *optional*)):
|
| 635 |
+
List of tensors containing masks of the response tokens.
|
| 636 |
+
|
| 637 |
+
Returns:
|
| 638 |
+
`dict[str, Any]`: A summary of the training statistics
|
| 639 |
+
"""
|
| 640 |
+
bs = self.config.batch_size
|
| 641 |
+
|
| 642 |
+
queries, responses, scores, response_masks = self._step_safety_checker(
|
| 643 |
+
bs, queries, responses, scores, response_masks
|
| 644 |
+
)
|
| 645 |
+
scores = torch.tensor(scores, device=self.current_device)
|
| 646 |
+
if self.config.use_score_scaling:
|
| 647 |
+
# Score scaling
|
| 648 |
+
scores_mean, scores_std = self.running.update(scores)
|
| 649 |
+
tensor_to_kwargs = dict(dtype=scores.dtype, device=scores.device)
|
| 650 |
+
score_scaling_factor = self.running.std.to(**tensor_to_kwargs) + torch.finfo(scores.dtype).eps
|
| 651 |
+
if self.config.use_score_norm:
|
| 652 |
+
scores = (scores - self.running.mean.to(**tensor_to_kwargs)) / score_scaling_factor
|
| 653 |
+
else:
|
| 654 |
+
scores /= score_scaling_factor
|
| 655 |
+
|
| 656 |
+
if self.config.score_clip is not None:
|
| 657 |
+
# Score clipping
|
| 658 |
+
scores_dtype = scores.dtype
|
| 659 |
+
scores = torch.clip(scores.float(), -self.config.score_clip, self.config.score_clip).to(dtype=scores_dtype)
|
| 660 |
+
|
| 661 |
+
# if we want to push best model to the hub
|
| 662 |
+
if hasattr(self, "highest_reward"):
|
| 663 |
+
if self.compare_step % self.config.compare_steps == 0:
|
| 664 |
+
curr_mean_reward = scores.mean()
|
| 665 |
+
# if the best reward ever seen
|
| 666 |
+
if curr_mean_reward > self.highest_reward:
|
| 667 |
+
self.highest_reward = curr_mean_reward
|
| 668 |
+
# push model to hub
|
| 669 |
+
self.push_to_hub(**self.push_to_hub_kwargs)
|
| 670 |
+
self.compare_step += 1
|
| 671 |
+
|
| 672 |
+
timing = dict()
|
| 673 |
+
t0 = time.time()
|
| 674 |
+
|
| 675 |
+
t = time.time()
|
| 676 |
+
|
| 677 |
+
model_inputs = self.prepare_model_inputs(queries, responses)
|
| 678 |
+
|
| 679 |
+
if self.is_distributed:
|
| 680 |
+
pad_first = self.tokenizer.padding_side == "left"
|
| 681 |
+
|
| 682 |
+
model_inputs["input_ids"] = self.accelerator.pad_across_processes(
|
| 683 |
+
model_inputs["input_ids"],
|
| 684 |
+
dim=1,
|
| 685 |
+
pad_index=self.tokenizer.pad_token_id,
|
| 686 |
+
pad_first=pad_first,
|
| 687 |
+
)
|
| 688 |
+
model_inputs["attention_mask"] = self.accelerator.pad_across_processes(
|
| 689 |
+
model_inputs["attention_mask"], dim=1, pad_index=0, pad_first=pad_first
|
| 690 |
+
)
|
| 691 |
+
if self.is_encoder_decoder:
|
| 692 |
+
model_inputs["decoder_input_ids"] = self.accelerator.pad_across_processes(
|
| 693 |
+
model_inputs["decoder_input_ids"],
|
| 694 |
+
dim=1,
|
| 695 |
+
pad_index=self.tokenizer.pad_token_id,
|
| 696 |
+
pad_first=pad_first,
|
| 697 |
+
)
|
| 698 |
+
model_inputs["decoder_attention_mask"] = self.accelerator.pad_across_processes(
|
| 699 |
+
model_inputs["decoder_attention_mask"],
|
| 700 |
+
dim=1,
|
| 701 |
+
pad_index=0,
|
| 702 |
+
pad_first=pad_first,
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
model_inputs_names = list(model_inputs.keys())
|
| 706 |
+
|
| 707 |
+
full_kl_penalty = self.config.kl_penalty == "full"
|
| 708 |
+
|
| 709 |
+
with torch.no_grad():
|
| 710 |
+
all_logprobs, logits_or_none, values, masks = self.batched_forward_pass(
|
| 711 |
+
self.model,
|
| 712 |
+
queries,
|
| 713 |
+
responses,
|
| 714 |
+
model_inputs,
|
| 715 |
+
response_masks=response_masks,
|
| 716 |
+
return_logits=full_kl_penalty,
|
| 717 |
+
)
|
| 718 |
+
with self.optional_peft_ctx():
|
| 719 |
+
ref_logprobs, ref_logits_or_none, _, _ = self.batched_forward_pass(
|
| 720 |
+
self.model if self.is_peft_model else self.ref_model,
|
| 721 |
+
queries,
|
| 722 |
+
responses,
|
| 723 |
+
model_inputs,
|
| 724 |
+
return_logits=full_kl_penalty,
|
| 725 |
+
)
|
| 726 |
+
|
| 727 |
+
timing["time/ppo/forward_pass"] = time.time() - t
|
| 728 |
+
|
| 729 |
+
with torch.no_grad():
|
| 730 |
+
t = time.time()
|
| 731 |
+
if full_kl_penalty:
|
| 732 |
+
active_full_logprobs = logprobs_from_logits(logits_or_none, None, gather=False)
|
| 733 |
+
ref_full_logprobs = logprobs_from_logits(ref_logits_or_none, None, gather=False)
|
| 734 |
+
|
| 735 |
+
rewards, non_score_reward, kls = self.compute_rewards(
|
| 736 |
+
scores, active_full_logprobs, ref_full_logprobs, masks
|
| 737 |
+
)
|
| 738 |
+
else:
|
| 739 |
+
rewards, non_score_reward, kls = self.compute_rewards(scores, all_logprobs, ref_logprobs, masks)
|
| 740 |
+
timing["time/ppo/compute_rewards"] = time.time() - t
|
| 741 |
+
|
| 742 |
+
t = time.time()
|
| 743 |
+
values, advantages, returns = self.compute_advantages(values, rewards, masks)
|
| 744 |
+
timing["time/ppo/compute_advantages"] = time.time() - t
|
| 745 |
+
|
| 746 |
+
# upcast to float32 to avoid dataset issues
|
| 747 |
+
batch_dict = {
|
| 748 |
+
"queries": queries,
|
| 749 |
+
"responses": responses,
|
| 750 |
+
"logprobs": all_logprobs.to(torch.float32),
|
| 751 |
+
"values": values.to(torch.float32),
|
| 752 |
+
"masks": masks,
|
| 753 |
+
"advantages": advantages,
|
| 754 |
+
"returns": returns,
|
| 755 |
+
}
|
| 756 |
+
batch_dict.update(model_inputs)
|
| 757 |
+
|
| 758 |
+
t = time.time()
|
| 759 |
+
all_stats = []
|
| 760 |
+
early_stop = False
|
| 761 |
+
for _ in range(self.config.ppo_epochs):
|
| 762 |
+
if early_stop:
|
| 763 |
+
break
|
| 764 |
+
b_inds = np.random.permutation(bs)
|
| 765 |
+
for backward_batch_start in range(0, bs, self.config.backward_batch_size):
|
| 766 |
+
backward_batch_end = backward_batch_start + self.config.backward_batch_size
|
| 767 |
+
backward_batch_inds = b_inds[backward_batch_start:backward_batch_end]
|
| 768 |
+
|
| 769 |
+
for mini_batch_start in range(0, self.config.backward_batch_size, self.config.mini_batch_size):
|
| 770 |
+
mini_batch_end = mini_batch_start + self.config.mini_batch_size
|
| 771 |
+
mini_batch_inds = backward_batch_inds[mini_batch_start:mini_batch_end]
|
| 772 |
+
mini_batch_dict = {
|
| 773 |
+
"logprobs": batch_dict["logprobs"][mini_batch_inds],
|
| 774 |
+
"values": batch_dict["values"][mini_batch_inds],
|
| 775 |
+
"masks": batch_dict["masks"][mini_batch_inds],
|
| 776 |
+
# hacks: the queries and responses are ragged.
|
| 777 |
+
"queries": [batch_dict["queries"][i] for i in mini_batch_inds],
|
| 778 |
+
"responses": [batch_dict["responses"][i] for i in mini_batch_inds],
|
| 779 |
+
"advantages": batch_dict["advantages"][mini_batch_inds],
|
| 780 |
+
"returns": batch_dict["returns"][mini_batch_inds],
|
| 781 |
+
}
|
| 782 |
+
for k in model_inputs_names:
|
| 783 |
+
mini_batch_dict[k] = batch_dict[k][mini_batch_inds]
|
| 784 |
+
with self.accelerator.accumulate(self.model):
|
| 785 |
+
model_inputs = {k: mini_batch_dict[k] for k in model_inputs_names}
|
| 786 |
+
|
| 787 |
+
logprobs, logits, vpreds, _ = self.batched_forward_pass(
|
| 788 |
+
self.model,
|
| 789 |
+
mini_batch_dict["queries"],
|
| 790 |
+
mini_batch_dict["responses"],
|
| 791 |
+
model_inputs,
|
| 792 |
+
return_logits=True,
|
| 793 |
+
)
|
| 794 |
+
train_stats = self.train_minibatch(
|
| 795 |
+
mini_batch_dict["logprobs"],
|
| 796 |
+
mini_batch_dict["values"],
|
| 797 |
+
logprobs,
|
| 798 |
+
logits,
|
| 799 |
+
vpreds,
|
| 800 |
+
mini_batch_dict["masks"],
|
| 801 |
+
mini_batch_dict["advantages"],
|
| 802 |
+
mini_batch_dict["returns"],
|
| 803 |
+
)
|
| 804 |
+
all_stats.append(train_stats)
|
| 805 |
+
|
| 806 |
+
# typically, early stopping is done at the epoch level
|
| 807 |
+
if self.config.early_stopping:
|
| 808 |
+
policykl = train_stats["policy/policykl"]
|
| 809 |
+
early_stop = self._early_stop(policykl)
|
| 810 |
+
if early_stop:
|
| 811 |
+
break
|
| 812 |
+
|
| 813 |
+
timing["time/ppo/optimize_step"] = time.time() - t
|
| 814 |
+
|
| 815 |
+
t = time.time()
|
| 816 |
+
train_stats = stack_dicts(all_stats)
|
| 817 |
+
|
| 818 |
+
# reshape advantages/ratios such that they are not averaged.
|
| 819 |
+
train_stats["policy/advantages"] = torch.flatten(train_stats["policy/advantages"]).unsqueeze(0)
|
| 820 |
+
train_stats["policy/advantages"] = torch.nan_to_num(train_stats["policy/advantages"], WANDB_PADDING)
|
| 821 |
+
train_stats["policy/ratio"] = torch.flatten(train_stats["policy/ratio"]).unsqueeze(0)
|
| 822 |
+
|
| 823 |
+
stats = self.record_step_stats(
|
| 824 |
+
scores=scores,
|
| 825 |
+
logprobs=all_logprobs,
|
| 826 |
+
ref_logprobs=ref_logprobs,
|
| 827 |
+
non_score_reward=non_score_reward,
|
| 828 |
+
train_stats=train_stats,
|
| 829 |
+
kl_coef=self.kl_ctl.value,
|
| 830 |
+
masks=masks,
|
| 831 |
+
queries=queries,
|
| 832 |
+
responses=responses,
|
| 833 |
+
kls=kls,
|
| 834 |
+
)
|
| 835 |
+
# Gather/Reduce stats from all processes
|
| 836 |
+
if self.is_distributed:
|
| 837 |
+
stats = self.gather_stats(stats)
|
| 838 |
+
stats = stats_to_np(stats)
|
| 839 |
+
timing["time/ppo/calc_stats"] = time.time() - t
|
| 840 |
+
stats["ppo/learning_rate"] = self.optimizer.param_groups[0]["lr"]
|
| 841 |
+
|
| 842 |
+
# Update the KL control - multiply the batch_size by the number of processes
|
| 843 |
+
self.kl_ctl.update(
|
| 844 |
+
stats["objective/kl"],
|
| 845 |
+
self.config.batch_size * self.accelerator.num_processes,
|
| 846 |
+
)
|
| 847 |
+
|
| 848 |
+
# Log the total ppo time
|
| 849 |
+
timing["time/ppo/total"] = time.time() - t0
|
| 850 |
+
stats.update(timing)
|
| 851 |
+
|
| 852 |
+
# post-process stats for tensorboard and other loggers
|
| 853 |
+
if self.config.log_with != "wandb":
|
| 854 |
+
stats = convert_to_scalar(stats)
|
| 855 |
+
|
| 856 |
+
if self.lr_scheduler is not None:
|
| 857 |
+
self.lr_scheduler.step()
|
| 858 |
+
|
| 859 |
+
return stats
|
| 860 |
+
|
| 861 |
+
def _early_stop(self, policykl):
|
| 862 |
+
r"""
|
| 863 |
+
Handles the early stopping logic. If the policy KL is greater than the target KL, then the gradient is zeroed and
|
| 864 |
+
the optimization step is skipped.
|
| 865 |
+
This also handles the multi-gpu case where the policy KL is averaged across all processes.
|
| 866 |
+
|
| 867 |
+
Args:
|
| 868 |
+
policy_kl (torch.Tensor):
|
| 869 |
+
the policy KL
|
| 870 |
+
|
| 871 |
+
Returns:
|
| 872 |
+
`bool`: whether to early stop or not
|
| 873 |
+
"""
|
| 874 |
+
early_stop = False
|
| 875 |
+
if not self.config.early_stopping:
|
| 876 |
+
return early_stop
|
| 877 |
+
|
| 878 |
+
if not self.is_distributed and policykl > 1.5 * self.config.target_kl:
|
| 879 |
+
self.optimizer.zero_grad()
|
| 880 |
+
early_stop = True
|
| 881 |
+
elif self.is_distributed:
|
| 882 |
+
import torch.distributed as dist
|
| 883 |
+
|
| 884 |
+
# Wait for all processes to finish
|
| 885 |
+
dist.barrier()
|
| 886 |
+
|
| 887 |
+
# all gather the policykl
|
| 888 |
+
dist.all_reduce(policykl, dist.ReduceOp.SUM)
|
| 889 |
+
policykl /= self.accelerator.num_processes
|
| 890 |
+
|
| 891 |
+
if policykl > 1.5 * self.config.target_kl:
|
| 892 |
+
self.optimizer.zero_grad()
|
| 893 |
+
early_stop = True
|
| 894 |
+
return early_stop
|
| 895 |
+
|
| 896 |
+
def gather_stats(self, stats):
|
| 897 |
+
"""
|
| 898 |
+
Gather stats from all processes. Useful in the context of distributed training.
|
| 899 |
+
|
| 900 |
+
Args:
|
| 901 |
+
stats (dict[str, Any]):
|
| 902 |
+
a dictionary of stats to be gathered. The stats should contain torch tensors.
|
| 903 |
+
|
| 904 |
+
Returns:
|
| 905 |
+
`dict[str, Any]`: A dictionary of stats with the tensors gathered.
|
| 906 |
+
"""
|
| 907 |
+
import torch.distributed as dist
|
| 908 |
+
|
| 909 |
+
# Wait for all processes to finish
|
| 910 |
+
dist.barrier()
|
| 911 |
+
|
| 912 |
+
for k, v in stats.items():
|
| 913 |
+
if isinstance(v, torch.Tensor):
|
| 914 |
+
dist.all_reduce(v.to(self.accelerator.device), dist.ReduceOp.SUM)
|
| 915 |
+
v /= self.accelerator.num_processes
|
| 916 |
+
stats[k] = v
|
| 917 |
+
return stats
|
| 918 |
+
|
| 919 |
+
def prepare_model_inputs(self, queries: torch.Tensor, responses: torch.Tensor):
|
| 920 |
+
if self.is_encoder_decoder:
|
| 921 |
+
input_data = self.data_collator(
|
| 922 |
+
[{"input_ids": q, "attention_mask": torch.ones_like(q)} for q in queries]
|
| 923 |
+
).to(self.current_device)
|
| 924 |
+
|
| 925 |
+
decoder_inputs = self.data_collator(
|
| 926 |
+
[{"input_ids": r, "attention_mask": torch.ones_like(r)} for r in responses]
|
| 927 |
+
).to(self.current_device)
|
| 928 |
+
|
| 929 |
+
input_data["decoder_input_ids"] = decoder_inputs["input_ids"]
|
| 930 |
+
input_data["decoder_attention_mask"] = decoder_inputs["attention_mask"]
|
| 931 |
+
else:
|
| 932 |
+
input_ids = [torch.cat([q, r]) for q, r in zip(queries, responses)]
|
| 933 |
+
input_data = self.data_collator(
|
| 934 |
+
[{"input_ids": ids, "attention_mask": torch.ones_like(ids)} for ids in input_ids]
|
| 935 |
+
).to(self.current_device)
|
| 936 |
+
|
| 937 |
+
input_data.pop("labels", None) # we don't want to compute LM losses
|
| 938 |
+
return input_data
|
| 939 |
+
|
| 940 |
+
@PPODecorators.empty_device_cache()
|
| 941 |
+
def batched_forward_pass(
|
| 942 |
+
self,
|
| 943 |
+
model: PreTrainedModelWrapper,
|
| 944 |
+
queries: torch.Tensor,
|
| 945 |
+
responses: torch.Tensor,
|
| 946 |
+
model_inputs: dict,
|
| 947 |
+
return_logits: bool = False,
|
| 948 |
+
response_masks: Optional[torch.Tensor] = None,
|
| 949 |
+
):
|
| 950 |
+
"""
|
| 951 |
+
Calculate model outputs in multiple batches.
|
| 952 |
+
|
| 953 |
+
Args:
|
| 954 |
+
queries (`torch.LongTensor`):
|
| 955 |
+
List of tensors containing the encoded queries, shape (`batch_size`, `query_length`)
|
| 956 |
+
responses (`torch.LongTensor`):
|
| 957 |
+
List of tensors containing the encoded responses, shape (`batch_size`, `response_length`)
|
| 958 |
+
return_logits (`bool`, *optional*, defaults to `False`):
|
| 959 |
+
Whether to return all_logits. Set to `False` if logits are not needed to reduce memory consumption.
|
| 960 |
+
Returns:
|
| 961 |
+
(tuple):
|
| 962 |
+
- all_logprobs (`torch.FloatTensor`): Log probabilities of the responses,
|
| 963 |
+
shape (`batch_size`, `response_length`)
|
| 964 |
+
- all_ref_logprobs (`torch.FloatTensor`): Log probabilities of the responses,
|
| 965 |
+
shape (`batch_size`, `response_length`)
|
| 966 |
+
- all_values (`torch.FloatTensor`): Values of the responses, shape (`batch_size`, `response_length`)
|
| 967 |
+
"""
|
| 968 |
+
bs = len(queries)
|
| 969 |
+
fbs = self.config.mini_batch_size
|
| 970 |
+
all_logprobs = []
|
| 971 |
+
all_logits = []
|
| 972 |
+
all_masks = []
|
| 973 |
+
all_values = []
|
| 974 |
+
|
| 975 |
+
model.eval()
|
| 976 |
+
|
| 977 |
+
for i in range(math.ceil(bs / fbs)):
|
| 978 |
+
input_kwargs = {key: value[i * fbs : (i + 1) * fbs] for key, value in model_inputs.items()}
|
| 979 |
+
query_batch = queries[i * fbs : (i + 1) * fbs]
|
| 980 |
+
response_batch = responses[i * fbs : (i + 1) * fbs]
|
| 981 |
+
if response_masks is not None:
|
| 982 |
+
response_masks_batch = response_masks[i * fbs : (i + 1) * fbs]
|
| 983 |
+
logits, _, values = model(**input_kwargs)
|
| 984 |
+
|
| 985 |
+
if self.is_encoder_decoder:
|
| 986 |
+
input_ids = input_kwargs["decoder_input_ids"]
|
| 987 |
+
attention_mask = input_kwargs["decoder_attention_mask"]
|
| 988 |
+
else:
|
| 989 |
+
input_ids = input_kwargs["input_ids"]
|
| 990 |
+
attention_mask = input_kwargs["attention_mask"]
|
| 991 |
+
|
| 992 |
+
logprobs = logprobs_from_logits(logits[:, :-1, :], input_ids[:, 1:])
|
| 993 |
+
masks = torch.zeros_like(attention_mask)
|
| 994 |
+
masks[:, :-1] = attention_mask[:, 1:]
|
| 995 |
+
|
| 996 |
+
for j in range(len(query_batch)):
|
| 997 |
+
if self.is_encoder_decoder:
|
| 998 |
+
# Decoder sentence starts always in the index 1 after padding in the Enc-Dec Models
|
| 999 |
+
start = 1
|
| 1000 |
+
end = attention_mask[j, :].sum() - 1
|
| 1001 |
+
else:
|
| 1002 |
+
start = len(query_batch[j]) - 1 # logprobs starts from the second query token
|
| 1003 |
+
if attention_mask[j, 0] == 0: # offset left padding
|
| 1004 |
+
start += attention_mask[j, :].nonzero()[0]
|
| 1005 |
+
end = start + len(response_batch[j])
|
| 1006 |
+
if response_masks is not None:
|
| 1007 |
+
response_masks_batch[j] = torch.cat(
|
| 1008 |
+
(torch.zeros_like(query_batch[j]), response_masks_batch[j])
|
| 1009 |
+
)[1:]
|
| 1010 |
+
|
| 1011 |
+
masks[j, :start] = 0
|
| 1012 |
+
masks[j, end:] = 0
|
| 1013 |
+
if response_masks is not None:
|
| 1014 |
+
masks[j, start:end] = masks[j, start:end] * response_masks_batch[j][start:end]
|
| 1015 |
+
|
| 1016 |
+
if return_logits:
|
| 1017 |
+
all_logits.append(logits)
|
| 1018 |
+
else:
|
| 1019 |
+
del logits
|
| 1020 |
+
all_values.append(values)
|
| 1021 |
+
all_logprobs.append(logprobs)
|
| 1022 |
+
all_masks.append(masks)
|
| 1023 |
+
|
| 1024 |
+
return (
|
| 1025 |
+
torch.cat(all_logprobs),
|
| 1026 |
+
torch.cat(all_logits)[:, :-1] if return_logits else None,
|
| 1027 |
+
torch.cat(all_values)[:, :-1],
|
| 1028 |
+
torch.cat(all_masks)[:, :-1],
|
| 1029 |
+
)
|
| 1030 |
+
|
| 1031 |
+
@PPODecorators.empty_device_cache()
|
| 1032 |
+
def train_minibatch(
|
| 1033 |
+
self,
|
| 1034 |
+
old_logprobs: torch.FloatTensor,
|
| 1035 |
+
values: torch.FloatTensor,
|
| 1036 |
+
logprobs: torch.FloatTensor,
|
| 1037 |
+
logits: torch.FloatTensor,
|
| 1038 |
+
vpreds: torch.FloatTensor,
|
| 1039 |
+
mask: torch.LongTensor,
|
| 1040 |
+
advantages: torch.FloatTensor,
|
| 1041 |
+
returns: torch.FloatTensor,
|
| 1042 |
+
):
|
| 1043 |
+
"""
|
| 1044 |
+
Train one PPO minibatch
|
| 1045 |
+
|
| 1046 |
+
Args:
|
| 1047 |
+
logprobs (`torch.FloatTensor`):
|
| 1048 |
+
Log probabilities of the model, shape [mini_batch_size, response_length]
|
| 1049 |
+
values (`torch.FloatTensor`):
|
| 1050 |
+
Values of the value head, shape [mini_batch_size, response_length]
|
| 1051 |
+
query (`torch.LongTensor`):
|
| 1052 |
+
Encoded queries, shape [mini_batch_size, query_length]
|
| 1053 |
+
response (`torch.LongTensor`):
|
| 1054 |
+
Encoded responses, shape [mini_batch_size, response_length]
|
| 1055 |
+
model_input (`torch.LongTensor`):
|
| 1056 |
+
Concatenated queries and responses, shape [mini_batch_size, query_length+response_length]
|
| 1057 |
+
|
| 1058 |
+
Returns:
|
| 1059 |
+
train_stats (dict[str, `torch.Tensor`]):
|
| 1060 |
+
Dictionary of training statistics
|
| 1061 |
+
"""
|
| 1062 |
+
self.model.train()
|
| 1063 |
+
loss_p, loss_v, train_stats = self.loss(
|
| 1064 |
+
old_logprobs, values, logits, vpreds, logprobs, mask, advantages, returns
|
| 1065 |
+
)
|
| 1066 |
+
loss = loss_p + loss_v
|
| 1067 |
+
self.accelerator.backward(loss)
|
| 1068 |
+
if self.config.max_grad_norm is not None:
|
| 1069 |
+
if self.accelerator.sync_gradients:
|
| 1070 |
+
self.accelerator.clip_grad_norm_(self.model_params, self.config.max_grad_norm)
|
| 1071 |
+
self.optimizer.step()
|
| 1072 |
+
# we call optimizer.zero_grad() every time and let `accelerator` handle accumulation
|
| 1073 |
+
# see https://huggingface.co/docs/accelerate/usage_guides/gradient_accumulation#the-finished-code
|
| 1074 |
+
self.optimizer.zero_grad()
|
| 1075 |
+
return train_stats
|
| 1076 |
+
|
| 1077 |
+
def compute_rewards(
|
| 1078 |
+
self,
|
| 1079 |
+
scores: torch.FloatTensor,
|
| 1080 |
+
logprobs: torch.FloatTensor,
|
| 1081 |
+
ref_logprobs: torch.FloatTensor,
|
| 1082 |
+
masks: torch.LongTensor,
|
| 1083 |
+
):
|
| 1084 |
+
"""
|
| 1085 |
+
Compute per token rewards from scores and KL-penalty.
|
| 1086 |
+
|
| 1087 |
+
Args:
|
| 1088 |
+
scores (`torch.FloatTensor`):
|
| 1089 |
+
Scores from the reward model, shape (`batch_size`)
|
| 1090 |
+
logprobs (`torch.FloatTensor`):
|
| 1091 |
+
Log probabilities of the model, shape (`batch_size`, `response_length`)
|
| 1092 |
+
ref_logprobs (`torch.FloatTensor`):
|
| 1093 |
+
Log probabilities of the reference model, shape (`batch_size`, `response_length`)
|
| 1094 |
+
|
| 1095 |
+
Returns:
|
| 1096 |
+
`torch.FloatTensor`: Per token rewards, shape (`batch_size`, `response_length`)
|
| 1097 |
+
`torch.FloatTensor`: Non score rewards, shape (`batch_size`, `response_length`)
|
| 1098 |
+
`torch.FloatTensor`: KL penalty, shape (`batch_size`, `response_length`)
|
| 1099 |
+
"""
|
| 1100 |
+
rewards, non_score_rewards, kls = [], [], []
|
| 1101 |
+
for score, logprob, ref_logprob, mask in zip(scores, logprobs, ref_logprobs, masks):
|
| 1102 |
+
# compute KL penalty (from difference in logprobs)
|
| 1103 |
+
kl = self._kl_penalty(logprob, ref_logprob)
|
| 1104 |
+
kls.append(kl)
|
| 1105 |
+
non_score_reward = -self.kl_ctl.value * kl
|
| 1106 |
+
non_score_rewards.append(non_score_reward)
|
| 1107 |
+
reward = non_score_reward.clone()
|
| 1108 |
+
last_non_masked_index = mask.nonzero()[-1]
|
| 1109 |
+
|
| 1110 |
+
# reward is preference model score + KL penalty
|
| 1111 |
+
reward[last_non_masked_index] += score
|
| 1112 |
+
rewards.append(reward)
|
| 1113 |
+
return torch.stack(rewards), torch.stack(non_score_rewards), torch.stack(kls)
|
| 1114 |
+
|
| 1115 |
+
def _kl_penalty(self, logprob: torch.FloatTensor, ref_logprob: torch.FloatTensor) -> torch.FloatTensor:
|
| 1116 |
+
if self.config.kl_penalty == "kl":
|
| 1117 |
+
return logprob - ref_logprob
|
| 1118 |
+
|
| 1119 |
+
if self.config.kl_penalty == "abs":
|
| 1120 |
+
return (logprob - ref_logprob).abs()
|
| 1121 |
+
|
| 1122 |
+
if self.config.kl_penalty == "mse":
|
| 1123 |
+
return 0.5 * (logprob - ref_logprob).square()
|
| 1124 |
+
|
| 1125 |
+
if self.config.kl_penalty == "full":
|
| 1126 |
+
# Flip is required due to this issue? :https://github.com/pytorch/pytorch/issues/57459
|
| 1127 |
+
return F.kl_div(ref_logprob, logprob, log_target=True, reduction="none").sum(-1)
|
| 1128 |
+
|
| 1129 |
+
raise NotImplementedError
|
| 1130 |
+
|
| 1131 |
+
def compute_advantages(
|
| 1132 |
+
self,
|
| 1133 |
+
values: torch.FloatTensor,
|
| 1134 |
+
rewards: torch.FloatTensor,
|
| 1135 |
+
mask: torch.FloatTensor,
|
| 1136 |
+
):
|
| 1137 |
+
lastgaelam = 0
|
| 1138 |
+
advantages_reversed = []
|
| 1139 |
+
gen_len = rewards.shape[-1]
|
| 1140 |
+
|
| 1141 |
+
values = values * mask
|
| 1142 |
+
rewards = rewards * mask
|
| 1143 |
+
|
| 1144 |
+
if self.config.whiten_rewards:
|
| 1145 |
+
rewards = masked_whiten(rewards, mask, shift_mean=False)
|
| 1146 |
+
|
| 1147 |
+
for t in reversed(range(gen_len)):
|
| 1148 |
+
nextvalues = values[:, t + 1] if t < gen_len - 1 else 0.0
|
| 1149 |
+
delta = rewards[:, t] + self.config.gamma * nextvalues - values[:, t]
|
| 1150 |
+
lastgaelam = delta + self.config.gamma * self.config.lam * lastgaelam
|
| 1151 |
+
advantages_reversed.append(lastgaelam)
|
| 1152 |
+
advantages = torch.stack(advantages_reversed[::-1]).transpose(0, 1)
|
| 1153 |
+
|
| 1154 |
+
returns = advantages + values
|
| 1155 |
+
advantages = masked_whiten(advantages, mask)
|
| 1156 |
+
advantages = advantages.detach()
|
| 1157 |
+
return values, advantages, returns
|
| 1158 |
+
|
| 1159 |
+
def loss(
|
| 1160 |
+
self,
|
| 1161 |
+
old_logprobs: torch.FloatTensor,
|
| 1162 |
+
values: torch.FloatTensor,
|
| 1163 |
+
logits: torch.FloatTensor,
|
| 1164 |
+
vpreds: torch.FloatTensor,
|
| 1165 |
+
logprobs: torch.FloatTensor,
|
| 1166 |
+
mask: torch.LongTensor,
|
| 1167 |
+
advantages: torch.FloatTensor,
|
| 1168 |
+
returns: torch.FloatTensor,
|
| 1169 |
+
):
|
| 1170 |
+
"""
|
| 1171 |
+
Calculate policy and value losses.
|
| 1172 |
+
|
| 1173 |
+
Args:
|
| 1174 |
+
old_logprobs (`torch.FloatTensor`):
|
| 1175 |
+
Log probabilities of the model, shape (`batch_size`, `response_length`)
|
| 1176 |
+
values (`torch.FloatTensor`):
|
| 1177 |
+
Values of the value head, shape (`batch_size`, `response_length`)
|
| 1178 |
+
rewards (`torch.FloatTensor`):
|
| 1179 |
+
Rewards from the reward model, shape (`batch_size`, `response_length`)
|
| 1180 |
+
logits (`torch.FloatTensor`):
|
| 1181 |
+
Logits of the model, shape (`batch_size`, `response_length`, `vocab_size`)
|
| 1182 |
+
v_pred (`torch.FloatTensor`):
|
| 1183 |
+
Values of the value head, shape (`batch_size`, `response_length`)
|
| 1184 |
+
logprobs (`torch.FloatTensor`):
|
| 1185 |
+
Log probabilities of the model, shape (`batch_size`, `response_length`)
|
| 1186 |
+
"""
|
| 1187 |
+
|
| 1188 |
+
vpredclipped = clip_by_value(
|
| 1189 |
+
vpreds,
|
| 1190 |
+
values - self.config.cliprange_value,
|
| 1191 |
+
values + self.config.cliprange_value,
|
| 1192 |
+
)
|
| 1193 |
+
|
| 1194 |
+
vf_losses1 = (vpreds - returns) ** 2
|
| 1195 |
+
vf_losses2 = (vpredclipped - returns) ** 2
|
| 1196 |
+
vf_loss = 0.5 * masked_mean(torch.max(vf_losses1, vf_losses2), mask)
|
| 1197 |
+
vf_clipfrac = masked_mean(torch.gt(vf_losses2, vf_losses1).float(), mask)
|
| 1198 |
+
|
| 1199 |
+
ratio = torch.exp(logprobs - old_logprobs)
|
| 1200 |
+
|
| 1201 |
+
pg_losses = -advantages * ratio
|
| 1202 |
+
pg_losses2 = -advantages * torch.clamp(ratio, 1.0 - self.config.cliprange, 1.0 + self.config.cliprange)
|
| 1203 |
+
|
| 1204 |
+
pg_loss = masked_mean(torch.max(pg_losses, pg_losses2), mask)
|
| 1205 |
+
pg_clipfrac = masked_mean(torch.gt(pg_losses2, pg_losses).float(), mask)
|
| 1206 |
+
|
| 1207 |
+
loss = pg_loss + self.config.vf_coef * vf_loss
|
| 1208 |
+
|
| 1209 |
+
avg_ratio = masked_mean(ratio, mask).item()
|
| 1210 |
+
if avg_ratio > self.config.ratio_threshold:
|
| 1211 |
+
warnings.warn(
|
| 1212 |
+
f"The average ratio of batch ({avg_ratio:.2f}) exceeds threshold {self.config.ratio_threshold:.2f}. Skipping batch."
|
| 1213 |
+
)
|
| 1214 |
+
pg_loss = pg_loss * 0.0
|
| 1215 |
+
vf_loss = vf_loss * 0.0
|
| 1216 |
+
loss = loss * 0.0
|
| 1217 |
+
|
| 1218 |
+
entropy = masked_mean(entropy_from_logits(logits), mask)
|
| 1219 |
+
|
| 1220 |
+
approxkl = 0.5 * masked_mean((logprobs - old_logprobs) ** 2, mask)
|
| 1221 |
+
policykl = masked_mean(old_logprobs - logprobs, mask)
|
| 1222 |
+
|
| 1223 |
+
return_mean, return_var = masked_mean(returns, mask), masked_var(returns, mask)
|
| 1224 |
+
value_mean, value_var = masked_mean(values, mask), masked_var(values, mask)
|
| 1225 |
+
|
| 1226 |
+
stats = dict(
|
| 1227 |
+
loss=dict(policy=pg_loss.detach(), value=vf_loss.detach(), total=loss.detach()),
|
| 1228 |
+
policy=dict(
|
| 1229 |
+
entropy=entropy.detach(),
|
| 1230 |
+
approxkl=approxkl.detach(),
|
| 1231 |
+
policykl=policykl.detach(),
|
| 1232 |
+
clipfrac=pg_clipfrac.detach(),
|
| 1233 |
+
advantages=advantages.detach(),
|
| 1234 |
+
advantages_mean=masked_mean(advantages, mask).detach(),
|
| 1235 |
+
ratio=ratio.detach(),
|
| 1236 |
+
),
|
| 1237 |
+
returns=dict(mean=return_mean.detach(), var=return_var.detach()),
|
| 1238 |
+
val=dict(
|
| 1239 |
+
vpred=masked_mean(vpreds, mask).detach(),
|
| 1240 |
+
error=masked_mean((vpreds - returns) ** 2, mask).detach(),
|
| 1241 |
+
clipfrac=vf_clipfrac.detach(),
|
| 1242 |
+
mean=value_mean.detach(),
|
| 1243 |
+
var=value_var.detach(),
|
| 1244 |
+
),
|
| 1245 |
+
)
|
| 1246 |
+
return pg_loss, self.config.vf_coef * vf_loss, flatten_dict(stats)
|
| 1247 |
+
|
| 1248 |
+
def record_step_stats(self, kl_coef: float, **data):
|
| 1249 |
+
"""
|
| 1250 |
+
Record training step statistics.
|
| 1251 |
+
|
| 1252 |
+
|
| 1253 |
+
Args:
|
| 1254 |
+
kl_coef (`float`):
|
| 1255 |
+
KL coefficient
|
| 1256 |
+
data (`dict`):
|
| 1257 |
+
Dictionary of training step data
|
| 1258 |
+
|
| 1259 |
+
Returns:
|
| 1260 |
+
stats (`dict`):
|
| 1261 |
+
Dictionary of training step statistics
|
| 1262 |
+
"""
|
| 1263 |
+
mask = data.pop("masks")
|
| 1264 |
+
|
| 1265 |
+
kls = data.pop("kls")
|
| 1266 |
+
kl_list = ((kls) * mask).sum(axis=-1)
|
| 1267 |
+
mean_kl = kl_list.mean()
|
| 1268 |
+
mean_entropy = (-data["logprobs"] * mask).sum(axis=-1).mean()
|
| 1269 |
+
|
| 1270 |
+
mean_non_score_reward = masked_mean(
|
| 1271 |
+
data["non_score_reward"], mask
|
| 1272 |
+
) # non_score_reward is size `batch_size`, `response_length`
|
| 1273 |
+
mean_scores = data["scores"].mean() # scores is size `batch_size`
|
| 1274 |
+
std_scores = data["scores"].std()
|
| 1275 |
+
|
| 1276 |
+
if mean_kl.item() < -1.0:
|
| 1277 |
+
# warn users
|
| 1278 |
+
warnings.warn(
|
| 1279 |
+
f"KL divergence is starting to become negative: {mean_kl.item():.2f} - this might be a precursor for failed training."
|
| 1280 |
+
" sometimes this happens because the generation kwargs are not correctly set. Please make sure"
|
| 1281 |
+
" that the generation kwargs are set correctly, or review your training hyperparameters."
|
| 1282 |
+
)
|
| 1283 |
+
|
| 1284 |
+
stats = {
|
| 1285 |
+
"objective/kl": mean_kl,
|
| 1286 |
+
"objective/kl_dist": kl_list,
|
| 1287 |
+
"objective/logprobs": data["logprobs"],
|
| 1288 |
+
"objective/ref_logprobs": data["ref_logprobs"],
|
| 1289 |
+
"objective/kl_coef": kl_coef,
|
| 1290 |
+
"objective/entropy": mean_entropy,
|
| 1291 |
+
"ppo/mean_non_score_reward": mean_non_score_reward,
|
| 1292 |
+
"ppo/mean_scores": mean_scores,
|
| 1293 |
+
"ppo/std_scores": std_scores,
|
| 1294 |
+
}
|
| 1295 |
+
|
| 1296 |
+
# Log text properties
|
| 1297 |
+
query_lens = torch.tensor([len(query) for query in data["queries"]], dtype=torch.float)
|
| 1298 |
+
response_lens = torch.tensor([len(response) for response in data["responses"]], dtype=torch.float)
|
| 1299 |
+
|
| 1300 |
+
stats["tokens/queries_len_mean"] = torch.mean(query_lens).cpu().numpy().item()
|
| 1301 |
+
stats["tokens/queries_len_std"] = torch.std(query_lens).cpu().numpy().item()
|
| 1302 |
+
stats["tokens/queries_dist"] = query_lens.cpu().numpy()
|
| 1303 |
+
stats["tokens/responses_len_mean"] = torch.mean(response_lens).cpu().numpy().item()
|
| 1304 |
+
stats["tokens/responses_len_std"] = torch.std(response_lens).cpu().numpy().item()
|
| 1305 |
+
stats["tokens/responses_dist"] = response_lens.cpu().numpy()
|
| 1306 |
+
|
| 1307 |
+
for k, v in data["train_stats"].items():
|
| 1308 |
+
stats[f"ppo/{k}"] = torch.mean(v, axis=0)
|
| 1309 |
+
stats["ppo/val/var_explained"] = 1 - stats["ppo/val/error"] / stats["ppo/returns/var"]
|
| 1310 |
+
return stats
|
| 1311 |
+
|
| 1312 |
+
def log_stats(
|
| 1313 |
+
self,
|
| 1314 |
+
stats: dict,
|
| 1315 |
+
batch: dict,
|
| 1316 |
+
rewards: List[torch.FloatTensor],
|
| 1317 |
+
columns_to_log: List[str] = ["query", "response"],
|
| 1318 |
+
):
|
| 1319 |
+
"""
|
| 1320 |
+
A function that logs all the training stats. Call it at the end of each epoch.
|
| 1321 |
+
|
| 1322 |
+
Args:
|
| 1323 |
+
stats (dict[str, Any]):
|
| 1324 |
+
A dictionary of training stats.
|
| 1325 |
+
batch (dict[str, Any]):
|
| 1326 |
+
A dictionary of batch data, this contains the queries and responses.
|
| 1327 |
+
rewards (`List[torch.FloatTensor]`):
|
| 1328 |
+
A tensor of rewards.
|
| 1329 |
+
"""
|
| 1330 |
+
|
| 1331 |
+
# all gather stats
|
| 1332 |
+
if not isinstance(rewards, torch.Tensor):
|
| 1333 |
+
rewards = torch.tensor(rewards).to(self.current_device)
|
| 1334 |
+
rewards = self.accelerator.gather(rewards).flatten()
|
| 1335 |
+
|
| 1336 |
+
if self.config.log_with == "wandb":
|
| 1337 |
+
import wandb
|
| 1338 |
+
|
| 1339 |
+
if any([column_to_log not in batch.keys() for column_to_log in columns_to_log]):
|
| 1340 |
+
raise ValueError(f"Columns to log {columns_to_log} are not present in the batch {batch.keys()}.")
|
| 1341 |
+
|
| 1342 |
+
batch_list = [batch[column_to_log] for column_to_log in columns_to_log]
|
| 1343 |
+
if self.is_distributed:
|
| 1344 |
+
gathered_batch_list = []
|
| 1345 |
+
for b in batch_list:
|
| 1346 |
+
flattened = gather_object(b)
|
| 1347 |
+
gathered_batch_list.append(flattened)
|
| 1348 |
+
batch_list = gathered_batch_list
|
| 1349 |
+
|
| 1350 |
+
# Log only if we are in the main process
|
| 1351 |
+
if self.accelerator.is_main_process:
|
| 1352 |
+
logs = {}
|
| 1353 |
+
|
| 1354 |
+
# Log stats
|
| 1355 |
+
if "query" not in batch.keys() and "response" not in batch.keys():
|
| 1356 |
+
# warn the user that the game logs will not be logged
|
| 1357 |
+
warnings.warn(
|
| 1358 |
+
"The game logs will not be logged because the batch does not contain the keys 'query' and "
|
| 1359 |
+
"'response'. "
|
| 1360 |
+
)
|
| 1361 |
+
elif self.config.log_with == "wandb":
|
| 1362 |
+
table_rows = [list(r) for r in zip(*batch_list, rewards.cpu().tolist())]
|
| 1363 |
+
logs.update({"game_log": wandb.Table(columns=[*columns_to_log, "reward"], rows=table_rows)})
|
| 1364 |
+
|
| 1365 |
+
logs.update(stats)
|
| 1366 |
+
|
| 1367 |
+
# manually cast in fp32 for bf16 torch tensors
|
| 1368 |
+
for k, v in logs.items():
|
| 1369 |
+
if isinstance(v, torch.Tensor) and v.dtype == torch.bfloat16:
|
| 1370 |
+
logs[k] = v.float()
|
| 1371 |
+
|
| 1372 |
+
logs["env/reward_mean"] = torch.mean(rewards).cpu().numpy().item()
|
| 1373 |
+
logs["env/reward_std"] = torch.std(rewards).cpu().numpy().item()
|
| 1374 |
+
logs["env/reward_dist"] = rewards.cpu().numpy()
|
| 1375 |
+
|
| 1376 |
+
if self.config.log_with == "tensorboard":
|
| 1377 |
+
# update the current step
|
| 1378 |
+
self.current_step += 1
|
| 1379 |
+
|
| 1380 |
+
self.accelerator.log(
|
| 1381 |
+
logs,
|
| 1382 |
+
step=self.current_step if self.config.log_with == "tensorboard" else None,
|
| 1383 |
+
)
|
| 1384 |
+
|
| 1385 |
+
def create_model_card(self, path: str, model_name: Optional[str] = "TRL Model") -> None:
|
| 1386 |
+
"""Creates and saves a model card for a TRL model.
|
| 1387 |
+
|
| 1388 |
+
Args:
|
| 1389 |
+
path (`str`): The path to save the model card to.
|
| 1390 |
+
model_name (`str`, *optional*): The name of the model, defaults to `TRL Model`.
|
| 1391 |
+
"""
|
| 1392 |
+
try:
|
| 1393 |
+
user = whoami()["name"]
|
| 1394 |
+
# handle the offline case
|
| 1395 |
+
except: # noqa
|
| 1396 |
+
warnings.warn("Cannot retrieve user information assuming you are running in offline mode.")
|
| 1397 |
+
return
|
| 1398 |
+
|
| 1399 |
+
if not os.path.exists(path):
|
| 1400 |
+
os.makedirs(path)
|
| 1401 |
+
|
| 1402 |
+
model_card_content = MODEL_CARD_TEMPLATE.format(model_name=model_name, model_id=f"{user}/{path}")
|
| 1403 |
+
with open(os.path.join(path, "README.md"), "w", encoding="utf-8") as f:
|
| 1404 |
+
f.write(model_card_content)
|
| 1405 |
+
|
| 1406 |
+
def _save_pretrained(self, save_directory: str) -> None:
|
| 1407 |
+
self.accelerator.unwrap_model(self.model).save_pretrained(save_directory)
|
| 1408 |
+
self.tokenizer.save_pretrained(save_directory)
|
| 1409 |
+
self.create_model_card(save_directory)
|
| 1410 |
+
|
| 1411 |
+
def _show_tokens(self, tokens, masks):
|
| 1412 |
+
from rich import print
|
| 1413 |
+
from rich.text import Text
|
| 1414 |
+
|
| 1415 |
+
text = Text()
|
| 1416 |
+
|
| 1417 |
+
for i, (token, mask) in enumerate(zip(tokens, masks)):
|
| 1418 |
+
if mask == 1:
|
| 1419 |
+
text.append(self.tokenizer.decode(token.item()), style="black on deep_sky_blue1")
|
| 1420 |
+
text.append(" ")
|
| 1421 |
+
else:
|
| 1422 |
+
text.append(self.tokenizer.decode(token.item()), style="black on cyan3")
|
| 1423 |
+
text.append(" ")
|
| 1424 |
+
print(text)
|
| 1425 |
+
|
| 1426 |
+
def _prepare_deepspeed(self, model: PreTrainedModelWrapper):
|
| 1427 |
+
# Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473
|
| 1428 |
+
deepspeed_plugin = self.accelerator.state.deepspeed_plugin
|
| 1429 |
+
config_kwargs = deepspeed_plugin.deepspeed_config
|
| 1430 |
+
if model is not None:
|
| 1431 |
+
if hasattr(model, "config"):
|
| 1432 |
+
hidden_size = (
|
| 1433 |
+
max(model.config.hidden_sizes)
|
| 1434 |
+
if getattr(model.config, "hidden_sizes", None)
|
| 1435 |
+
else getattr(model.config, "hidden_size", None)
|
| 1436 |
+
)
|
| 1437 |
+
if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3:
|
| 1438 |
+
# Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0`
|
| 1439 |
+
# This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081
|
| 1440 |
+
config_kwargs.update(
|
| 1441 |
+
{
|
| 1442 |
+
"zero_optimization.reduce_bucket_size": hidden_size * hidden_size,
|
| 1443 |
+
"zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size,
|
| 1444 |
+
"zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size,
|
| 1445 |
+
}
|
| 1446 |
+
)
|
| 1447 |
+
|
| 1448 |
+
# If ZeRO-3 is used, we shard both the active and reference model.
|
| 1449 |
+
# Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO disabled (stage 0)
|
| 1450 |
+
if config_kwargs["zero_optimization"]["stage"] != 3:
|
| 1451 |
+
config_kwargs["zero_optimization"]["stage"] = 0
|
| 1452 |
+
model, *_ = deepspeed.initialize(model=model, config=config_kwargs)
|
| 1453 |
+
model.eval()
|
| 1454 |
+
return model
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/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."""
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/reward_trainer.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
if is_peft_available():
|
| 32 |
+
from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class RewardTrainer(Trainer):
|
| 36 |
+
r"""
|
| 37 |
+
The RewardTrainer can be used to train your custom Reward Model. It is a subclass of the
|
| 38 |
+
`transformers.Trainer` class and inherits all of its attributes and methods. It is recommended to use
|
| 39 |
+
an `AutoModelForSequenceClassification` as the reward model. The reward model should be trained on a dataset
|
| 40 |
+
of paired examples, where each example is a tuple of two sequences. The reward model should be trained to
|
| 41 |
+
predict which example in the pair is more relevant to the task at hand.
|
| 42 |
+
|
| 43 |
+
The reward trainer expects a very specific format for the dataset. The dataset should contain two 4 entries at least
|
| 44 |
+
if you don't use the default `RewardDataCollatorWithPadding` data collator. The entries should be named
|
| 45 |
+
- `input_ids_chosen`
|
| 46 |
+
- `attention_mask_chosen`
|
| 47 |
+
- `input_ids_rejected`
|
| 48 |
+
- `attention_mask_rejected`
|
| 49 |
+
|
| 50 |
+
Optionally, you can also pass a `margin` entry to the dataset. This entry should contain the margin used to modulate the
|
| 51 |
+
loss of the reward model as outlined in https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/.
|
| 52 |
+
If you don't pass a margin, no margin will be used.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
def __init__(
|
| 56 |
+
self,
|
| 57 |
+
model: Union[PreTrainedModel, nn.Module] = None,
|
| 58 |
+
args: Optional[RewardConfig] = None,
|
| 59 |
+
data_collator: Optional[DataCollator] = None,
|
| 60 |
+
train_dataset: Optional[Dataset] = None,
|
| 61 |
+
eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None,
|
| 62 |
+
tokenizer: Optional[PreTrainedTokenizerBase] = None,
|
| 63 |
+
model_init: Optional[Callable[[], PreTrainedModel]] = None,
|
| 64 |
+
compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None,
|
| 65 |
+
callbacks: Optional[List[TrainerCallback]] = None,
|
| 66 |
+
optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (
|
| 67 |
+
None,
|
| 68 |
+
None,
|
| 69 |
+
),
|
| 70 |
+
preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
|
| 71 |
+
max_length: Optional[int] = None,
|
| 72 |
+
peft_config: Optional[Dict] = None,
|
| 73 |
+
):
|
| 74 |
+
"""
|
| 75 |
+
Initialize RewardTrainer.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
model (`transformers.PreTrainedModel`):
|
| 79 |
+
The model to train, preferably an `AutoModelForSequenceClassification`.
|
| 80 |
+
args (`RewardConfig`):
|
| 81 |
+
The arguments to use for training.
|
| 82 |
+
data_collator (`transformers.DataCollator`):
|
| 83 |
+
The data collator to use for training. If None is specified, the default data collator (`RewardDataCollatorWithPadding`) will be used
|
| 84 |
+
which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences.
|
| 85 |
+
train_dataset (`datasets.Dataset`):
|
| 86 |
+
The dataset to use for training.
|
| 87 |
+
eval_dataset (`datasets.Dataset`):
|
| 88 |
+
The dataset to use for evaluation.
|
| 89 |
+
tokenizer (`transformers.PreTrainedTokenizerBase`):
|
| 90 |
+
The tokenizer to use for training. This argument is required if you want to use the default data collator.
|
| 91 |
+
model_init (`Callable[[], transformers.PreTrainedModel]`):
|
| 92 |
+
The model initializer to use for training. If None is specified, the default model initializer will be used.
|
| 93 |
+
compute_metrics (`Callable[[transformers.EvalPrediction], Dict]`, *optional* defaults to `compute_accuracy`):
|
| 94 |
+
The metrics to use for evaluation. If no metrics are specified, the default metric (`compute_accuracy`) will be used.
|
| 95 |
+
callbacks (`List[transformers.TrainerCallback]`):
|
| 96 |
+
The callbacks to use for training.
|
| 97 |
+
optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
|
| 98 |
+
The optimizer and scheduler to use for training.
|
| 99 |
+
preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
|
| 100 |
+
The function to use to preprocess the logits before computing the metrics.
|
| 101 |
+
max_length (`int`, defaults to `None`):
|
| 102 |
+
The maximum length of the sequences in the batch. This argument is required if you want to use the default data collator.
|
| 103 |
+
peft_config (`Dict`, defaults to `None`):
|
| 104 |
+
The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model.
|
| 105 |
+
"""
|
| 106 |
+
if type(args) == TrainingArguments:
|
| 107 |
+
warnings.warn(
|
| 108 |
+
"Using `transformers.TrainingArguments` for `args` is deprecated and will be removed in a future version. Please use `RewardConfig` instead.",
|
| 109 |
+
FutureWarning,
|
| 110 |
+
)
|
| 111 |
+
if max_length is not None:
|
| 112 |
+
warnings.warn(
|
| 113 |
+
"The `max_length` argument is deprecated and will be removed in a future version. Please use the `RewardConfig` to set `max_length` instead.",
|
| 114 |
+
FutureWarning,
|
| 115 |
+
)
|
| 116 |
+
else:
|
| 117 |
+
if max_length is not None and args.max_length is not None:
|
| 118 |
+
raise ValueError(
|
| 119 |
+
"You cannot specify both `max_length` and `args.max_length`. Please use the `RewardConfig` to set `max_length` once."
|
| 120 |
+
)
|
| 121 |
+
if max_length is not None and args.max_length is None:
|
| 122 |
+
warnings.warn(
|
| 123 |
+
"The `max_length` argument is deprecated and will be removed in a future version. Please use the `RewardConfig` to set `max_length` instead.",
|
| 124 |
+
FutureWarning,
|
| 125 |
+
)
|
| 126 |
+
if not is_peft_available() and peft_config is not None:
|
| 127 |
+
raise ValueError(
|
| 128 |
+
"PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models"
|
| 129 |
+
)
|
| 130 |
+
elif is_peft_available() and peft_config is not None:
|
| 131 |
+
if not isinstance(model, PeftModel):
|
| 132 |
+
if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_quantized", False):
|
| 133 |
+
_supports_gc_kwargs = "gradient_checkpointing_kwargs" in list(
|
| 134 |
+
inspect.signature(prepare_model_for_kbit_training).parameters
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
preprare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing}
|
| 138 |
+
|
| 139 |
+
if not _supports_gc_kwargs and args.gradient_checkpointing_kwargs is not None:
|
| 140 |
+
warnings.warn(
|
| 141 |
+
"You passed `gradient_checkpointing_kwargs` in the trainer's kwargs, but your peft version does not support it. "
|
| 142 |
+
"please update to the latest version of peft to use `gradient_checkpointing_kwargs`."
|
| 143 |
+
)
|
| 144 |
+
elif _supports_gc_kwargs and args.gradient_checkpointing_kwargs is not None:
|
| 145 |
+
preprare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs
|
| 146 |
+
|
| 147 |
+
model = prepare_model_for_kbit_training(model, **preprare_model_kwargs)
|
| 148 |
+
|
| 149 |
+
model = get_peft_model(model, peft_config)
|
| 150 |
+
|
| 151 |
+
if compute_metrics is None:
|
| 152 |
+
compute_metrics = compute_accuracy
|
| 153 |
+
|
| 154 |
+
if data_collator is None:
|
| 155 |
+
if tokenizer is None:
|
| 156 |
+
raise ValueError(
|
| 157 |
+
"max_length or a tokenizer must be specified when using the default RewardDataCollatorWithPadding"
|
| 158 |
+
)
|
| 159 |
+
if type(args) == TrainingArguments:
|
| 160 |
+
if max_length is None:
|
| 161 |
+
warnings.warn(
|
| 162 |
+
"When using RewardDataCollatorWithPadding, you should set `max_length` in RewardConfig."
|
| 163 |
+
" It will be set to `512` by default, but you should do it yourself in the future.",
|
| 164 |
+
UserWarning,
|
| 165 |
+
)
|
| 166 |
+
max_length = 512
|
| 167 |
+
else:
|
| 168 |
+
if max_length is None and args.max_length is None:
|
| 169 |
+
warnings.warn(
|
| 170 |
+
"When using RewardDataCollatorWithPadding, you should set `max_length` in RewardConfig."
|
| 171 |
+
" It will be set to `512` by default, but you should do it yourself in the future.",
|
| 172 |
+
UserWarning,
|
| 173 |
+
)
|
| 174 |
+
max_length = 512
|
| 175 |
+
if max_length is None and args.max_length is not None:
|
| 176 |
+
max_length = args.max_length
|
| 177 |
+
|
| 178 |
+
data_collator = RewardDataCollatorWithPadding(tokenizer, max_length=max_length)
|
| 179 |
+
|
| 180 |
+
if args.remove_unused_columns:
|
| 181 |
+
try: # for bc before https://github.com/huggingface/transformers/pull/25435
|
| 182 |
+
args.remove_unused_columns = False
|
| 183 |
+
except FrozenInstanceError:
|
| 184 |
+
args = replace(args, remove_unused_columns=False)
|
| 185 |
+
# warn users
|
| 186 |
+
warnings.warn(
|
| 187 |
+
"When using RewardDataCollatorWithPadding, you should set `remove_unused_columns=False` in your RewardConfig"
|
| 188 |
+
" we have set it for you, but you should do it yourself in the future.",
|
| 189 |
+
UserWarning,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
self.use_reward_data_collator = True
|
| 193 |
+
else:
|
| 194 |
+
self.use_reward_data_collator = False
|
| 195 |
+
super().__init__(
|
| 196 |
+
model,
|
| 197 |
+
args,
|
| 198 |
+
data_collator,
|
| 199 |
+
train_dataset,
|
| 200 |
+
eval_dataset,
|
| 201 |
+
tokenizer,
|
| 202 |
+
model_init,
|
| 203 |
+
compute_metrics,
|
| 204 |
+
callbacks,
|
| 205 |
+
optimizers,
|
| 206 |
+
preprocess_logits_for_metrics,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
def compute_loss(
|
| 210 |
+
self,
|
| 211 |
+
model: Union[PreTrainedModel, nn.Module],
|
| 212 |
+
inputs: Dict[str, Union[torch.Tensor, Any]],
|
| 213 |
+
return_outputs=False,
|
| 214 |
+
) -> Union[torch.Tensor, Tuple[torch.Tensor, Dict[str, torch.Tensor]]]:
|
| 215 |
+
if not self.use_reward_data_collator:
|
| 216 |
+
warnings.warn(
|
| 217 |
+
"The current compute_loss is implemented for RewardDataCollatorWithPadding,"
|
| 218 |
+
" if you are using a custom data collator make sure you know what you are doing or"
|
| 219 |
+
" implement your own compute_loss method."
|
| 220 |
+
)
|
| 221 |
+
rewards_chosen = model(
|
| 222 |
+
input_ids=inputs["input_ids_chosen"],
|
| 223 |
+
attention_mask=inputs["attention_mask_chosen"],
|
| 224 |
+
return_dict=True,
|
| 225 |
+
)["logits"]
|
| 226 |
+
rewards_rejected = model(
|
| 227 |
+
input_ids=inputs["input_ids_rejected"],
|
| 228 |
+
attention_mask=inputs["attention_mask_rejected"],
|
| 229 |
+
return_dict=True,
|
| 230 |
+
)["logits"]
|
| 231 |
+
# calculate loss, optionally modulate with margin
|
| 232 |
+
if "margin" in inputs:
|
| 233 |
+
loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected - inputs["margin"]).mean()
|
| 234 |
+
else:
|
| 235 |
+
loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected).mean()
|
| 236 |
+
|
| 237 |
+
if return_outputs:
|
| 238 |
+
return loss, {
|
| 239 |
+
"rewards_chosen": rewards_chosen,
|
| 240 |
+
"rewards_rejected": rewards_rejected,
|
| 241 |
+
}
|
| 242 |
+
return loss
|
| 243 |
+
|
| 244 |
+
def prediction_step(
|
| 245 |
+
self,
|
| 246 |
+
model: Union[PreTrainedModel, nn.Module],
|
| 247 |
+
inputs: Dict[str, Union[torch.Tensor, Any]],
|
| 248 |
+
prediction_loss_only: bool,
|
| 249 |
+
ignore_keys: Optional[List[str]] = None,
|
| 250 |
+
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]:
|
| 251 |
+
inputs = self._prepare_inputs(inputs)
|
| 252 |
+
if ignore_keys is None:
|
| 253 |
+
if hasattr(self.model, "config"):
|
| 254 |
+
ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", [])
|
| 255 |
+
else:
|
| 256 |
+
ignore_keys = []
|
| 257 |
+
|
| 258 |
+
with torch.no_grad():
|
| 259 |
+
loss, logits_dict = self.compute_loss(model, inputs, return_outputs=True)
|
| 260 |
+
|
| 261 |
+
if prediction_loss_only:
|
| 262 |
+
return (loss, None, None)
|
| 263 |
+
|
| 264 |
+
loss = loss.detach()
|
| 265 |
+
logits = tuple(v for k, v in logits_dict.items() if k not in ignore_keys)
|
| 266 |
+
logits = nested_detach(logits)
|
| 267 |
+
# Stack accepted against rejected, mean over logits
|
| 268 |
+
# and softmax to get preferences between accepted and rejected to sum to 1
|
| 269 |
+
logits = torch.stack(logits).mean(dim=2).softmax(dim=0).T
|
| 270 |
+
|
| 271 |
+
labels = torch.zeros(logits.shape[0])
|
| 272 |
+
labels = self._prepare_inputs(labels)
|
| 273 |
+
|
| 274 |
+
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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 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 |
+
if is_peft_available():
|
| 51 |
+
from peft import PeftConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class SFTTrainer(Trainer):
|
| 55 |
+
r"""
|
| 56 |
+
Class definition of the Supervised Finetuning Trainer (SFT Trainer).
|
| 57 |
+
This class is a wrapper around the `transformers.Trainer` class and inherits all of its attributes and methods.
|
| 58 |
+
The trainer takes care of properly initializing the PeftModel in case a user passes a `PeftConfig` object.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
model (Union[`transformers.PreTrainedModel`, `nn.Module`, `str`]):
|
| 62 |
+
The model to train, can be a `PreTrainedModel`, a `torch.nn.Module` or a string with the model name to
|
| 63 |
+
load from cache or download. The model can be also converted to a `PeftModel` if a `PeftConfig` object is
|
| 64 |
+
passed to the `peft_config` argument.
|
| 65 |
+
args (Optional[`transformers.TrainingArguments`]):
|
| 66 |
+
The arguments to tweak for training. Please refer to the official documentation of `transformers.TrainingArguments`
|
| 67 |
+
for more information.
|
| 68 |
+
data_collator (Optional[`transformers.DataCollator`]):
|
| 69 |
+
The data collator to use for training.
|
| 70 |
+
train_dataset (Optional[`datasets.Dataset`]):
|
| 71 |
+
The dataset to use for training. We recommend users to use `trl.trainer.ConstantLengthDataset` to create their dataset.
|
| 72 |
+
eval_dataset (Optional[Union[`datasets.Dataset`, Dict[`str`, `datasets.Dataset`]]]):
|
| 73 |
+
The dataset to use for evaluation. We recommend users to use `trl.trainer.ConstantLengthDataset` to create their dataset.
|
| 74 |
+
tokenizer (Optional[`transformers.PreTrainedTokenizer`]):
|
| 75 |
+
The tokenizer to use for training. If not specified, the tokenizer associated to the model will be used.
|
| 76 |
+
model_init (`Callable[[], transformers.PreTrainedModel]`):
|
| 77 |
+
The model initializer to use for training. If None is specified, the default model initializer will be used.
|
| 78 |
+
compute_metrics (`Callable[[transformers.EvalPrediction], Dict]`, *optional* defaults to None):
|
| 79 |
+
The function used to compute metrics during evaluation. It should return a dictionary mapping metric names to metric values.
|
| 80 |
+
If not specified, only the loss will be computed during evaluation.
|
| 81 |
+
callbacks (`List[transformers.TrainerCallback]`):
|
| 82 |
+
The callbacks to use for training.
|
| 83 |
+
optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
|
| 84 |
+
The optimizer and scheduler to use for training.
|
| 85 |
+
preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
|
| 86 |
+
The function to use to preprocess the logits before computing the metrics.
|
| 87 |
+
peft_config (`Optional[PeftConfig]`):
|
| 88 |
+
The PeftConfig object to use to initialize the PeftModel.
|
| 89 |
+
dataset_text_field (`Optional[str]`):
|
| 90 |
+
The name of the text field of the dataset, in case this is passed by a user, the trainer will automatically create a
|
| 91 |
+
`ConstantLengthDataset` based on the `dataset_text_field` argument.
|
| 92 |
+
formatting_func (`Optional[Callable]`):
|
| 93 |
+
The formatting function to be used for creating the `ConstantLengthDataset`.
|
| 94 |
+
max_seq_length (`Optional[int]`):
|
| 95 |
+
The maximum sequence length to use for the `ConstantLengthDataset` and for automatically creating the Dataset. Defaults to `512`.
|
| 96 |
+
infinite (`Optional[bool]`):
|
| 97 |
+
Whether to use an infinite dataset or not. Defaults to `False`.
|
| 98 |
+
num_of_sequences (`Optional[int]`):
|
| 99 |
+
The number of sequences to use for the `ConstantLengthDataset`. Defaults to `1024`.
|
| 100 |
+
chars_per_token (`Optional[float]`):
|
| 101 |
+
The number of characters per token to use for the `ConstantLengthDataset`. Defaults to `3.6`. You can check how this is computed in the
|
| 102 |
+
stack-llama example: https://github.com/huggingface/trl/blob/08f550674c553c36c51d1027613c29f14f3676a5/examples/stack_llama/scripts/supervised_finetuning.py#L53.
|
| 103 |
+
packing (`Optional[bool]`):
|
| 104 |
+
Used only in case `dataset_text_field` is passed. This argument is used by the `ConstantLengthDataset` to pack the sequences
|
| 105 |
+
of the dataset.
|
| 106 |
+
dataset_num_proc (`Optional[int]`):
|
| 107 |
+
The number of workers to use to tokenize the data. Only used when `packing=False`. Defaults to None.
|
| 108 |
+
dataset_batch_size (`int`):
|
| 109 |
+
The number of examples to tokenize per batch. If batch_size <= 0 or batch_size == None,
|
| 110 |
+
tokenize the full dataset as a single batch. Defaults to 1000.
|
| 111 |
+
neftune_noise_alpha (`Optional[float]`):
|
| 112 |
+
If not `None`, this will activate NEFTune noise embeddings. This has been proven to drastically improve model performances for instruction
|
| 113 |
+
fine-tuning. Check out the original paper here: https://arxiv.org/abs/2310.05914 and the original code here: https://github.com/neelsjain/NEFTune
|
| 114 |
+
model_init_kwargs: (`Optional[Dict]`, *optional*):
|
| 115 |
+
Dict of Optional kwargs to pass when instantiating the model from a string
|
| 116 |
+
dataset_kwargs: (`Optional[Dict]`, *optional*):
|
| 117 |
+
Dict of Optional kwargs to pass when creating packed or non-packed datasets
|
| 118 |
+
"""
|
| 119 |
+
_tag_names = ["trl", "sft"]
|
| 120 |
+
|
| 121 |
+
def __init__(
|
| 122 |
+
self,
|
| 123 |
+
model: Union[PreTrainedModel, nn.Module, str] = None,
|
| 124 |
+
args: TrainingArguments = None,
|
| 125 |
+
data_collator: Optional[DataCollator] = None,
|
| 126 |
+
train_dataset: Optional[Dataset] = None,
|
| 127 |
+
eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None,
|
| 128 |
+
tokenizer: Optional[PreTrainedTokenizerBase] = None,
|
| 129 |
+
model_init: Optional[Callable[[], PreTrainedModel]] = None,
|
| 130 |
+
compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None,
|
| 131 |
+
callbacks: Optional[List[TrainerCallback]] = None,
|
| 132 |
+
optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
|
| 133 |
+
preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
|
| 134 |
+
peft_config: Optional["PeftConfig"] = None,
|
| 135 |
+
dataset_text_field: Optional[str] = None,
|
| 136 |
+
packing: Optional[bool] = False,
|
| 137 |
+
formatting_func: Optional[Callable] = None,
|
| 138 |
+
max_seq_length: Optional[int] = None,
|
| 139 |
+
infinite: Optional[bool] = None,
|
| 140 |
+
num_of_sequences: Optional[int] = 1024,
|
| 141 |
+
chars_per_token: Optional[float] = 3.6,
|
| 142 |
+
dataset_num_proc: Optional[int] = None,
|
| 143 |
+
dataset_batch_size: int = 1000,
|
| 144 |
+
neftune_noise_alpha: Optional[float] = None,
|
| 145 |
+
model_init_kwargs: Optional[Dict] = None,
|
| 146 |
+
dataset_kwargs: Optional[Dict] = None,
|
| 147 |
+
):
|
| 148 |
+
if model_init_kwargs is None:
|
| 149 |
+
model_init_kwargs = {}
|
| 150 |
+
elif not isinstance(model, str):
|
| 151 |
+
raise ValueError("You passed model_kwargs to the SFTTrainer. But your model is already instantiated.")
|
| 152 |
+
|
| 153 |
+
if infinite is not None:
|
| 154 |
+
warnings.warn(
|
| 155 |
+
"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."
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
if isinstance(model, str):
|
| 159 |
+
warnings.warn(
|
| 160 |
+
"You passed a model_id to the SFTTrainer. This will automatically create an "
|
| 161 |
+
"`AutoModelForCausalLM` or a `PeftModel` (if you passed a `peft_config`) for you."
|
| 162 |
+
)
|
| 163 |
+
model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs)
|
| 164 |
+
|
| 165 |
+
if packing and data_collator is not None and isinstance(data_collator, DataCollatorForCompletionOnlyLM):
|
| 166 |
+
raise ValueError(
|
| 167 |
+
"You passed a `DataCollatorForCompletionOnlyLM` to the SFTTrainer. This is not compatible with the `packing` argument."
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
if is_peft_available() and peft_config is not None:
|
| 171 |
+
if not isinstance(peft_config, PeftConfig):
|
| 172 |
+
raise ValueError(
|
| 173 |
+
"If you want to use the PeftModel, you need to pass a PeftConfig object to the SFTTrainer."
|
| 174 |
+
f" and you passed a {type(peft_config)}."
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
if not isinstance(model, PeftModel):
|
| 178 |
+
_support_gc_kwargs = hasattr(
|
| 179 |
+
args, "gradient_checkpointing_kwargs"
|
| 180 |
+
) and "gradient_checkpointing_kwargs" in list(
|
| 181 |
+
inspect.signature(prepare_model_for_kbit_training).parameters
|
| 182 |
+
)
|
| 183 |
+
gradient_checkpointing_kwargs = getattr(args, "gradient_checkpointing_kwargs", None) or {}
|
| 184 |
+
if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False):
|
| 185 |
+
preprare_model_kwargs = {
|
| 186 |
+
"use_gradient_checkpointing": getattr(args, "gradient_checkpointing", False)
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
if _support_gc_kwargs:
|
| 190 |
+
preprare_model_kwargs["gradient_checkpointing_kwargs"] = gradient_checkpointing_kwargs
|
| 191 |
+
|
| 192 |
+
model = prepare_model_for_kbit_training(model, **preprare_model_kwargs)
|
| 193 |
+
|
| 194 |
+
if args is not None:
|
| 195 |
+
args = dataclasses.replace(args, gradient_checkpointing=False)
|
| 196 |
+
elif getattr(args, "gradient_checkpointing", False) and (
|
| 197 |
+
"use_reentrant" not in gradient_checkpointing_kwargs
|
| 198 |
+
or gradient_checkpointing_kwargs["use_reentrant"]
|
| 199 |
+
):
|
| 200 |
+
# For backward compatibility with older versions of transformers
|
| 201 |
+
if hasattr(model, "enable_input_require_grads"):
|
| 202 |
+
model.enable_input_require_grads()
|
| 203 |
+
else:
|
| 204 |
+
|
| 205 |
+
def make_inputs_require_grad(module, input, output):
|
| 206 |
+
output.requires_grad_(True)
|
| 207 |
+
|
| 208 |
+
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
| 209 |
+
|
| 210 |
+
model = get_peft_model(model, peft_config)
|
| 211 |
+
if args.bf16 and getattr(model, "is_loaded_in_4bit", False):
|
| 212 |
+
peft_module_casting_to_bf16(model)
|
| 213 |
+
|
| 214 |
+
if tokenizer is None:
|
| 215 |
+
tokenizer = AutoTokenizer.from_pretrained(model.config._name_or_path)
|
| 216 |
+
if getattr(tokenizer, "pad_token", None) is None:
|
| 217 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 218 |
+
|
| 219 |
+
if max_seq_length is None:
|
| 220 |
+
# to overcome some issues with broken tokenizers
|
| 221 |
+
max_seq_length = min(tokenizer.model_max_length, 1024)
|
| 222 |
+
|
| 223 |
+
warnings.warn(
|
| 224 |
+
f"You didn't pass a `max_seq_length` argument to the SFTTrainer, this will default to {max_seq_length}"
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
self.dataset_num_proc = dataset_num_proc
|
| 228 |
+
self.dataset_batch_size = dataset_batch_size
|
| 229 |
+
|
| 230 |
+
self._trainer_supports_neftune = hasattr(args, "neftune_noise_alpha")
|
| 231 |
+
|
| 232 |
+
if neftune_noise_alpha is not None and self._trainer_supports_neftune:
|
| 233 |
+
args.neftune_noise_alpha = neftune_noise_alpha
|
| 234 |
+
warnings.warn(
|
| 235 |
+
"You passed a `neftune_noise_alpha` argument to the SFTTrainer, the value you passed will override the one in the `TrainingArguments`."
|
| 236 |
+
)
|
| 237 |
+
# self.neftune_noise_alpha is done at Trainer level
|
| 238 |
+
elif not self._trainer_supports_neftune:
|
| 239 |
+
self.neftune_noise_alpha = neftune_noise_alpha
|
| 240 |
+
|
| 241 |
+
if formatting_func is None and dataset_text_field is None:
|
| 242 |
+
# check if dataset has ChatML format or instruction format and is supported
|
| 243 |
+
# if not stays #None
|
| 244 |
+
formatting_func = get_formatting_func_from_dataset(train_dataset, tokenizer)
|
| 245 |
+
|
| 246 |
+
if not packing:
|
| 247 |
+
if dataset_text_field is None and formatting_func is None:
|
| 248 |
+
raise ValueError(
|
| 249 |
+
"You passed `packing=False` to the SFTTrainer, but you didn't pass a `dataset_text_field` or `formatting_func` argument."
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
if data_collator is None:
|
| 253 |
+
data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
|
| 254 |
+
|
| 255 |
+
# Pre-process the datasets only once per node. The remaining processes will use the cache.
|
| 256 |
+
with PartialState().local_main_process_first():
|
| 257 |
+
if dataset_kwargs is None:
|
| 258 |
+
dataset_kwargs = {}
|
| 259 |
+
if train_dataset is not None:
|
| 260 |
+
train_dataset = self._prepare_dataset(
|
| 261 |
+
train_dataset,
|
| 262 |
+
tokenizer,
|
| 263 |
+
packing,
|
| 264 |
+
dataset_text_field,
|
| 265 |
+
max_seq_length,
|
| 266 |
+
formatting_func,
|
| 267 |
+
num_of_sequences,
|
| 268 |
+
chars_per_token,
|
| 269 |
+
remove_unused_columns=args.remove_unused_columns if args is not None else True,
|
| 270 |
+
**dataset_kwargs,
|
| 271 |
+
)
|
| 272 |
+
if eval_dataset is not None:
|
| 273 |
+
_multiple = isinstance(eval_dataset, dict)
|
| 274 |
+
_eval_datasets = eval_dataset if _multiple else {"singleton": eval_dataset}
|
| 275 |
+
for _eval_dataset_name, _eval_dataset in _eval_datasets.items():
|
| 276 |
+
_eval_datasets[_eval_dataset_name] = self._prepare_dataset(
|
| 277 |
+
_eval_dataset,
|
| 278 |
+
tokenizer,
|
| 279 |
+
packing,
|
| 280 |
+
dataset_text_field,
|
| 281 |
+
max_seq_length,
|
| 282 |
+
formatting_func,
|
| 283 |
+
num_of_sequences,
|
| 284 |
+
chars_per_token,
|
| 285 |
+
remove_unused_columns=args.remove_unused_columns if args is not None else True,
|
| 286 |
+
**dataset_kwargs,
|
| 287 |
+
)
|
| 288 |
+
if not _multiple:
|
| 289 |
+
eval_dataset = _eval_datasets["singleton"]
|
| 290 |
+
|
| 291 |
+
if tokenizer.padding_side is not None and tokenizer.padding_side != "right":
|
| 292 |
+
warnings.warn(
|
| 293 |
+
"You passed a tokenizer with `padding_side` not equal to `right` to the SFTTrainer. This might lead to some unexpected behaviour due to "
|
| 294 |
+
"overflow issues when training a model in half-precision. You might consider adding `tokenizer.padding_side = 'right'` to your code."
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
super().__init__(
|
| 298 |
+
model=model,
|
| 299 |
+
args=args,
|
| 300 |
+
data_collator=data_collator,
|
| 301 |
+
train_dataset=train_dataset,
|
| 302 |
+
eval_dataset=eval_dataset,
|
| 303 |
+
tokenizer=tokenizer,
|
| 304 |
+
model_init=model_init,
|
| 305 |
+
compute_metrics=compute_metrics,
|
| 306 |
+
callbacks=callbacks,
|
| 307 |
+
optimizers=optimizers,
|
| 308 |
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
if self.args.max_steps > 0 and packing:
|
| 312 |
+
warnings.warn(
|
| 313 |
+
"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."
|
| 314 |
+
)
|
| 315 |
+
self.train_dataset.infinite = True
|
| 316 |
+
elif self.args.max_steps == -1 and packing:
|
| 317 |
+
self.train_dataset.infinite = False
|
| 318 |
+
|
| 319 |
+
@wraps(Trainer.train)
|
| 320 |
+
def train(self, *args, **kwargs):
|
| 321 |
+
# Activate neftune right before training.
|
| 322 |
+
if self.neftune_noise_alpha is not None and not self._trainer_supports_neftune:
|
| 323 |
+
self.model = self._trl_activate_neftune(self.model)
|
| 324 |
+
|
| 325 |
+
output = super().train(*args, **kwargs)
|
| 326 |
+
|
| 327 |
+
# After training we make sure to retrieve back the original forward pass method
|
| 328 |
+
# for the embedding layer by removing the forward post hook.
|
| 329 |
+
if self.neftune_noise_alpha is not None and not self._trainer_supports_neftune:
|
| 330 |
+
unwrapped_model = unwrap_model(self.model)
|
| 331 |
+
if is_peft_available() and isinstance(unwrapped_model, PeftModel):
|
| 332 |
+
embeddings = unwrapped_model.base_model.model.get_input_embeddings()
|
| 333 |
+
else:
|
| 334 |
+
embeddings = unwrapped_model.get_input_embeddings()
|
| 335 |
+
|
| 336 |
+
self.neftune_hook_handle.remove()
|
| 337 |
+
del embeddings.neftune_noise_alpha
|
| 338 |
+
|
| 339 |
+
return output
|
| 340 |
+
|
| 341 |
+
@wraps(Trainer.push_to_hub)
|
| 342 |
+
def push_to_hub(self, commit_message: Optional[str] = "End of training", blocking: bool = True, **kwargs) -> str:
|
| 343 |
+
"""
|
| 344 |
+
Overwrite the `push_to_hub` method in order to force-add the tag "sft" when pushing the
|
| 345 |
+
model on the Hub. Please refer to `~transformers.Trainer.push_to_hub` for more details.
|
| 346 |
+
"""
|
| 347 |
+
kwargs = trl_sanitze_kwargs_for_tagging(model=self.model, tag_names=self._tag_names, kwargs=kwargs)
|
| 348 |
+
|
| 349 |
+
return super().push_to_hub(commit_message=commit_message, blocking=blocking, **kwargs)
|
| 350 |
+
|
| 351 |
+
def _prepare_dataset(
|
| 352 |
+
self,
|
| 353 |
+
dataset,
|
| 354 |
+
tokenizer,
|
| 355 |
+
packing,
|
| 356 |
+
dataset_text_field,
|
| 357 |
+
max_seq_length,
|
| 358 |
+
formatting_func,
|
| 359 |
+
num_of_sequences,
|
| 360 |
+
chars_per_token,
|
| 361 |
+
remove_unused_columns=True,
|
| 362 |
+
append_concat_token=True,
|
| 363 |
+
add_special_tokens=True,
|
| 364 |
+
):
|
| 365 |
+
if dataset is None:
|
| 366 |
+
raise ValueError("The dataset should not be None")
|
| 367 |
+
|
| 368 |
+
# check if torch dataset / dataloader and do nothing
|
| 369 |
+
if isinstance(dataset, (torch.utils.data.IterableDataset, torch.utils.data.Dataset, ConstantLengthDataset)):
|
| 370 |
+
return dataset
|
| 371 |
+
|
| 372 |
+
if not packing:
|
| 373 |
+
return self._prepare_non_packed_dataloader(
|
| 374 |
+
tokenizer,
|
| 375 |
+
dataset,
|
| 376 |
+
dataset_text_field,
|
| 377 |
+
max_seq_length,
|
| 378 |
+
formatting_func,
|
| 379 |
+
add_special_tokens,
|
| 380 |
+
remove_unused_columns,
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
else:
|
| 384 |
+
return self._prepare_packed_dataloader(
|
| 385 |
+
tokenizer,
|
| 386 |
+
dataset,
|
| 387 |
+
dataset_text_field,
|
| 388 |
+
max_seq_length,
|
| 389 |
+
num_of_sequences,
|
| 390 |
+
chars_per_token,
|
| 391 |
+
formatting_func,
|
| 392 |
+
append_concat_token,
|
| 393 |
+
add_special_tokens,
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
def _prepare_non_packed_dataloader(
|
| 397 |
+
self,
|
| 398 |
+
tokenizer,
|
| 399 |
+
dataset,
|
| 400 |
+
dataset_text_field,
|
| 401 |
+
max_seq_length,
|
| 402 |
+
formatting_func=None,
|
| 403 |
+
add_special_tokens=True,
|
| 404 |
+
remove_unused_columns=True,
|
| 405 |
+
):
|
| 406 |
+
use_formatting_func = formatting_func is not None and dataset_text_field is None
|
| 407 |
+
self._dataset_sanity_checked = False
|
| 408 |
+
|
| 409 |
+
# Inspired from: https://huggingface.co/learn/nlp-course/chapter7/6?fw=pt
|
| 410 |
+
def tokenize(element):
|
| 411 |
+
outputs = tokenizer(
|
| 412 |
+
element[dataset_text_field] if not use_formatting_func else formatting_func(element),
|
| 413 |
+
add_special_tokens=add_special_tokens,
|
| 414 |
+
truncation=True,
|
| 415 |
+
padding=False,
|
| 416 |
+
max_length=max_seq_length,
|
| 417 |
+
return_overflowing_tokens=False,
|
| 418 |
+
return_length=False,
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
if use_formatting_func and not self._dataset_sanity_checked:
|
| 422 |
+
if not isinstance(formatting_func(element), list):
|
| 423 |
+
raise ValueError(
|
| 424 |
+
"The `formatting_func` should return a list of processed strings since it can lead to silent bugs."
|
| 425 |
+
)
|
| 426 |
+
else:
|
| 427 |
+
self._dataset_sanity_checked = True
|
| 428 |
+
|
| 429 |
+
return {"input_ids": outputs["input_ids"], "attention_mask": outputs["attention_mask"]}
|
| 430 |
+
|
| 431 |
+
signature_columns = ["input_ids", "labels", "attention_mask"]
|
| 432 |
+
|
| 433 |
+
extra_columns = list(set(dataset.column_names) - set(signature_columns))
|
| 434 |
+
|
| 435 |
+
if not remove_unused_columns and len(extra_columns) > 0:
|
| 436 |
+
warnings.warn(
|
| 437 |
+
"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 "
|
| 438 |
+
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."
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
tokenized_dataset = dataset.map(
|
| 442 |
+
tokenize,
|
| 443 |
+
batched=True,
|
| 444 |
+
remove_columns=dataset.column_names if remove_unused_columns else None,
|
| 445 |
+
num_proc=self.dataset_num_proc,
|
| 446 |
+
batch_size=self.dataset_batch_size,
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
return tokenized_dataset
|
| 450 |
+
|
| 451 |
+
def _prepare_packed_dataloader(
|
| 452 |
+
self,
|
| 453 |
+
tokenizer,
|
| 454 |
+
dataset,
|
| 455 |
+
dataset_text_field,
|
| 456 |
+
max_seq_length,
|
| 457 |
+
num_of_sequences,
|
| 458 |
+
chars_per_token,
|
| 459 |
+
formatting_func=None,
|
| 460 |
+
append_concat_token=True,
|
| 461 |
+
add_special_tokens=True,
|
| 462 |
+
):
|
| 463 |
+
if dataset_text_field is not None or formatting_func is not None:
|
| 464 |
+
if tokenizer is None:
|
| 465 |
+
raise ValueError("You need to pass a tokenizer when using `dataset_text_field` with `SFTTrainer`.")
|
| 466 |
+
|
| 467 |
+
constant_length_iterator = ConstantLengthDataset(
|
| 468 |
+
tokenizer,
|
| 469 |
+
dataset,
|
| 470 |
+
dataset_text_field=dataset_text_field,
|
| 471 |
+
formatting_func=formatting_func,
|
| 472 |
+
seq_length=max_seq_length,
|
| 473 |
+
infinite=False,
|
| 474 |
+
num_of_sequences=num_of_sequences,
|
| 475 |
+
chars_per_token=chars_per_token,
|
| 476 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 477 |
+
append_concat_token=append_concat_token,
|
| 478 |
+
add_special_tokens=add_special_tokens,
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
def data_generator(constant_length_iterator):
|
| 482 |
+
yield from constant_length_iterator
|
| 483 |
+
|
| 484 |
+
try:
|
| 485 |
+
packed_dataset = Dataset.from_generator(
|
| 486 |
+
data_generator, gen_kwargs={"constant_length_iterator": constant_length_iterator}
|
| 487 |
+
)
|
| 488 |
+
except (DatasetGenerationError, SchemaInferenceError):
|
| 489 |
+
raise ValueError(
|
| 490 |
+
"Error occurred while packing the dataset. Make sure that your dataset has enough samples to at least yield one packed sequence."
|
| 491 |
+
)
|
| 492 |
+
return packed_dataset
|
| 493 |
+
else:
|
| 494 |
+
raise ValueError(
|
| 495 |
+
"You need to pass a `dataset_text_field` or `formatting_func` argument to the SFTTrainer if you want to use the `ConstantLengthDataset`."
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
def _trl_activate_neftune(self, model):
|
| 499 |
+
r"""
|
| 500 |
+
Activates the neftune as presented in this code: https://github.com/neelsjain/NEFTune and paper: https://arxiv.org/abs/2310.05914
|
| 501 |
+
Since in transformers Trainer we do have an `_activate_neftune` method, we need to rename this method to avoid conflicts.
|
| 502 |
+
"""
|
| 503 |
+
unwrapped_model = unwrap_model(model)
|
| 504 |
+
if is_peft_available() and isinstance(unwrapped_model, PeftModel):
|
| 505 |
+
embeddings = unwrapped_model.base_model.model.get_input_embeddings()
|
| 506 |
+
else:
|
| 507 |
+
embeddings = unwrapped_model.get_input_embeddings()
|
| 508 |
+
|
| 509 |
+
embeddings.neftune_noise_alpha = self.neftune_noise_alpha
|
| 510 |
+
hook_handle = embeddings.register_forward_hook(neftune_post_forward_hook)
|
| 511 |
+
self.neftune_hook_handle = hook_handle
|
| 512 |
+
return model
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/trl/trainer/utils.py
ADDED
|
@@ -0,0 +1,724 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 random
|
| 15 |
+
import warnings
|
| 16 |
+
from collections import deque
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
from accelerate import PartialState
|
| 23 |
+
from torch.nn.utils.rnn import pad_sequence
|
| 24 |
+
from torch.utils.data import IterableDataset
|
| 25 |
+
from transformers import BitsAndBytesConfig, DataCollatorForLanguageModeling, PreTrainedTokenizerBase
|
| 26 |
+
|
| 27 |
+
from ..import_utils import is_peft_available, is_unsloth_available, is_xpu_available
|
| 28 |
+
from ..trainer.model_config import ModelConfig
|
| 29 |
+
|
| 30 |
+
if is_peft_available():
|
| 31 |
+
from peft import LoraConfig, PeftConfig
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class AdaptiveKLController:
|
| 35 |
+
"""
|
| 36 |
+
Adaptive KL controller described in the paper:
|
| 37 |
+
https://arxiv.org/pdf/1909.08593.pdf
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(self, init_kl_coef, target, horizon):
|
| 41 |
+
self.value = init_kl_coef
|
| 42 |
+
self.target = target
|
| 43 |
+
self.horizon = horizon
|
| 44 |
+
|
| 45 |
+
def update(self, current, n_steps):
|
| 46 |
+
target = self.target
|
| 47 |
+
proportional_error = np.clip(current / target - 1, -0.2, 0.2)
|
| 48 |
+
mult = 1 + proportional_error * n_steps / self.horizon
|
| 49 |
+
self.value *= mult
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class FixedKLController:
|
| 53 |
+
"""Fixed KL controller."""
|
| 54 |
+
|
| 55 |
+
def __init__(self, kl_coef):
|
| 56 |
+
self.value = kl_coef
|
| 57 |
+
|
| 58 |
+
def update(self, current, n_steps):
|
| 59 |
+
pass
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class DataCollatorForCompletionOnlyLM(DataCollatorForLanguageModeling):
|
| 63 |
+
"""
|
| 64 |
+
Data collator used for completion tasks. It ensures that all the tokens of the labels are set to an 'ignore_index'
|
| 65 |
+
when they do not come from the assistant. This ensure that the loss is only
|
| 66 |
+
calculated on the completion made by the assistant.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
response_template (`Union[str, List[int]]`): the template form that indicates the start of the response, typically something like
|
| 70 |
+
'### Response:\n'. It can also be passed as tokenized ids, which can be useful when using a tokenizer that encodes the response
|
| 71 |
+
differently if it does not have proper context.
|
| 72 |
+
instruction_template (`Union[str, List[int]]`): the template form that indicates the start of the human instruction, typically something like
|
| 73 |
+
'### Human:\n'. Useful for assistant-style conversation datasets. It can also be passed as tokenized ids.
|
| 74 |
+
mlm (`bool`, *optional*, defaults to `False`): Whether or not to use masked language modeling in the underlying
|
| 75 |
+
`DataCollatorForLanguageModeling` class. Note that this option currently has no effect but is present
|
| 76 |
+
for flexibility and backwards-compatibility.
|
| 77 |
+
ignore_index (`int`, *optional*, defaults to `-100`):
|
| 78 |
+
The index to use to ignore the initial tokens with
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
def __init__(
|
| 82 |
+
self,
|
| 83 |
+
response_template: Union[str, List[int]],
|
| 84 |
+
instruction_template: Union[str, List[int]] = None,
|
| 85 |
+
*args,
|
| 86 |
+
mlm: bool = False,
|
| 87 |
+
ignore_index: int = -100,
|
| 88 |
+
**kwargs,
|
| 89 |
+
):
|
| 90 |
+
super().__init__(*args, mlm=mlm, **kwargs)
|
| 91 |
+
|
| 92 |
+
self.instruction_template = instruction_template
|
| 93 |
+
if isinstance(instruction_template, str):
|
| 94 |
+
# The user provides a string, must tokenize
|
| 95 |
+
self.instruction_token_ids = self.tokenizer.encode(self.instruction_template, add_special_tokens=False)
|
| 96 |
+
else:
|
| 97 |
+
# The user already provides the token ids
|
| 98 |
+
self.instruction_token_ids = instruction_template
|
| 99 |
+
|
| 100 |
+
self.response_template = response_template
|
| 101 |
+
if isinstance(response_template, str):
|
| 102 |
+
# The user provides a string, must tokenize
|
| 103 |
+
self.response_token_ids = self.tokenizer.encode(self.response_template, add_special_tokens=False)
|
| 104 |
+
else:
|
| 105 |
+
# The user already provides the token ids
|
| 106 |
+
self.response_token_ids = response_template
|
| 107 |
+
|
| 108 |
+
if not self.mlm and self.instruction_template and self.tokenizer.pad_token_id == self.tokenizer.eos_token_id:
|
| 109 |
+
warnings.warn(
|
| 110 |
+
"The pad_token_id and eos_token_id values of this tokenizer are identical. "
|
| 111 |
+
"If you are planning for multi-turn training, "
|
| 112 |
+
"it can result in the model continuously generating questions and answers without eos token. "
|
| 113 |
+
"To avoid this, set the pad_token_id to a different value."
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
self.ignore_index = ignore_index
|
| 117 |
+
|
| 118 |
+
def torch_call(self, examples: List[Union[List[int], Any, Dict[str, Any]]]) -> Dict[str, Any]:
|
| 119 |
+
batch = super().torch_call(examples)
|
| 120 |
+
|
| 121 |
+
if self.instruction_template is None:
|
| 122 |
+
for i in range(len(examples)):
|
| 123 |
+
response_token_ids_start_idx = None
|
| 124 |
+
|
| 125 |
+
for idx in np.where(batch["labels"][i] == self.response_token_ids[0])[0]:
|
| 126 |
+
# `response_token_ids` is `'### Response:\n'`, here we are just making sure that the token IDs match
|
| 127 |
+
if self.response_token_ids == batch["labels"][i][idx : idx + len(self.response_token_ids)].tolist():
|
| 128 |
+
response_token_ids_start_idx = idx
|
| 129 |
+
|
| 130 |
+
if response_token_ids_start_idx is None:
|
| 131 |
+
warnings.warn(
|
| 132 |
+
f"Could not find response key `{self.response_template}` in the "
|
| 133 |
+
f'following instance: {self.tokenizer.decode(batch["input_ids"][i])} '
|
| 134 |
+
f"This instance will be ignored in loss calculation. "
|
| 135 |
+
f"Note, if this happens often, consider increasing the `max_seq_length`."
|
| 136 |
+
)
|
| 137 |
+
batch["labels"][i, :] = self.ignore_index
|
| 138 |
+
else:
|
| 139 |
+
response_token_ids_end_idx = response_token_ids_start_idx + len(self.response_token_ids)
|
| 140 |
+
|
| 141 |
+
# Make pytorch loss function ignore all tokens up through the end of the response key
|
| 142 |
+
batch["labels"][i, :response_token_ids_end_idx] = self.ignore_index
|
| 143 |
+
|
| 144 |
+
else:
|
| 145 |
+
for i in range(len(examples)):
|
| 146 |
+
response_token_ids_idxs = []
|
| 147 |
+
human_token_ids_idxs = []
|
| 148 |
+
|
| 149 |
+
for assistant_idx in np.where(batch["labels"][i] == self.response_token_ids[0])[0]:
|
| 150 |
+
# find the indexes of the start of a response.
|
| 151 |
+
if (
|
| 152 |
+
self.response_token_ids
|
| 153 |
+
== batch["labels"][i][assistant_idx : assistant_idx + len(self.response_token_ids)].tolist()
|
| 154 |
+
):
|
| 155 |
+
response_token_ids_idxs.append(assistant_idx + len(self.response_token_ids))
|
| 156 |
+
|
| 157 |
+
if len(response_token_ids_idxs) == 0:
|
| 158 |
+
warnings.warn(
|
| 159 |
+
f"Could not find response key `{self.response_template}` in the "
|
| 160 |
+
f'following instance: {self.tokenizer.decode(batch["input_ids"][i])} '
|
| 161 |
+
f"This instance will be ignored in loss calculation. "
|
| 162 |
+
f"Note, if this happens often, consider increasing the `max_seq_length`."
|
| 163 |
+
)
|
| 164 |
+
batch["labels"][i, :] = self.ignore_index
|
| 165 |
+
|
| 166 |
+
human_token_ids = self.instruction_token_ids
|
| 167 |
+
for human_idx in np.where(batch["labels"][i] == human_token_ids[0])[0]:
|
| 168 |
+
# find the indexes of the start of a human answer.
|
| 169 |
+
if human_token_ids == batch["labels"][i][human_idx : human_idx + len(human_token_ids)].tolist():
|
| 170 |
+
human_token_ids_idxs.append(human_idx)
|
| 171 |
+
|
| 172 |
+
if len(human_token_ids_idxs) == 0:
|
| 173 |
+
warnings.warn(
|
| 174 |
+
f"Could not find instruction key `{self.instruction_template}` in the "
|
| 175 |
+
f'following instance: {self.tokenizer.decode(batch["input_ids"][i])} '
|
| 176 |
+
f"This instance will be ignored in loss calculation. "
|
| 177 |
+
f"Note, if this happens often, consider increasing the `max_seq_length`."
|
| 178 |
+
)
|
| 179 |
+
batch["labels"][i, :] = self.ignore_index
|
| 180 |
+
|
| 181 |
+
if (
|
| 182 |
+
len(human_token_ids_idxs) > 0
|
| 183 |
+
and len(response_token_ids_idxs) > 0
|
| 184 |
+
and human_token_ids_idxs[0] > response_token_ids_idxs[0]
|
| 185 |
+
):
|
| 186 |
+
human_token_ids_idxs = [0] + human_token_ids_idxs
|
| 187 |
+
|
| 188 |
+
for idx, (start, end) in enumerate(zip(human_token_ids_idxs, response_token_ids_idxs)):
|
| 189 |
+
# Make pytorch loss function ignore all non response tokens
|
| 190 |
+
if idx != 0:
|
| 191 |
+
batch["labels"][i, start:end] = self.ignore_index
|
| 192 |
+
else:
|
| 193 |
+
batch["labels"][i, :end] = self.ignore_index
|
| 194 |
+
|
| 195 |
+
if len(response_token_ids_idxs) < len(human_token_ids_idxs):
|
| 196 |
+
batch["labels"][i, human_token_ids_idxs[-1] :] = self.ignore_index
|
| 197 |
+
|
| 198 |
+
return batch
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@dataclass
|
| 202 |
+
class RewardDataCollatorWithPadding:
|
| 203 |
+
r"""
|
| 204 |
+
Reward DataCollator class that pads the inputs to the maximum length of the batch.
|
| 205 |
+
Args:
|
| 206 |
+
tokenizer (`PreTrainedTokenizerBase`):
|
| 207 |
+
The tokenizer used for encoding the data.
|
| 208 |
+
padding (`Union[bool, str, `PaddingStrategy`]`, `optional`, defaults to `True`):
|
| 209 |
+
padding_strategy to pass to the tokenizer.
|
| 210 |
+
max_length (`Optional[int]`, `optional`, defaults to `None`):
|
| 211 |
+
The maximum length of the sequence to be processed.
|
| 212 |
+
pad_to_multiple_of (`Optional[int]`, `optional`, defaults to `None`):
|
| 213 |
+
If set will pad the sequence to a multiple of the provided value.
|
| 214 |
+
return_tensors (`str`, `optional`, defaults to `"pt"`):
|
| 215 |
+
The tensor type to use.
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
tokenizer: PreTrainedTokenizerBase
|
| 219 |
+
padding: Union[bool, str] = True
|
| 220 |
+
max_length: Optional[int] = None
|
| 221 |
+
pad_to_multiple_of: Optional[int] = None
|
| 222 |
+
return_tensors: str = "pt"
|
| 223 |
+
|
| 224 |
+
def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
|
| 225 |
+
features_chosen = []
|
| 226 |
+
features_rejected = []
|
| 227 |
+
margin = []
|
| 228 |
+
# check if we have a margin. If we do, we need to batch it as well
|
| 229 |
+
has_margin = "margin" in features[0]
|
| 230 |
+
for feature in features:
|
| 231 |
+
# check if the keys are named as expected
|
| 232 |
+
if (
|
| 233 |
+
"input_ids_chosen" not in feature
|
| 234 |
+
or "input_ids_rejected" not in feature
|
| 235 |
+
or "attention_mask_chosen" not in feature
|
| 236 |
+
or "attention_mask_rejected" not in feature
|
| 237 |
+
):
|
| 238 |
+
raise ValueError(
|
| 239 |
+
"The features should include `input_ids_chosen`, `attention_mask_chosen`, `input_ids_rejected` and `attention_mask_rejected`"
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
features_chosen.append(
|
| 243 |
+
{
|
| 244 |
+
"input_ids": feature["input_ids_chosen"],
|
| 245 |
+
"attention_mask": feature["attention_mask_chosen"],
|
| 246 |
+
}
|
| 247 |
+
)
|
| 248 |
+
features_rejected.append(
|
| 249 |
+
{
|
| 250 |
+
"input_ids": feature["input_ids_rejected"],
|
| 251 |
+
"attention_mask": feature["attention_mask_rejected"],
|
| 252 |
+
}
|
| 253 |
+
)
|
| 254 |
+
if has_margin:
|
| 255 |
+
margin.append(feature["margin"])
|
| 256 |
+
batch_chosen = self.tokenizer.pad(
|
| 257 |
+
features_chosen,
|
| 258 |
+
padding=self.padding,
|
| 259 |
+
max_length=self.max_length,
|
| 260 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 261 |
+
return_tensors=self.return_tensors,
|
| 262 |
+
)
|
| 263 |
+
batch_rejected = self.tokenizer.pad(
|
| 264 |
+
features_rejected,
|
| 265 |
+
padding=self.padding,
|
| 266 |
+
max_length=self.max_length,
|
| 267 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 268 |
+
return_tensors=self.return_tensors,
|
| 269 |
+
)
|
| 270 |
+
batch = {
|
| 271 |
+
"input_ids_chosen": batch_chosen["input_ids"],
|
| 272 |
+
"attention_mask_chosen": batch_chosen["attention_mask"],
|
| 273 |
+
"input_ids_rejected": batch_rejected["input_ids"],
|
| 274 |
+
"attention_mask_rejected": batch_rejected["attention_mask"],
|
| 275 |
+
"return_loss": True,
|
| 276 |
+
}
|
| 277 |
+
if has_margin:
|
| 278 |
+
margin = torch.tensor(margin, dtype=torch.float)
|
| 279 |
+
batch["margin"] = margin
|
| 280 |
+
return batch
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
@dataclass
|
| 284 |
+
class DPODataCollatorWithPadding:
|
| 285 |
+
r"""
|
| 286 |
+
DPO DataCollator class that pads the tokenized inputs to the maximum length of the batch.
|
| 287 |
+
Args:
|
| 288 |
+
pad_token_id (`int` defaults to 0):
|
| 289 |
+
The tokenizer's pad_token_id.
|
| 290 |
+
label_pad_token_id (`int`, defaults to -100):
|
| 291 |
+
The label used for masking.
|
| 292 |
+
is_encoder_decoder (`Optional[bool]`, `optional`, defaults to `None`):
|
| 293 |
+
Whether or not you model has an encoder_decoder architecture.
|
| 294 |
+
"""
|
| 295 |
+
tokenizer: PreTrainedTokenizerBase
|
| 296 |
+
pad_token_id: int = 0
|
| 297 |
+
label_pad_token_id: int = -100
|
| 298 |
+
is_encoder_decoder: Optional[bool] = False
|
| 299 |
+
|
| 300 |
+
def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
|
| 301 |
+
# first, pad everything to the same length
|
| 302 |
+
padded_batch = {}
|
| 303 |
+
for k in features[0].keys():
|
| 304 |
+
if k.endswith("_input_ids") or k.endswith("_attention_mask") or k.endswith("_labels"):
|
| 305 |
+
if self.is_encoder_decoder:
|
| 306 |
+
to_pad = [torch.LongTensor(ex[k]) for ex in features]
|
| 307 |
+
|
| 308 |
+
if (k.startswith("prompt")) and (k.endswith("input_ids")):
|
| 309 |
+
if self.pad_token_id is None:
|
| 310 |
+
raise ValueError(
|
| 311 |
+
"Padding is enabled, but the tokenizer is not configured with a padding token."
|
| 312 |
+
" Explicitly set `tokenizer.pad_token` (e.g. `tokenizer.pad_token = tokenizer.eos_token`)"
|
| 313 |
+
" before calling the trainer."
|
| 314 |
+
)
|
| 315 |
+
padding_value = self.pad_token_id
|
| 316 |
+
elif k.endswith("_attention_mask"):
|
| 317 |
+
padding_value = 0
|
| 318 |
+
elif (k.startswith("chosen")) or (k.startswith("rejected")) or ("decoder" in k):
|
| 319 |
+
padding_value = self.label_pad_token_id
|
| 320 |
+
else:
|
| 321 |
+
raise ValueError(f"Unexpected key in batch '{k}'")
|
| 322 |
+
padded_batch[k] = pad_sequence(to_pad, batch_first=True, padding_value=padding_value)
|
| 323 |
+
else:
|
| 324 |
+
# adapted from https://stackoverflow.com/questions/73256206
|
| 325 |
+
if "prompt" in k:
|
| 326 |
+
to_pad = [torch.LongTensor(ex[k][::-1]) for ex in features]
|
| 327 |
+
else:
|
| 328 |
+
to_pad = [torch.LongTensor(ex[k]) for ex in features]
|
| 329 |
+
if k.endswith("_input_ids"):
|
| 330 |
+
if self.pad_token_id is None:
|
| 331 |
+
raise ValueError(
|
| 332 |
+
"Padding is enabled, but the tokenizer is not configured with a padding token."
|
| 333 |
+
" Explicitly set `tokenizer.pad_token` (e.g. `tokenizer.pad_token = tokenizer.eos_token`)"
|
| 334 |
+
" before calling the trainer."
|
| 335 |
+
)
|
| 336 |
+
padding_value = self.pad_token_id
|
| 337 |
+
elif k.endswith("_labels"):
|
| 338 |
+
padding_value = self.label_pad_token_id
|
| 339 |
+
elif k.endswith("_attention_mask"):
|
| 340 |
+
padding_value = 0
|
| 341 |
+
else:
|
| 342 |
+
raise ValueError(f"Unexpected key in batch '{k}'")
|
| 343 |
+
|
| 344 |
+
padded_batch[k] = pad_sequence(to_pad, batch_first=True, padding_value=padding_value)
|
| 345 |
+
# for the prompt, flip back so padding is on left side
|
| 346 |
+
if "prompt" in k:
|
| 347 |
+
padded_batch[k] = padded_batch[k].flip(dims=[1])
|
| 348 |
+
elif k.endswith("_logps"):
|
| 349 |
+
# the cached reference model logprobs
|
| 350 |
+
padded_batch[k] = torch.tensor([ex[k] for ex in features])
|
| 351 |
+
else:
|
| 352 |
+
padded_batch[k] = [ex[k] for ex in features]
|
| 353 |
+
|
| 354 |
+
return padded_batch
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
class ConstantLengthDataset(IterableDataset):
|
| 358 |
+
"""
|
| 359 |
+
Iterable dataset that returns constant length chunks of tokens from stream of text files.
|
| 360 |
+
The dataset also formats the text before tokenization with a specific format that is provided
|
| 361 |
+
by the user.
|
| 362 |
+
|
| 363 |
+
Args:
|
| 364 |
+
tokenizer (`transformers.PreTrainedTokenizer`):
|
| 365 |
+
The processor used for processing the data.
|
| 366 |
+
dataset (`dataset.Dataset`):
|
| 367 |
+
Dataset with text files.
|
| 368 |
+
dataset_text_field (`str`, **optional**):
|
| 369 |
+
Name of the field in the dataset that contains the text. Used only if `formatting_func` is `None`.
|
| 370 |
+
formatting_func (`Callable`, **optional**):
|
| 371 |
+
Function that formats the text before tokenization. Usually it is recommended to have follows a certain
|
| 372 |
+
pattern such as `"### Question: {question} ### Answer: {answer}"`
|
| 373 |
+
infinite (`bool`, *optional*, defaults to `False`):
|
| 374 |
+
If True the iterator is reset after dataset reaches end else stops.
|
| 375 |
+
seq_length (`int`, *optional*, defaults to `1024`):
|
| 376 |
+
Length of token sequences to return.
|
| 377 |
+
num_of_sequences (`int`, *optional*, defaults to `1024`):
|
| 378 |
+
Number of token sequences to keep in buffer.
|
| 379 |
+
chars_per_token (`int`, *optional*, defaults to `3.6`):
|
| 380 |
+
Number of characters per token used to estimate number of tokens in text buffer.
|
| 381 |
+
eos_token_id (`int`, *optional*, defaults to `0`):
|
| 382 |
+
Id of the end of sequence token if the passed tokenizer does not have an EOS token.
|
| 383 |
+
shuffle ('bool', *optional*, defaults to True)
|
| 384 |
+
Shuffle the examples before they are returned
|
| 385 |
+
append_concat_token ('bool', *optional*, defaults to True)
|
| 386 |
+
If true, appends `eos_token_id` at the end of each sample being packed.
|
| 387 |
+
add_special_tokens ('bool', *optional*, defaults to True)
|
| 388 |
+
If true, tokenizers adds special tokens to each sample being packed.
|
| 389 |
+
"""
|
| 390 |
+
|
| 391 |
+
def __init__(
|
| 392 |
+
self,
|
| 393 |
+
tokenizer,
|
| 394 |
+
dataset,
|
| 395 |
+
dataset_text_field=None,
|
| 396 |
+
formatting_func=None,
|
| 397 |
+
infinite=False,
|
| 398 |
+
seq_length=1024,
|
| 399 |
+
num_of_sequences=1024,
|
| 400 |
+
chars_per_token=3.6,
|
| 401 |
+
eos_token_id=0,
|
| 402 |
+
shuffle=True,
|
| 403 |
+
append_concat_token=True,
|
| 404 |
+
add_special_tokens=True,
|
| 405 |
+
):
|
| 406 |
+
self.tokenizer = tokenizer
|
| 407 |
+
|
| 408 |
+
if tokenizer.eos_token_id is None:
|
| 409 |
+
warnings.warn(
|
| 410 |
+
"The passed tokenizer does not have an EOS token. We will use the passed eos_token_id instead which corresponds"
|
| 411 |
+
f" to {eos_token_id}. If this is not the correct EOS token, make sure to pass the correct eos_token_id."
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
self.concat_token_id = tokenizer.eos_token_id if tokenizer.eos_token_id else eos_token_id
|
| 415 |
+
self.dataset = dataset
|
| 416 |
+
self.seq_length = seq_length
|
| 417 |
+
self.infinite = infinite
|
| 418 |
+
self.current_size = 0
|
| 419 |
+
self.max_buffer_size = seq_length * chars_per_token * num_of_sequences
|
| 420 |
+
self.shuffle = shuffle
|
| 421 |
+
self.append_concat_token = append_concat_token
|
| 422 |
+
self.add_special_tokens = add_special_tokens
|
| 423 |
+
if formatting_func is None:
|
| 424 |
+
self.formatting_func = lambda x: x[dataset_text_field]
|
| 425 |
+
else:
|
| 426 |
+
self.formatting_func = formatting_func
|
| 427 |
+
|
| 428 |
+
if formatting_func is not None:
|
| 429 |
+
if formatting_func.__code__.co_argcount > 1:
|
| 430 |
+
warnings.warn(
|
| 431 |
+
"The passed formatting_func has more than one argument. Usually that function should have a single argument `example`"
|
| 432 |
+
" which corresponds to the dictionary returned by each element of the dataset. Make sure you know what you are doing."
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
def __len__(self):
|
| 436 |
+
return len(self.dataset)
|
| 437 |
+
|
| 438 |
+
def __iter__(self):
|
| 439 |
+
iterator = iter(self.dataset)
|
| 440 |
+
more_examples = True
|
| 441 |
+
while more_examples:
|
| 442 |
+
buffer, buffer_len = [], 0
|
| 443 |
+
while True:
|
| 444 |
+
if buffer_len >= self.max_buffer_size:
|
| 445 |
+
break
|
| 446 |
+
try:
|
| 447 |
+
buffer.append(self.formatting_func(next(iterator)))
|
| 448 |
+
buffer_len += len(buffer[-1])
|
| 449 |
+
except StopIteration:
|
| 450 |
+
if self.infinite:
|
| 451 |
+
iterator = iter(self.dataset)
|
| 452 |
+
warnings.warn("The dataset reached end and the iterator is reset to the start.")
|
| 453 |
+
else:
|
| 454 |
+
more_examples = False
|
| 455 |
+
break
|
| 456 |
+
tokenized_inputs = self.tokenizer(buffer, add_special_tokens=self.add_special_tokens, truncation=False)[
|
| 457 |
+
"input_ids"
|
| 458 |
+
]
|
| 459 |
+
all_token_ids = []
|
| 460 |
+
for tokenized_input in tokenized_inputs:
|
| 461 |
+
if self.append_concat_token:
|
| 462 |
+
tokenized_input = tokenized_input + [self.concat_token_id]
|
| 463 |
+
all_token_ids.extend(tokenized_input)
|
| 464 |
+
examples = []
|
| 465 |
+
for i in range(0, len(all_token_ids), self.seq_length):
|
| 466 |
+
input_ids = all_token_ids[i : i + self.seq_length]
|
| 467 |
+
if len(input_ids) == self.seq_length:
|
| 468 |
+
examples.append(input_ids)
|
| 469 |
+
if self.shuffle:
|
| 470 |
+
random.shuffle(examples)
|
| 471 |
+
for example in examples:
|
| 472 |
+
self.current_size += 1
|
| 473 |
+
yield {
|
| 474 |
+
"input_ids": torch.LongTensor(example),
|
| 475 |
+
"labels": torch.LongTensor(example),
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
class RunningMoments:
|
| 480 |
+
def __init__(self, accelerator):
|
| 481 |
+
"""
|
| 482 |
+
Calculates the running mean and standard deviation of a data stream. Reference:
|
| 483 |
+
https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L75
|
| 484 |
+
"""
|
| 485 |
+
self.mean = 0
|
| 486 |
+
self.std = 1
|
| 487 |
+
self.var = 1
|
| 488 |
+
self.count = 1e-24
|
| 489 |
+
self.accelerator = accelerator
|
| 490 |
+
|
| 491 |
+
@torch.no_grad()
|
| 492 |
+
def update(self, xs: torch.Tensor) -> Tuple[float, float]:
|
| 493 |
+
"""
|
| 494 |
+
Updates running moments from batch's moments computed across ranks
|
| 495 |
+
"""
|
| 496 |
+
if self.accelerator.use_distributed:
|
| 497 |
+
xs_mean, xs_var, xs_count = get_global_statistics(self.accelerator, xs)
|
| 498 |
+
else:
|
| 499 |
+
xs_count = xs.numel()
|
| 500 |
+
xs_var, xs_mean = torch.var_mean(xs, unbiased=False)
|
| 501 |
+
xs_mean, xs_var = xs_mean.float(), xs_var.float()
|
| 502 |
+
|
| 503 |
+
delta = xs_mean - self.mean
|
| 504 |
+
tot_count = self.count + xs_count
|
| 505 |
+
|
| 506 |
+
new_sum = xs_var * xs_count
|
| 507 |
+
# correct old_sum deviation accounting for the new mean
|
| 508 |
+
old_sum = self.var * self.count + delta**2 * self.count * xs_count / tot_count
|
| 509 |
+
tot_sum = old_sum + new_sum
|
| 510 |
+
|
| 511 |
+
self.mean += delta * xs_count / tot_count
|
| 512 |
+
self.var = tot_sum / tot_count
|
| 513 |
+
self.std = (self.var * tot_count / (tot_count - 1)).float().sqrt()
|
| 514 |
+
self.count = tot_count
|
| 515 |
+
|
| 516 |
+
return xs_mean.item(), (xs_var * xs_count / (xs_count - 1)).float().sqrt().item()
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
@torch.no_grad()
|
| 520 |
+
def get_global_statistics(accelerator, xs: torch.Tensor, mask=None, device="cpu") -> Tuple[float, float, int]:
|
| 521 |
+
"""
|
| 522 |
+
Computes element-wise mean and variance of the tensor across processes. Reference:
|
| 523 |
+
https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L57C1-L73C75
|
| 524 |
+
"""
|
| 525 |
+
xs = xs.to(accelerator.device)
|
| 526 |
+
sum_and_count = torch.tensor([xs.sum(), (xs.numel() if mask is None else mask.sum())], device=xs.device)
|
| 527 |
+
sum_and_count = accelerator.reduce(sum_and_count)
|
| 528 |
+
global_sum, count = sum_and_count
|
| 529 |
+
global_mean = global_sum / count
|
| 530 |
+
|
| 531 |
+
sum_var = torch.sum(((xs - global_mean) ** 2).mul(1 if mask is None else mask))
|
| 532 |
+
sum_var = accelerator.reduce(sum_var)
|
| 533 |
+
global_var = sum_var / count
|
| 534 |
+
|
| 535 |
+
return global_mean.to(device), global_var.to(device), count.to(device)
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def compute_accuracy(eval_pred) -> Dict[str, float]:
|
| 539 |
+
predictions, labels = eval_pred
|
| 540 |
+
# Here, predictions is rewards_chosen and rewards_rejected.
|
| 541 |
+
# We want to see how much of the time rewards_chosen > rewards_rejected.
|
| 542 |
+
if np.array(predictions[:, 0] == predictions[:, 1], dtype=float).sum() > 0:
|
| 543 |
+
warnings.warn(
|
| 544 |
+
f"There are {np.array(predictions[:, 0] == predictions[:, 1]).sum()} out of {len(predictions[:, 0])} instances where the predictions for both options are equal. As a consequence the accuracy can be misleading."
|
| 545 |
+
)
|
| 546 |
+
predictions = np.argmax(predictions, axis=1)
|
| 547 |
+
|
| 548 |
+
accuracy = np.array(predictions == labels, dtype=float).mean().item()
|
| 549 |
+
return {"accuracy": accuracy}
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def pad_to_length(tensor: torch.Tensor, length: int, pad_value: Union[int, float], dim: int = -1) -> torch.Tensor:
|
| 553 |
+
if tensor.size(dim) >= length:
|
| 554 |
+
return tensor
|
| 555 |
+
else:
|
| 556 |
+
pad_size = list(tensor.shape)
|
| 557 |
+
pad_size[dim] = length - tensor.size(dim)
|
| 558 |
+
return torch.cat(
|
| 559 |
+
[
|
| 560 |
+
tensor,
|
| 561 |
+
pad_value * torch.ones(*pad_size, dtype=tensor.dtype, device=tensor.device),
|
| 562 |
+
],
|
| 563 |
+
dim=dim,
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
def disable_dropout_in_model(model: torch.nn.Module) -> None:
|
| 568 |
+
for module in model.modules():
|
| 569 |
+
if isinstance(module, torch.nn.Dropout):
|
| 570 |
+
module.p = 0
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def exact_div(a, b, a_str, b_str, custom_error_message=""):
|
| 574 |
+
q = a // b
|
| 575 |
+
if a != q * b:
|
| 576 |
+
raise ValueError(f"{custom_error_message}, {a_str}={a}, {b_str}={b}, inexact division: {a} / {b} = {a / b}")
|
| 577 |
+
return q
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
# copied from https://github.com/kvablack/ddpo-pytorch/blob/main/ddpo_pytorch/stat_tracking.py#L5
|
| 581 |
+
class PerPromptStatTracker:
|
| 582 |
+
r"""
|
| 583 |
+
Class for tracking statistics per prompt. Mainly used to calculate advantage for the DPPO algorithm
|
| 584 |
+
|
| 585 |
+
Args:
|
| 586 |
+
buffer_size (`int`):
|
| 587 |
+
Size of the buffer to keep for each prompt.
|
| 588 |
+
min_count (`int`):
|
| 589 |
+
Minimum number of samples to keep in the buffer before calculating the mean and std.
|
| 590 |
+
"""
|
| 591 |
+
|
| 592 |
+
def __init__(self, buffer_size, min_count):
|
| 593 |
+
self.buffer_size = buffer_size
|
| 594 |
+
self.min_count = min_count
|
| 595 |
+
self.stats = {}
|
| 596 |
+
|
| 597 |
+
def update(self, prompts, rewards):
|
| 598 |
+
prompts = np.array(prompts)
|
| 599 |
+
rewards = np.array(rewards)
|
| 600 |
+
unique = np.unique(prompts)
|
| 601 |
+
advantages = np.empty_like(rewards)
|
| 602 |
+
for prompt in unique:
|
| 603 |
+
prompt_rewards = rewards[prompts == prompt]
|
| 604 |
+
if prompt not in self.stats:
|
| 605 |
+
self.stats[prompt] = deque(maxlen=self.buffer_size)
|
| 606 |
+
self.stats[prompt].extend(prompt_rewards)
|
| 607 |
+
|
| 608 |
+
if len(self.stats[prompt]) < self.min_count:
|
| 609 |
+
mean = np.mean(rewards)
|
| 610 |
+
std = np.std(rewards) + 1e-6
|
| 611 |
+
else:
|
| 612 |
+
mean = np.mean(self.stats[prompt])
|
| 613 |
+
std = np.std(self.stats[prompt]) + 1e-6
|
| 614 |
+
advantages[prompts == prompt] = (prompt_rewards - mean) / std
|
| 615 |
+
|
| 616 |
+
return advantages
|
| 617 |
+
|
| 618 |
+
def get_stats(self):
|
| 619 |
+
return {k: {"mean": np.mean(v), "std": np.std(v), "count": len(v)} for k, v in self.stats.items()}
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def neftune_post_forward_hook(module, input, output):
|
| 623 |
+
"""
|
| 624 |
+
Implements the NEFTune forward pass for the model using forward hooks. Note this works only for
|
| 625 |
+
torch.nn.Embedding layers. This method is slightly adapted from the original source code
|
| 626 |
+
that can be found here: https://github.com/neelsjain/NEFTune
|
| 627 |
+
|
| 628 |
+
Simply add it to your model as follows:
|
| 629 |
+
```python
|
| 630 |
+
model = ...
|
| 631 |
+
model.embed_tokens.neftune_noise_alpha = 0.1
|
| 632 |
+
model.embed_tokens.register_forward_hook(neftune_post_forward_hook)
|
| 633 |
+
```
|
| 634 |
+
|
| 635 |
+
Args:
|
| 636 |
+
module (`torch.nn.Module`):
|
| 637 |
+
The embedding module where the hook is attached. Note that you need to set
|
| 638 |
+
`module.neftune_noise_alpha` to the desired noise alpha value.
|
| 639 |
+
input (`torch.Tensor`):
|
| 640 |
+
The input tensor to the model.
|
| 641 |
+
output (`torch.Tensor`):
|
| 642 |
+
The output tensor of the model (i.e. the embeddings).
|
| 643 |
+
"""
|
| 644 |
+
if module.training:
|
| 645 |
+
dims = torch.tensor(output.size(1) * output.size(2))
|
| 646 |
+
mag_norm = module.neftune_noise_alpha / torch.sqrt(dims)
|
| 647 |
+
output = output + torch.zeros_like(output).uniform_(-mag_norm, mag_norm)
|
| 648 |
+
return output
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def peft_module_casting_to_bf16(model):
|
| 652 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
| 653 |
+
|
| 654 |
+
for name, module in model.named_modules():
|
| 655 |
+
if isinstance(module, BaseTunerLayer):
|
| 656 |
+
module = module.to(torch.bfloat16)
|
| 657 |
+
elif isinstance(module, torch.nn.LayerNorm) or "norm" in name:
|
| 658 |
+
module = module.to(torch.float32)
|
| 659 |
+
elif any(x in name for x in ["lm_head", "embed_tokens", "wte", "wpe"]):
|
| 660 |
+
if hasattr(module, "weight"):
|
| 661 |
+
if module.weight.dtype == torch.float32:
|
| 662 |
+
module = module.to(torch.bfloat16)
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
def trl_sanitze_kwargs_for_tagging(model, tag_names, kwargs=None):
|
| 666 |
+
if is_unsloth_available():
|
| 667 |
+
# Unsloth adds a new attribute in the model config `unsloth_version`
|
| 668 |
+
# to keep track of models that have been patched with unsloth.
|
| 669 |
+
if hasattr(model, "config") and getattr(model.config, "unsloth_version", None) is not None:
|
| 670 |
+
tag_names.append("unsloth")
|
| 671 |
+
|
| 672 |
+
if kwargs is not None:
|
| 673 |
+
if "tags" not in kwargs:
|
| 674 |
+
kwargs["tags"] = tag_names
|
| 675 |
+
elif "tags" in kwargs and isinstance(kwargs["tags"], list):
|
| 676 |
+
kwargs["tags"].extend(tag_names)
|
| 677 |
+
elif "tags" in kwargs and isinstance(kwargs["tags"], str):
|
| 678 |
+
tag_names.append(kwargs["tags"])
|
| 679 |
+
kwargs["tags"] = tag_names
|
| 680 |
+
return kwargs
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def get_quantization_config(model_config: ModelConfig) -> Optional[BitsAndBytesConfig]:
|
| 684 |
+
if model_config.load_in_4bit:
|
| 685 |
+
quantization_config = BitsAndBytesConfig(
|
| 686 |
+
load_in_4bit=True,
|
| 687 |
+
bnb_4bit_compute_dtype=model_config.torch_dtype, # For consistency with model weights, we use the same value as `torch_dtype`
|
| 688 |
+
bnb_4bit_quant_type=model_config.bnb_4bit_quant_type,
|
| 689 |
+
bnb_4bit_use_double_quant=model_config.use_bnb_nested_quant,
|
| 690 |
+
)
|
| 691 |
+
elif model_config.load_in_8bit:
|
| 692 |
+
quantization_config = BitsAndBytesConfig(
|
| 693 |
+
load_in_8bit=True,
|
| 694 |
+
)
|
| 695 |
+
else:
|
| 696 |
+
quantization_config = None
|
| 697 |
+
|
| 698 |
+
return quantization_config
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
def get_kbit_device_map() -> Optional[Dict[str, int]]:
|
| 702 |
+
if is_xpu_available():
|
| 703 |
+
return {"": f"xpu:{PartialState().local_process_index}"}
|
| 704 |
+
elif torch.cuda.is_available():
|
| 705 |
+
return {"": PartialState().local_process_index}
|
| 706 |
+
else:
|
| 707 |
+
return None
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def get_peft_config(model_config: ModelConfig) -> "Optional[PeftConfig]":
|
| 711 |
+
if model_config.use_peft is False:
|
| 712 |
+
return None
|
| 713 |
+
|
| 714 |
+
peft_config = LoraConfig(
|
| 715 |
+
r=model_config.lora_r,
|
| 716 |
+
lora_alpha=model_config.lora_alpha,
|
| 717 |
+
lora_dropout=model_config.lora_dropout,
|
| 718 |
+
bias="none",
|
| 719 |
+
task_type="CAUSAL_LM",
|
| 720 |
+
target_modules=model_config.lora_target_modules,
|
| 721 |
+
modules_to_save=model_config.lora_modules_to_save,
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
return peft_config
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/unit_test_utils.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 NVIDIA CORPORATION & AFFILIATES
|
| 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 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 16 |
+
|
| 17 |
+
from unittest.case import _id as __id
|
| 18 |
+
from unittest.case import skip as __skip
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def requires_gpu(reason=None):
|
| 22 |
+
import torch
|
| 23 |
+
|
| 24 |
+
reason = "no GPUs detected. Only test in GPU environemnts" if reason is None else reason
|
| 25 |
+
if not torch.cuda.is_available():
|
| 26 |
+
return __skip(reason)
|
| 27 |
+
return __id
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def requires_lustre(reason=None):
|
| 31 |
+
import os.path as osp
|
| 32 |
+
|
| 33 |
+
if not (osp.isdir("/lustre") or osp.isdir("/mnt")):
|
| 34 |
+
reason = "lustre path is not avaliable." if reason is None else reason
|
| 35 |
+
return __skip(reason)
|
| 36 |
+
return __id
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 NVIDIA CORPORATION & AFFILIATES
|
| 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 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 16 |
+
# This file is modified from https://github.com/haotian-liu/LLaVA/
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
import datetime
|
| 20 |
+
import logging
|
| 21 |
+
import logging.handlers
|
| 22 |
+
import os
|
| 23 |
+
import sys
|
| 24 |
+
|
| 25 |
+
import requests
|
| 26 |
+
|
| 27 |
+
from llava.constants import LOGDIR
|
| 28 |
+
|
| 29 |
+
server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
|
| 30 |
+
moderation_msg = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN."
|
| 31 |
+
|
| 32 |
+
handler = None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def build_logger(logger_name, logger_filename):
|
| 36 |
+
global handler
|
| 37 |
+
|
| 38 |
+
formatter = logging.Formatter(
|
| 39 |
+
fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
|
| 40 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# Set the format of root handlers
|
| 44 |
+
if not logging.getLogger().handlers:
|
| 45 |
+
logging.basicConfig(level=logging.INFO)
|
| 46 |
+
logging.getLogger().handlers[0].setFormatter(formatter)
|
| 47 |
+
|
| 48 |
+
# Redirect stdout and stderr to loggers
|
| 49 |
+
stdout_logger = logging.getLogger("stdout")
|
| 50 |
+
stdout_logger.setLevel(logging.INFO)
|
| 51 |
+
sl = StreamToLogger(stdout_logger, logging.INFO)
|
| 52 |
+
sys.stdout = sl
|
| 53 |
+
|
| 54 |
+
stderr_logger = logging.getLogger("stderr")
|
| 55 |
+
stderr_logger.setLevel(logging.ERROR)
|
| 56 |
+
sl = StreamToLogger(stderr_logger, logging.ERROR)
|
| 57 |
+
sys.stderr = sl
|
| 58 |
+
|
| 59 |
+
# Get logger
|
| 60 |
+
logger = logging.getLogger(logger_name)
|
| 61 |
+
logger.setLevel(logging.INFO)
|
| 62 |
+
|
| 63 |
+
# Add a file handler for all loggers
|
| 64 |
+
if handler is None:
|
| 65 |
+
os.makedirs(LOGDIR, exist_ok=True)
|
| 66 |
+
filename = os.path.join(LOGDIR, logger_filename)
|
| 67 |
+
handler = logging.handlers.TimedRotatingFileHandler(
|
| 68 |
+
filename, when='D', utc=True, encoding='UTF-8')
|
| 69 |
+
handler.setFormatter(formatter)
|
| 70 |
+
|
| 71 |
+
for name, item in logging.root.manager.loggerDict.items():
|
| 72 |
+
if isinstance(item, logging.Logger):
|
| 73 |
+
item.addHandler(handler)
|
| 74 |
+
|
| 75 |
+
return logger
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class StreamToLogger(object):
|
| 79 |
+
"""
|
| 80 |
+
Fake file-like stream object that redirects writes to a logger instance.
|
| 81 |
+
"""
|
| 82 |
+
def __init__(self, logger, log_level=logging.INFO):
|
| 83 |
+
self.terminal = sys.stdout
|
| 84 |
+
self.logger = logger
|
| 85 |
+
self.log_level = log_level
|
| 86 |
+
self.linebuf = ''
|
| 87 |
+
|
| 88 |
+
def __getattr__(self, attr):
|
| 89 |
+
return getattr(self.terminal, attr)
|
| 90 |
+
|
| 91 |
+
def write(self, buf):
|
| 92 |
+
temp_linebuf = self.linebuf + buf
|
| 93 |
+
self.linebuf = ''
|
| 94 |
+
for line in temp_linebuf.splitlines(True):
|
| 95 |
+
# From the io.TextIOWrapper docs:
|
| 96 |
+
# On output, if newline is None, any '\n' characters written
|
| 97 |
+
# are translated to the system default line separator.
|
| 98 |
+
# By default sys.stdout.write() expects '\n' newlines and then
|
| 99 |
+
# translates them so this is still cross platform.
|
| 100 |
+
if line[-1] == '\n':
|
| 101 |
+
self.logger.log(self.log_level, line.rstrip())
|
| 102 |
+
else:
|
| 103 |
+
self.linebuf += line
|
| 104 |
+
|
| 105 |
+
def flush(self):
|
| 106 |
+
if self.linebuf != '':
|
| 107 |
+
self.logger.log(self.log_level, self.linebuf.rstrip())
|
| 108 |
+
self.linebuf = ''
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def disable_torch_init():
|
| 112 |
+
"""
|
| 113 |
+
Disable the redundant torch default initialization to accelerate model creation.
|
| 114 |
+
"""
|
| 115 |
+
import torch
|
| 116 |
+
setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
|
| 117 |
+
setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def violates_moderation(text):
|
| 121 |
+
"""
|
| 122 |
+
Check whether the text violates OpenAI moderation API.
|
| 123 |
+
"""
|
| 124 |
+
url = "https://api.openai.com/v1/moderations"
|
| 125 |
+
headers = {"Content-Type": "application/json",
|
| 126 |
+
"Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]}
|
| 127 |
+
text = text.replace("\n", "")
|
| 128 |
+
data = "{" + '"input": ' + f'"{text}"' + "}"
|
| 129 |
+
data = data.encode("utf-8")
|
| 130 |
+
try:
|
| 131 |
+
ret = requests.post(url, headers=headers, data=data, timeout=5)
|
| 132 |
+
flagged = ret.json()["results"][0]["flagged"]
|
| 133 |
+
except requests.exceptions.RequestException as e:
|
| 134 |
+
flagged = False
|
| 135 |
+
except KeyError as e:
|
| 136 |
+
flagged = False
|
| 137 |
+
|
| 138 |
+
return flagged
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def pretty_print_semaphore(semaphore):
|
| 142 |
+
if semaphore is None:
|
| 143 |
+
return "None"
|
| 144 |
+
return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})"
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .utils import *
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils/distributed.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import warnings
|
| 3 |
+
from typing import Any, List, Optional
|
| 4 |
+
|
| 5 |
+
from torch import distributed as dist
|
| 6 |
+
|
| 7 |
+
__all__ = ["init", "is_initialized", "size", "rank", "local_size", "local_rank", "is_main", "gather"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def init() -> None:
|
| 11 |
+
if "RANK" not in os.environ:
|
| 12 |
+
warnings.warn("Environment variable `RANK` is not set. Skipping distributed initialization.")
|
| 13 |
+
return
|
| 14 |
+
dist.init_process_group(backend="nccl", init_method="env://")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def is_initialized() -> bool:
|
| 18 |
+
return dist.is_initialized()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def size() -> int:
|
| 22 |
+
return int(os.environ.get("WORLD_SIZE", 1))
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def rank() -> int:
|
| 26 |
+
return int(os.environ.get("RANK", 0))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def local_size() -> int:
|
| 30 |
+
return int(os.environ.get("LOCAL_WORLD_SIZE", 1))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def local_rank() -> int:
|
| 34 |
+
return int(os.environ.get("LOCAL_RANK", 0))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def is_main() -> bool:
|
| 38 |
+
return rank() == 0
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def gather(obj: Any, dst: int = 0) -> Optional[List[Any]]:
|
| 42 |
+
if is_main():
|
| 43 |
+
objs = [None for _ in range(size())]
|
| 44 |
+
dist.gather_object(obj, objs, dst=dst)
|
| 45 |
+
return objs
|
| 46 |
+
else:
|
| 47 |
+
dist.gather_object(obj, dst=dst)
|
| 48 |
+
return None
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils/io.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import pickle
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
from io import TextIOWrapper
|
| 6 |
+
from typing import IO, Any, BinaryIO, Callable, Dict, Iterator, TextIO, Union
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
import yaml
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"load",
|
| 14 |
+
"save",
|
| 15 |
+
"load_json",
|
| 16 |
+
"save_json",
|
| 17 |
+
"load_jsonl",
|
| 18 |
+
"save_jsonl",
|
| 19 |
+
"load_mat",
|
| 20 |
+
"save_mat",
|
| 21 |
+
"load_npy",
|
| 22 |
+
"save_npy",
|
| 23 |
+
"load_npz",
|
| 24 |
+
"save_npz",
|
| 25 |
+
"load_pt",
|
| 26 |
+
"save_pt",
|
| 27 |
+
"load_yaml",
|
| 28 |
+
"save_yaml",
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@contextmanager
|
| 33 |
+
def file_descriptor(f: Union[str, IO], mode: str = "r") -> Iterator[IO]:
|
| 34 |
+
opened = False
|
| 35 |
+
try:
|
| 36 |
+
if isinstance(f, str):
|
| 37 |
+
f = open(f, mode)
|
| 38 |
+
opened = True
|
| 39 |
+
yield f
|
| 40 |
+
finally:
|
| 41 |
+
if opened:
|
| 42 |
+
assert isinstance(f, TextIOWrapper), type(f)
|
| 43 |
+
f.close()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def load_json(f: Union[str, TextIO], **kwargs) -> Any:
|
| 47 |
+
with file_descriptor(f, mode="r") as fd:
|
| 48 |
+
return json.load(fd, **kwargs)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def save_json(f: Union[str, TextIO], obj: Any, **kwargs) -> None:
|
| 52 |
+
with file_descriptor(f, mode="w") as fd:
|
| 53 |
+
json.dump(obj, fd, **kwargs)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def load_jsonl(f: Union[str, TextIO], **kwargs) -> Any:
|
| 57 |
+
with file_descriptor(f, mode="r") as fd:
|
| 58 |
+
return [json.loads(datum, **kwargs) for datum in fd.readlines()]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def save_jsonl(f: Union[str, TextIO], obj: Any, **kwargs) -> None:
|
| 62 |
+
with file_descriptor(f, mode="w") as fd:
|
| 63 |
+
fd.write("\n".join(json.dumps(datum, **kwargs) for datum in obj))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def load_mat(f: Union[str, BinaryIO], **kwargs) -> Any:
|
| 67 |
+
import scipy.io
|
| 68 |
+
|
| 69 |
+
return scipy.io.loadmat(f, **kwargs)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def save_mat(f: Union[str, BinaryIO], obj: Any, **kwargs) -> None:
|
| 73 |
+
import scipy.io
|
| 74 |
+
|
| 75 |
+
scipy.io.savemat(f, obj, **kwargs)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def load_npy(f: Union[str, BinaryIO], **kwargs) -> Any:
|
| 79 |
+
return np.load(f, **kwargs)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def save_npy(f: Union[str, BinaryIO], obj: Any, **kwargs) -> None:
|
| 83 |
+
np.save(f, obj, **kwargs)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def load_npz(f: Union[str, BinaryIO], **kwargs) -> Any:
|
| 87 |
+
return np.load(f, **kwargs)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def save_npz(f: Union[str, BinaryIO], obj: Any, **kwargs) -> None:
|
| 91 |
+
np.savez(f, obj, **kwargs)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def load_pkl(f: Union[str, BinaryIO], **kwargs) -> Any:
|
| 95 |
+
with file_descriptor(f, mode="rb") as fd:
|
| 96 |
+
try:
|
| 97 |
+
return pickle.load(fd, **kwargs)
|
| 98 |
+
except UnicodeDecodeError:
|
| 99 |
+
if "encoding" in kwargs:
|
| 100 |
+
raise
|
| 101 |
+
fd.seek(0)
|
| 102 |
+
return pickle.load(fd, encoding="latin1", **kwargs)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def save_pkl(f: Union[str, BinaryIO], obj: Any, **kwargs) -> None:
|
| 106 |
+
with file_descriptor(f, mode="wb") as fd:
|
| 107 |
+
pickle.dump(obj, fd, **kwargs)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def load_pt(f: Union[str, BinaryIO], **kwargs) -> Any:
|
| 111 |
+
return torch.load(f, **kwargs)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def save_pt(f: Union[str, BinaryIO], obj: Any, **kwargs) -> None:
|
| 115 |
+
torch.save(obj, f, **kwargs)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def load_yaml(f: Union[str, TextIO]) -> Any:
|
| 119 |
+
with file_descriptor(f, mode="r") as fd:
|
| 120 |
+
return yaml.safe_load(fd)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def save_yaml(f: Union[str, TextIO], obj: Any, **kwargs) -> None:
|
| 124 |
+
with file_descriptor(f, mode="w") as fd:
|
| 125 |
+
yaml.safe_dump(obj, fd, **kwargs)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
__io_registry: Dict[str, Dict[str, Callable]] = {
|
| 129 |
+
".json": {"load": load_json, "save": save_json},
|
| 130 |
+
".jsonl": {"load": load_jsonl, "save": save_jsonl},
|
| 131 |
+
".mat": {"load": load_mat, "save": save_mat},
|
| 132 |
+
".npy": {"load": load_npy, "save": save_npy},
|
| 133 |
+
".npz": {"load": load_npz, "save": save_npz},
|
| 134 |
+
".pkl": {"load": load_pkl, "save": save_pkl},
|
| 135 |
+
".pt": {"load": load_pt, "save": save_pt},
|
| 136 |
+
".pth": {"load": load_pt, "save": save_pt},
|
| 137 |
+
".pth.tar": {"load": load_pt, "save": save_pt},
|
| 138 |
+
".yaml": {"load": load_yaml, "save": save_yaml},
|
| 139 |
+
".yml": {"load": load_yaml, "save": save_yaml},
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def load(fpath: str, **kwargs) -> Any:
|
| 144 |
+
assert isinstance(fpath, str), type(fpath)
|
| 145 |
+
|
| 146 |
+
for extension in sorted(__io_registry.keys(), key=len, reverse=True):
|
| 147 |
+
if fpath.endswith(extension) and "load" in __io_registry[extension]:
|
| 148 |
+
return __io_registry[extension]["load"](fpath, **kwargs)
|
| 149 |
+
|
| 150 |
+
raise NotImplementedError(f'"{fpath}" cannot be loaded.')
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def save(fpath: str, obj: Any, **kwargs) -> None:
|
| 154 |
+
assert isinstance(fpath, str), type(fpath)
|
| 155 |
+
os.makedirs(os.path.dirname(fpath), exist_ok=True)
|
| 156 |
+
|
| 157 |
+
for extension in sorted(__io_registry.keys(), key=len, reverse=True):
|
| 158 |
+
if fpath.endswith(extension) and "save" in __io_registry[extension]:
|
| 159 |
+
__io_registry[extension]["save"](fpath, obj, **kwargs)
|
| 160 |
+
return
|
| 161 |
+
|
| 162 |
+
raise NotImplementedError(f'"{fpath}" cannot be saved.')
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils/merge_lora_weights_and_save_hf_model.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 NVIDIA CORPORATION & AFFILIATES
|
| 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 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 16 |
+
# This file is modified from https://github.com/dvlab-research/LongLoRA
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import os
|
| 20 |
+
from typing import Dict
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import transformers
|
| 24 |
+
from peft import PeftModel
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def parse_config():
|
| 28 |
+
parser = argparse.ArgumentParser(description="arg parser")
|
| 29 |
+
parser.add_argument("--base_model", type=str, default="/data/pretrained-models/llama-7b-hf")
|
| 30 |
+
parser.add_argument("--peft_model", type=str, default=None, help="")
|
| 31 |
+
parser.add_argument("--save_path", type=str, default=None, help="")
|
| 32 |
+
parser.add_argument("--cache_dir", type=str, default=None, help="./cache_dir")
|
| 33 |
+
parser.add_argument("--rope_theta", type=int, default=15300000, help="")
|
| 34 |
+
parser.add_argument("--max_position_embeddings", type=int, default=65536, help="")
|
| 35 |
+
args = parser.parse_args()
|
| 36 |
+
return args
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def smart_tokenizer_and_embedding_resize(
|
| 40 |
+
special_tokens_dict: Dict,
|
| 41 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
| 42 |
+
model: transformers.PreTrainedModel,
|
| 43 |
+
):
|
| 44 |
+
"""Resize tokenizer and embedding.
|
| 45 |
+
|
| 46 |
+
Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
|
| 47 |
+
"""
|
| 48 |
+
num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
|
| 49 |
+
model.resize_token_embeddings(len(tokenizer))
|
| 50 |
+
|
| 51 |
+
if num_new_tokens > 0:
|
| 52 |
+
input_embeddings = model.get_input_embeddings().weight.data
|
| 53 |
+
output_embeddings = model.get_output_embeddings().weight.data
|
| 54 |
+
|
| 55 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
| 56 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
| 57 |
+
|
| 58 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
| 59 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def main():
|
| 63 |
+
args = parse_config()
|
| 64 |
+
device = "cuda:0"
|
| 65 |
+
torch.cuda.set_device(device)
|
| 66 |
+
|
| 67 |
+
print("base model", args.base_model)
|
| 68 |
+
print("peft model", args.peft_model)
|
| 69 |
+
|
| 70 |
+
config = transformers.AutoConfig.from_pretrained(
|
| 71 |
+
args.base_model,
|
| 72 |
+
cache_dir=args.cache_dir,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
config.rope_theta = args.rope_theta
|
| 76 |
+
config.max_position_embeddings = args.max_position_embeddings
|
| 77 |
+
config.model_max_length = args.max_position_embeddings
|
| 78 |
+
config.tokenizer_model_max_length = args.max_position_embeddings
|
| 79 |
+
|
| 80 |
+
# Load model and tokenizer
|
| 81 |
+
model = transformers.AutoModelForCausalLM.from_pretrained(
|
| 82 |
+
args.base_model,
|
| 83 |
+
config=config,
|
| 84 |
+
cache_dir=args.cache_dir,
|
| 85 |
+
torch_dtype=torch.bfloat16,
|
| 86 |
+
device_map="auto",
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
| 90 |
+
args.base_model,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
model = PeftModel.from_pretrained(
|
| 94 |
+
model,
|
| 95 |
+
args.peft_model,
|
| 96 |
+
device_map="auto",
|
| 97 |
+
torch_dtype=torch.bfloat16,
|
| 98 |
+
)
|
| 99 |
+
model = model.merge_and_unload()
|
| 100 |
+
model.save_pretrained(args.save_path)
|
| 101 |
+
tokenizer.save_pretrained(args.save_path)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
if __name__ == "__main__":
|
| 105 |
+
main()
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils/tokenizer.py
ADDED
|
@@ -0,0 +1,165 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CORPORATION & AFFILIATES
|
| 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 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 16 |
+
|
| 17 |
+
import logging
|
| 18 |
+
from typing import Any, Dict, List, Optional, Sequence
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import transformers
|
| 22 |
+
|
| 23 |
+
from llava import conversation as conversation_lib
|
| 24 |
+
from llava.constants import IGNORE_INDEX
|
| 25 |
+
from llava.mm_utils import tokenizer_image_token
|
| 26 |
+
|
| 27 |
+
__all__ = [
|
| 28 |
+
"tokenize_conversation",
|
| 29 |
+
"preprocess_conversation",
|
| 30 |
+
"infer_stop_tokens",
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
SENTINEL = "[VILA-SENTINEL]"
|
| 35 |
+
DUMMY_CONVERSATION = [
|
| 36 |
+
{"from": "human", "value": "question"},
|
| 37 |
+
{"from": "gpt", "value": "answer"},
|
| 38 |
+
] * 10
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def tokenize_conversation_legacy(
|
| 42 |
+
messages: Sequence[Dict[str, str]],
|
| 43 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
| 44 |
+
add_generation_prompt: bool = False,
|
| 45 |
+
overrides: Optional[Dict[str, str]] = None,
|
| 46 |
+
no_system_prompt: bool = False,
|
| 47 |
+
) -> torch.Tensor:
|
| 48 |
+
conv = conversation_lib.default_conversation.copy()
|
| 49 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
| 50 |
+
|
| 51 |
+
if no_system_prompt:
|
| 52 |
+
conv.system = ""
|
| 53 |
+
|
| 54 |
+
# Skip the first message if it is not from human
|
| 55 |
+
if messages[0]["from"] != "human":
|
| 56 |
+
messages = messages[1:]
|
| 57 |
+
|
| 58 |
+
# Add a generation prompt if needed
|
| 59 |
+
if add_generation_prompt:
|
| 60 |
+
messages.append({"from": "gpt", "value": None})
|
| 61 |
+
|
| 62 |
+
conv.messages = []
|
| 63 |
+
for turn, message in enumerate(messages):
|
| 64 |
+
role = roles[message["from"]]
|
| 65 |
+
assert role == conv.roles[turn % 2]
|
| 66 |
+
if overrides is not None and message["from"] in overrides:
|
| 67 |
+
conv.append_message(role, overrides[message["from"]])
|
| 68 |
+
else:
|
| 69 |
+
conv.append_message(role, message["value"])
|
| 70 |
+
|
| 71 |
+
return tokenizer_image_token(conv.get_prompt(), tokenizer, return_tensors="pt")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def tokenize_conversation(
|
| 75 |
+
messages: Sequence[Dict[str, str]],
|
| 76 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
| 77 |
+
add_generation_prompt: bool = False,
|
| 78 |
+
overrides: Optional[Dict[str, str]] = None,
|
| 79 |
+
no_system_prompt: bool = False,
|
| 80 |
+
) -> torch.Tensor:
|
| 81 |
+
if conversation_lib.default_conversation.sep_style != conversation_lib.SeparatorStyle.AUTO:
|
| 82 |
+
return tokenize_conversation_legacy(
|
| 83 |
+
messages,
|
| 84 |
+
tokenizer,
|
| 85 |
+
add_generation_prompt=add_generation_prompt,
|
| 86 |
+
overrides=overrides,
|
| 87 |
+
no_system_prompt=no_system_prompt,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
if no_system_prompt:
|
| 91 |
+
raise NotImplementedError("The `no_system_prompt` option is not supported by the current tokenizer.")
|
| 92 |
+
|
| 93 |
+
conversation = []
|
| 94 |
+
for m in messages:
|
| 95 |
+
message = {}
|
| 96 |
+
if m["from"] == "human":
|
| 97 |
+
message["role"] = "user"
|
| 98 |
+
elif m["from"] == "gpt":
|
| 99 |
+
message["role"] = "assistant"
|
| 100 |
+
else:
|
| 101 |
+
raise ValueError(f"Unexpected sender '{m['from']}' in conversation entry.")
|
| 102 |
+
|
| 103 |
+
message["content"] = m["value"]
|
| 104 |
+
if overrides is not None and m["from"] in overrides:
|
| 105 |
+
message["content"] = overrides[m["from"]]
|
| 106 |
+
conversation.append(message)
|
| 107 |
+
|
| 108 |
+
text = tokenizer.apply_chat_template(
|
| 109 |
+
conversation,
|
| 110 |
+
add_generation_prompt=add_generation_prompt,
|
| 111 |
+
tokenize=False,
|
| 112 |
+
)
|
| 113 |
+
return tokenizer_image_token(text, tokenizer, return_tensors="pt")
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def preprocess_conversation(
|
| 117 |
+
conversation: Sequence[Dict[str, str]],
|
| 118 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
| 119 |
+
no_system_prompt: bool = False,
|
| 120 |
+
) -> Dict[str, Any]:
|
| 121 |
+
inputs = tokenize_conversation(conversation, tokenizer, no_system_prompt=no_system_prompt)
|
| 122 |
+
labels = torch.ones_like(inputs) * IGNORE_INDEX
|
| 123 |
+
|
| 124 |
+
# Generate the template by replacing the assistant's response with a sentinel.
|
| 125 |
+
template = tokenize_conversation(
|
| 126 |
+
conversation, tokenizer, overrides={"gpt": SENTINEL}, no_system_prompt=no_system_prompt
|
| 127 |
+
)
|
| 128 |
+
sentinel = tokenizer(SENTINEL, add_special_tokens=False).input_ids
|
| 129 |
+
sentinel = torch.tensor(sentinel, dtype=template.dtype)
|
| 130 |
+
|
| 131 |
+
# Remove sentinel tokens from the template.
|
| 132 |
+
mask = torch.ones_like(template, dtype=torch.bool)
|
| 133 |
+
for k in range(template.size(0) - sentinel.size(0)):
|
| 134 |
+
if torch.equal(template[k : k + sentinel.size(0)], sentinel):
|
| 135 |
+
mask[k : k + sentinel.size(0) + 1] = False # +1 to include the stop token
|
| 136 |
+
template = template[mask]
|
| 137 |
+
|
| 138 |
+
# Match the tokenized conversation with the template (with no assistant's response).
|
| 139 |
+
# Every token that is not matched will be included in the label for training.
|
| 140 |
+
p = 0
|
| 141 |
+
for k in range(inputs.size(0)):
|
| 142 |
+
if p < template.size(0) and inputs[k] == template[p]:
|
| 143 |
+
p += 1
|
| 144 |
+
else:
|
| 145 |
+
labels[k] = inputs[k]
|
| 146 |
+
|
| 147 |
+
# Mask all tokens in the label if the template is not fully matched.
|
| 148 |
+
if p < template.size(0):
|
| 149 |
+
logging.warning("Failed to process the conversation. All tokens will be masked in the label.")
|
| 150 |
+
labels[:] = IGNORE_INDEX
|
| 151 |
+
|
| 152 |
+
return {"input_ids": inputs, "labels": labels}
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def infer_stop_tokens(tokenizer: transformers.PreTrainedTokenizer) -> List[str]:
|
| 156 |
+
template = tokenize_conversation(DUMMY_CONVERSATION, tokenizer, overrides={"gpt": SENTINEL})
|
| 157 |
+
sentinel = tokenizer(SENTINEL, add_special_tokens=False).input_ids
|
| 158 |
+
sentinel = torch.tensor(sentinel, dtype=template.dtype)
|
| 159 |
+
|
| 160 |
+
stop_tokens = {tokenizer.eos_token}
|
| 161 |
+
for k in range(template.size(0) - sentinel.size(0)):
|
| 162 |
+
if torch.equal(template[k : k + sentinel.size(0)], sentinel):
|
| 163 |
+
stop_token = tokenizer.decode(template[k + sentinel.size(0)])
|
| 164 |
+
stop_tokens.add(stop_token)
|
| 165 |
+
return list(stop_tokens)
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/utils/utils.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 NVIDIA CORPORATION & AFFILIATES
|
| 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 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 16 |
+
# This file is modified from https://github.com/haotian-liu/LLaVA/
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
import logging
|
| 20 |
+
import logging.handlers
|
| 21 |
+
import os
|
| 22 |
+
import sys
|
| 23 |
+
|
| 24 |
+
import requests
|
| 25 |
+
|
| 26 |
+
from llava.constants import LOGDIR
|
| 27 |
+
|
| 28 |
+
server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
|
| 29 |
+
moderation_msg = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN."
|
| 30 |
+
|
| 31 |
+
handler = None
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def build_logger(logger_name, logger_filename):
|
| 35 |
+
global handler
|
| 36 |
+
|
| 37 |
+
formatter = logging.Formatter(
|
| 38 |
+
fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
|
| 39 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
# Set the format of root handlers
|
| 43 |
+
if not logging.getLogger().handlers:
|
| 44 |
+
logging.basicConfig(level=logging.INFO)
|
| 45 |
+
logging.getLogger().handlers[0].setFormatter(formatter)
|
| 46 |
+
|
| 47 |
+
# Redirect stdout and stderr to loggers
|
| 48 |
+
stdout_logger = logging.getLogger("stdout")
|
| 49 |
+
stdout_logger.setLevel(logging.INFO)
|
| 50 |
+
sl = StreamToLogger(stdout_logger, logging.INFO)
|
| 51 |
+
sys.stdout = sl
|
| 52 |
+
|
| 53 |
+
stderr_logger = logging.getLogger("stderr")
|
| 54 |
+
stderr_logger.setLevel(logging.ERROR)
|
| 55 |
+
sl = StreamToLogger(stderr_logger, logging.ERROR)
|
| 56 |
+
sys.stderr = sl
|
| 57 |
+
|
| 58 |
+
# Get logger
|
| 59 |
+
logger = logging.getLogger(logger_name)
|
| 60 |
+
logger.setLevel(logging.INFO)
|
| 61 |
+
|
| 62 |
+
# Add a file handler for all loggers
|
| 63 |
+
if handler is None:
|
| 64 |
+
os.makedirs(LOGDIR, exist_ok=True)
|
| 65 |
+
filename = os.path.join(LOGDIR, logger_filename)
|
| 66 |
+
handler = logging.handlers.TimedRotatingFileHandler(filename, when="D", utc=True, encoding="UTF-8")
|
| 67 |
+
handler.setFormatter(formatter)
|
| 68 |
+
|
| 69 |
+
for name, item in logging.root.manager.loggerDict.items():
|
| 70 |
+
if isinstance(item, logging.Logger):
|
| 71 |
+
item.addHandler(handler)
|
| 72 |
+
|
| 73 |
+
return logger
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class StreamToLogger:
|
| 77 |
+
"""
|
| 78 |
+
Fake file-like stream object that redirects writes to a logger instance.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
def __init__(self, logger, log_level=logging.INFO):
|
| 82 |
+
self.terminal = sys.stdout
|
| 83 |
+
self.logger = logger
|
| 84 |
+
self.log_level = log_level
|
| 85 |
+
self.linebuf = ""
|
| 86 |
+
|
| 87 |
+
def __getattr__(self, attr):
|
| 88 |
+
return getattr(self.terminal, attr)
|
| 89 |
+
|
| 90 |
+
def write(self, buf):
|
| 91 |
+
temp_linebuf = self.linebuf + buf
|
| 92 |
+
self.linebuf = ""
|
| 93 |
+
for line in temp_linebuf.splitlines(True):
|
| 94 |
+
# From the io.TextIOWrapper docs:
|
| 95 |
+
# On output, if newline is None, any '\n' characters written
|
| 96 |
+
# are translated to the system default line separator.
|
| 97 |
+
# By default sys.stdout.write() expects '\n' newlines and then
|
| 98 |
+
# translates them so this is still cross platform.
|
| 99 |
+
if line[-1] == "\n":
|
| 100 |
+
self.logger.log(self.log_level, line.rstrip())
|
| 101 |
+
else:
|
| 102 |
+
self.linebuf += line
|
| 103 |
+
|
| 104 |
+
def flush(self):
|
| 105 |
+
if self.linebuf != "":
|
| 106 |
+
self.logger.log(self.log_level, self.linebuf.rstrip())
|
| 107 |
+
self.linebuf = ""
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def disable_torch_init():
|
| 111 |
+
"""
|
| 112 |
+
Disable the redundant torch default initialization to accelerate model creation.
|
| 113 |
+
"""
|
| 114 |
+
import torch
|
| 115 |
+
|
| 116 |
+
setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
|
| 117 |
+
setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def violates_moderation(text):
|
| 121 |
+
"""
|
| 122 |
+
Check whether the text violates OpenAI moderation API.
|
| 123 |
+
"""
|
| 124 |
+
url = "https://api.openai.com/v1/moderations"
|
| 125 |
+
headers = {"Content-Type": "application/json", "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]}
|
| 126 |
+
text = text.replace("\n", "")
|
| 127 |
+
data = "{" + '"input": ' + f'"{text}"' + "}"
|
| 128 |
+
data = data.encode("utf-8")
|
| 129 |
+
try:
|
| 130 |
+
ret = requests.post(url, headers=headers, data=data, timeout=5)
|
| 131 |
+
flagged = ret.json()["results"][0]["flagged"]
|
| 132 |
+
except requests.exceptions.RequestException:
|
| 133 |
+
flagged = False
|
| 134 |
+
except KeyError:
|
| 135 |
+
flagged = False
|
| 136 |
+
|
| 137 |
+
return flagged
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def pretty_print_semaphore(semaphore):
|
| 141 |
+
if semaphore is None:
|
| 142 |
+
return "None"
|
| 143 |
+
return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})"
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2017-2019 NVIDIA CORPORATION. All rights reserved.
|
| 2 |
+
# This file is part of the WebDataset library.
|
| 3 |
+
# See the LICENSE file for licensing terms (BSD-style).
|
| 4 |
+
#
|
| 5 |
+
# flake8: noqa
|
| 6 |
+
|
| 7 |
+
from .wids import ChunkedSampler, DistributedChunkedSampler, DistributedLocalSampler, ShardedSampler, ShardListDataset
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids.py
ADDED
|
@@ -0,0 +1,825 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import gzip
|
| 3 |
+
import hashlib
|
| 4 |
+
import io
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
import os.path as osp
|
| 8 |
+
import random
|
| 9 |
+
import re
|
| 10 |
+
import sqlite3
|
| 11 |
+
import sys
|
| 12 |
+
import tempfile
|
| 13 |
+
import uuid
|
| 14 |
+
import warnings
|
| 15 |
+
from functools import partial
|
| 16 |
+
from typing import Any, BinaryIO, Dict, Optional, TypeVar, Union
|
| 17 |
+
from urllib.parse import quote, urlparse
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
import torch.distributed as dist
|
| 22 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 23 |
+
|
| 24 |
+
from .wids_dl import download_and_open
|
| 25 |
+
from .wids_lru import LRUCache
|
| 26 |
+
from .wids_mmtar import MMIndexedTar
|
| 27 |
+
from .wids_specs import load_dsdesc_and_resolve, urldir
|
| 28 |
+
from .wids_tar import TarFileReader, find_index_file
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
from torch.utils.data import Dataset, Sampler
|
| 32 |
+
except ImportError:
|
| 33 |
+
|
| 34 |
+
class Dataset:
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
class Sampler:
|
| 38 |
+
pass
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
T = TypeVar("T")
|
| 42 |
+
|
| 43 |
+
T_co = TypeVar("T_co", covariant=True)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def compute_file_md5sum(fname: Union[str, BinaryIO], chunksize: int = 1000000) -> str:
|
| 47 |
+
"""Compute the md5sum of a file in chunks.
|
| 48 |
+
|
| 49 |
+
Parameters
|
| 50 |
+
----------
|
| 51 |
+
fname : Union[str, BinaryIO]
|
| 52 |
+
Filename or file object
|
| 53 |
+
chunksize : int, optional
|
| 54 |
+
Chunk size in bytes, by default 1000000
|
| 55 |
+
|
| 56 |
+
Returns
|
| 57 |
+
-------
|
| 58 |
+
str
|
| 59 |
+
MD5 sum of the file
|
| 60 |
+
|
| 61 |
+
Examples
|
| 62 |
+
--------
|
| 63 |
+
>>> compute_file_md5sum("test.txt")
|
| 64 |
+
'd41d8cd98f00b204e9800998ecf8427e'
|
| 65 |
+
"""
|
| 66 |
+
md5 = hashlib.md5()
|
| 67 |
+
if isinstance(fname, str):
|
| 68 |
+
with open(fname, "rb") as f:
|
| 69 |
+
for chunk in iter(lambda: f.read(chunksize), b""):
|
| 70 |
+
md5.update(chunk)
|
| 71 |
+
else:
|
| 72 |
+
fname.seek(0)
|
| 73 |
+
for chunk in iter(lambda: fname.read(chunksize), b""):
|
| 74 |
+
md5.update(chunk)
|
| 75 |
+
return md5.hexdigest()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def compute_file_md5sum(fname: Union[str, BinaryIO], chunksize: int = 1000000) -> str:
|
| 79 |
+
"""Compute the md5sum of a file in chunks."""
|
| 80 |
+
md5 = hashlib.md5()
|
| 81 |
+
if isinstance(fname, str):
|
| 82 |
+
with open(fname, "rb") as f:
|
| 83 |
+
for chunk in iter(lambda: f.read(chunksize), b""):
|
| 84 |
+
md5.update(chunk)
|
| 85 |
+
else:
|
| 86 |
+
fname.seek(0)
|
| 87 |
+
for chunk in iter(lambda: fname.read(chunksize), b""):
|
| 88 |
+
md5.update(chunk)
|
| 89 |
+
return md5.hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def compute_num_samples(fname):
|
| 93 |
+
ds = IndexedTarSamples(fname)
|
| 94 |
+
return len(ds)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def splitname(fname):
|
| 98 |
+
"""Returns the basename and extension of a filename"""
|
| 99 |
+
assert "." in fname, "Filename must have an extension"
|
| 100 |
+
# basename, extension = re.match(r"^((?:.*/)?.*?)(\..*)$", fname).groups()
|
| 101 |
+
basename, extension = os.path.splitext(fname)
|
| 102 |
+
return basename, extension
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# NOTE(ligeng): change to ordered mapping to more flexbile dict
|
| 106 |
+
# TODO(ligeng): submit a PR to fix the mapping issue.
|
| 107 |
+
def group_by_key(names):
|
| 108 |
+
"""Group the file names by key.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
names: A list of file names.
|
| 112 |
+
|
| 113 |
+
Returns:
|
| 114 |
+
A list of lists of indices, where each sublist contains indices of files
|
| 115 |
+
with the same key.
|
| 116 |
+
"""
|
| 117 |
+
groups = []
|
| 118 |
+
kmaps = {}
|
| 119 |
+
for i, fname in enumerate(names):
|
| 120 |
+
# Ignore files that are not in a subdirectory.
|
| 121 |
+
if "." not in fname:
|
| 122 |
+
print(f"Warning: Ignoring file {fname} (no '.')")
|
| 123 |
+
continue
|
| 124 |
+
if fname == ".":
|
| 125 |
+
print(f"Warning: Ignoring the '.' file.")
|
| 126 |
+
continue
|
| 127 |
+
key, ext = splitname(fname)
|
| 128 |
+
if key not in kmaps:
|
| 129 |
+
kmaps[key] = []
|
| 130 |
+
kmaps[key].append(i)
|
| 131 |
+
for k, v in kmaps.items():
|
| 132 |
+
groups.append(v)
|
| 133 |
+
return groups
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def default_decoder(sample: Dict[str, Any], format: Optional[Union[bool, str]] = True):
|
| 137 |
+
"""A default decoder for webdataset.
|
| 138 |
+
|
| 139 |
+
This handles common file extensions: .txt, .cls, .cls2,
|
| 140 |
+
.jpg, .png, .json, .npy, .mp, .pt, .pth, .pickle, .pkl.
|
| 141 |
+
These are the most common extensions used in webdataset.
|
| 142 |
+
For other extensions, users can provide their own decoder.
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
sample: sample, modified in place
|
| 146 |
+
"""
|
| 147 |
+
sample = dict(sample)
|
| 148 |
+
for key, stream in sample.items():
|
| 149 |
+
extensions = key.split(".")
|
| 150 |
+
if len(extensions) < 1:
|
| 151 |
+
continue
|
| 152 |
+
extension = extensions[-1]
|
| 153 |
+
if extension in ["gz"]:
|
| 154 |
+
decompressed = gzip.decompress(stream.read())
|
| 155 |
+
stream = io.BytesIO(decompressed)
|
| 156 |
+
if len(extensions) < 2:
|
| 157 |
+
sample[key] = stream
|
| 158 |
+
continue
|
| 159 |
+
extension = extensions[-2]
|
| 160 |
+
if key.startswith("__"):
|
| 161 |
+
continue
|
| 162 |
+
elif extension in ["txt", "text"]:
|
| 163 |
+
value = stream.read()
|
| 164 |
+
sample[key] = value.decode("utf-8")
|
| 165 |
+
elif extension in ["cls", "cls2"]:
|
| 166 |
+
value = stream.read()
|
| 167 |
+
sample[key] = int(value.decode("utf-8"))
|
| 168 |
+
elif extension in ["jpg", "png", "ppm", "pgm", "pbm", "pnm"]:
|
| 169 |
+
if format == "PIL":
|
| 170 |
+
import PIL.Image
|
| 171 |
+
|
| 172 |
+
sample[key] = PIL.Image.open(stream)
|
| 173 |
+
elif format == "numpy":
|
| 174 |
+
import numpy as np
|
| 175 |
+
|
| 176 |
+
sample[key] = np.asarray(PIL.Image.open(stream))
|
| 177 |
+
else:
|
| 178 |
+
raise ValueError(f"Unknown format: {format}")
|
| 179 |
+
elif extension == "json":
|
| 180 |
+
import json
|
| 181 |
+
|
| 182 |
+
value = stream.read()
|
| 183 |
+
sample[key] = json.loads(value)
|
| 184 |
+
elif extension == "npy":
|
| 185 |
+
import numpy as np
|
| 186 |
+
|
| 187 |
+
sample[key] = np.load(stream)
|
| 188 |
+
elif extension == "mp":
|
| 189 |
+
import msgpack
|
| 190 |
+
|
| 191 |
+
value = stream.read()
|
| 192 |
+
sample[key] = msgpack.unpackb(value, raw=False)
|
| 193 |
+
elif extension in ["pt", "pth"]:
|
| 194 |
+
import torch
|
| 195 |
+
|
| 196 |
+
sample[key] = torch.load(stream)
|
| 197 |
+
elif extension in ["pickle", "pkl"]:
|
| 198 |
+
import pickle
|
| 199 |
+
|
| 200 |
+
sample[key] = pickle.load(stream)
|
| 201 |
+
elif extension == "mp4":
|
| 202 |
+
# Write stream to a temporary file
|
| 203 |
+
# with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmpfile:
|
| 204 |
+
# tmpfile.write(stream.read())
|
| 205 |
+
# tmpfile_path = tmpfile.name
|
| 206 |
+
|
| 207 |
+
# sample[key] = tmpfile_path
|
| 208 |
+
sample[key] = io.BytesIO(stream.read())
|
| 209 |
+
return sample
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
open_itfs = {}
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class IndexedTarSamples:
|
| 216 |
+
"""A class that accesses samples in a tar file. The tar file must follow
|
| 217 |
+
WebDataset conventions. The tar file is indexed when the IndexedTarSamples
|
| 218 |
+
object is created. The samples are accessed by index using the __getitem__
|
| 219 |
+
method. The __getitem__ method returns a dictionary containing the files
|
| 220 |
+
for the sample. The key for each file is the extension of the file name.
|
| 221 |
+
The key "__key__" is reserved for the key of the sample (the basename of
|
| 222 |
+
each file without the extension). For example, if the tar file contains
|
| 223 |
+
the files "sample1.jpg" and "sample1.txt", then the sample with key
|
| 224 |
+
"sample1" will be returned as the dictionary {"jpg": ..., "txt": ...}.
|
| 225 |
+
"""
|
| 226 |
+
|
| 227 |
+
def __init__(
|
| 228 |
+
self,
|
| 229 |
+
*,
|
| 230 |
+
path=None,
|
| 231 |
+
stream=None,
|
| 232 |
+
md5sum=None,
|
| 233 |
+
expected_size=None,
|
| 234 |
+
use_mmap=True,
|
| 235 |
+
index_file=find_index_file,
|
| 236 |
+
):
|
| 237 |
+
assert path is not None or stream is not None
|
| 238 |
+
|
| 239 |
+
# Create TarFileReader object to read from tar_file
|
| 240 |
+
self.path = path
|
| 241 |
+
stream = self.stream = stream or open(path, "rb")
|
| 242 |
+
|
| 243 |
+
# verify the MD5 sum
|
| 244 |
+
if md5sum is not None:
|
| 245 |
+
stream.seek(0)
|
| 246 |
+
got = compute_file_md5sum(stream)
|
| 247 |
+
assert got == md5sum, f"MD5 sum mismatch: expected {md5sum}, got {got}"
|
| 248 |
+
stream.seek(0)
|
| 249 |
+
|
| 250 |
+
# use either the mmap or the stream based implementation
|
| 251 |
+
# NOTE(ligeng): https://stackoverflow.com/questions/11072705/twitter-trends-api-unicodedecodeerror-utf8-codec-cant-decode-byte-0x8b-in-po
|
| 252 |
+
# import gzip
|
| 253 |
+
# print("convert to gzip IO stream")
|
| 254 |
+
# stream = gzip.GzipFile(fileobj=stream)
|
| 255 |
+
|
| 256 |
+
if use_mmap:
|
| 257 |
+
self.reader = MMIndexedTar(stream)
|
| 258 |
+
else:
|
| 259 |
+
self.reader = TarFileReader(stream, index_file=index_file)
|
| 260 |
+
|
| 261 |
+
# Get list of all files in stream
|
| 262 |
+
all_files = self.reader.names()
|
| 263 |
+
|
| 264 |
+
# Group files by key into samples
|
| 265 |
+
self.samples = group_by_key(all_files)
|
| 266 |
+
# print("DEBUG:", list(all_files)[:20])
|
| 267 |
+
# print("DEBUG:", self.samples[:20])
|
| 268 |
+
|
| 269 |
+
# check that the number of samples is correct
|
| 270 |
+
if expected_size is not None:
|
| 271 |
+
assert len(self) == expected_size, f"Expected {expected_size} samples, got {len(self)}"
|
| 272 |
+
|
| 273 |
+
self.uuid = str(uuid.uuid4())
|
| 274 |
+
|
| 275 |
+
def close(self):
|
| 276 |
+
self.reader.close()
|
| 277 |
+
if not self.stream.closed:
|
| 278 |
+
self.stream.close()
|
| 279 |
+
|
| 280 |
+
def __len__(self):
|
| 281 |
+
return len(self.samples)
|
| 282 |
+
|
| 283 |
+
def __getitem__(self, idx):
|
| 284 |
+
# Get indexes of files for the sample at index idx
|
| 285 |
+
try:
|
| 286 |
+
indexes = self.samples[idx]
|
| 287 |
+
except IndexError as e:
|
| 288 |
+
print(f"[wids-debug] curr idx: {idx}, total sample length: {len(self.samples)} {e}")
|
| 289 |
+
raise e
|
| 290 |
+
sample = {}
|
| 291 |
+
key = None
|
| 292 |
+
for i in indexes:
|
| 293 |
+
# Get filename and data for the file at index i
|
| 294 |
+
fname, data = self.reader.get_file(i)
|
| 295 |
+
# Split filename into key and extension
|
| 296 |
+
k, ext = splitname(fname)
|
| 297 |
+
# Make sure all files in sample have same key
|
| 298 |
+
key = key or k
|
| 299 |
+
assert key == k
|
| 300 |
+
sample[ext] = data
|
| 301 |
+
# Add key to sample
|
| 302 |
+
sample["__key__"] = key
|
| 303 |
+
return sample
|
| 304 |
+
|
| 305 |
+
def __str__(self):
|
| 306 |
+
return f"<IndexedTarSamples-{id(self)} {self.path}>"
|
| 307 |
+
|
| 308 |
+
def __repr__(self):
|
| 309 |
+
return str(self)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def hash_localname(dldir="/tmp/_wids_cache"):
|
| 313 |
+
os.makedirs(dldir, exist_ok=True)
|
| 314 |
+
|
| 315 |
+
connection = sqlite3.connect(os.path.join(dldir, "cache.db"))
|
| 316 |
+
cursor = connection.cursor()
|
| 317 |
+
cursor.execute("CREATE TABLE IF NOT EXISTS cache (url TEXT PRIMARY KEY, path TEXT, checksum TEXT)")
|
| 318 |
+
connection.commit()
|
| 319 |
+
|
| 320 |
+
def f(shard):
|
| 321 |
+
"""Given a URL, return a local name for the shard."""
|
| 322 |
+
if shard.startswith("pipe:"):
|
| 323 |
+
# uuencode the entire URL string
|
| 324 |
+
hex32 = base64.urlsafe_b64encode(hashlib.sha256(shard.encode()).digest())[:32].decode()
|
| 325 |
+
return os.path.join(dldir, "pipe__" + hex32)
|
| 326 |
+
else:
|
| 327 |
+
# we hash the host and directory components into a 16 character string
|
| 328 |
+
dirname = urldir(shard)
|
| 329 |
+
hex16 = base64.urlsafe_b64encode(hashlib.sha256(dirname.encode()).digest())[:16].decode()
|
| 330 |
+
# the cache name is the concatenation of the hex16 string and the file name component of the URL
|
| 331 |
+
cachename = "data__" + hex16 + "__" + os.path.basename(urlparse(shard).path)
|
| 332 |
+
checksum = None
|
| 333 |
+
cursor.execute(
|
| 334 |
+
"INSERT OR REPLACE INTO cache VALUES (?, ?, ?)",
|
| 335 |
+
(shard, cachename, checksum),
|
| 336 |
+
)
|
| 337 |
+
connection.commit()
|
| 338 |
+
return os.path.join(dldir, cachename)
|
| 339 |
+
|
| 340 |
+
return f
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def cache_localname(cachedir):
|
| 344 |
+
os.makedirs(cachedir, exist_ok=True)
|
| 345 |
+
|
| 346 |
+
def f(shard):
|
| 347 |
+
"""Given a URL, return a local name for the shard."""
|
| 348 |
+
path = urlparse(shard).path
|
| 349 |
+
fname = os.path.basename(path)
|
| 350 |
+
return os.path.join(cachedir, fname)
|
| 351 |
+
|
| 352 |
+
return f
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def default_localname(dldir="/tmp/_wids_cache"):
|
| 356 |
+
os.makedirs(dldir, exist_ok=True)
|
| 357 |
+
|
| 358 |
+
def f(shard):
|
| 359 |
+
"""Given a URL, return a local name for the shard."""
|
| 360 |
+
cachename = quote(shard, safe="+-")
|
| 361 |
+
return os.path.join(dldir, cachename)
|
| 362 |
+
|
| 363 |
+
return f
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
class LRUShards:
|
| 367 |
+
"""A class that manages a cache of shards. The cache is a LRU cache that
|
| 368 |
+
stores the local names of the shards as keys and the downloaded paths as
|
| 369 |
+
values. The shards are downloaded to a directory specified by dldir.
|
| 370 |
+
The local name of a shard is computed by the localname function, which
|
| 371 |
+
takes the shard URL as an argument. If keep is True, the downloaded files
|
| 372 |
+
are not deleted when they are no longer needed.
|
| 373 |
+
"""
|
| 374 |
+
|
| 375 |
+
def __init__(self, lru_size, keep=False, localname=default_localname()):
|
| 376 |
+
self.localname = localname
|
| 377 |
+
# the cache contains the local name as the key and the downloaded path as the value
|
| 378 |
+
self.lru = LRUCache(lru_size, release_handler=self.release_handler)
|
| 379 |
+
# keep statistics
|
| 380 |
+
self.reset_stats()
|
| 381 |
+
|
| 382 |
+
def reset_stats(self):
|
| 383 |
+
self.accesses = 0
|
| 384 |
+
self.misses = 0
|
| 385 |
+
|
| 386 |
+
def __len__(self):
|
| 387 |
+
return len(self.lru)
|
| 388 |
+
|
| 389 |
+
def release_handler(self, key, value):
|
| 390 |
+
value.close()
|
| 391 |
+
|
| 392 |
+
def clear(self):
|
| 393 |
+
self.lru.clear()
|
| 394 |
+
|
| 395 |
+
def get_shard(self, url):
|
| 396 |
+
assert isinstance(url, str)
|
| 397 |
+
self.accesses += 1
|
| 398 |
+
if url not in self.lru:
|
| 399 |
+
local = self.localname(url)
|
| 400 |
+
with download_and_open(url, local) as stream:
|
| 401 |
+
itf = IndexedTarSamples(path=local, stream=stream)
|
| 402 |
+
self.lru[url] = itf
|
| 403 |
+
self.misses += 1
|
| 404 |
+
self.last_missed = True
|
| 405 |
+
else:
|
| 406 |
+
self.last_missed = False
|
| 407 |
+
return self.lru[url]
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def interpret_transformations(transformations):
|
| 411 |
+
"""Interpret the transformations argument.
|
| 412 |
+
|
| 413 |
+
This takes care of transformations specified as string shortcuts
|
| 414 |
+
and returns a list of callables.
|
| 415 |
+
"""
|
| 416 |
+
if not isinstance(transformations, list):
|
| 417 |
+
transformations = [transformations]
|
| 418 |
+
|
| 419 |
+
result = []
|
| 420 |
+
|
| 421 |
+
for transformation in transformations:
|
| 422 |
+
if transformation == "PIL":
|
| 423 |
+
transformation = partial(default_decoder, format="PIL")
|
| 424 |
+
elif transformation == "numpy":
|
| 425 |
+
transformation = partial(default_decoder, format="numpy")
|
| 426 |
+
else:
|
| 427 |
+
assert callable(transformation)
|
| 428 |
+
result.append(transformation)
|
| 429 |
+
|
| 430 |
+
return result
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def hash_dataset_name(input_string):
|
| 434 |
+
"""Compute a hash of the input string and return the first 16 characters of the hash."""
|
| 435 |
+
# Compute SHA256 hash of the input string
|
| 436 |
+
hash_object = hashlib.sha256(input_string.encode())
|
| 437 |
+
hash_digest = hash_object.digest()
|
| 438 |
+
|
| 439 |
+
# Encode the hash in base64
|
| 440 |
+
base64_encoded_hash = base64.urlsafe_b64encode(hash_digest)
|
| 441 |
+
|
| 442 |
+
# Return the first 16 characters of the base64-encoded hash
|
| 443 |
+
return base64_encoded_hash[:16].decode("ascii")
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
class ShardListDataset(Dataset[T]):
|
| 447 |
+
"""An indexable dataset based on a list of shards.
|
| 448 |
+
|
| 449 |
+
The dataset is either given as a list of shards with optional options and name,
|
| 450 |
+
or as a URL pointing to a JSON descriptor file.
|
| 451 |
+
|
| 452 |
+
Datasets can reference other datasets via `source_url`.
|
| 453 |
+
|
| 454 |
+
Shard references within a dataset are resolve relative to an explicitly
|
| 455 |
+
given `base` property, or relative to the URL from which the dataset
|
| 456 |
+
descriptor was loaded.
|
| 457 |
+
"""
|
| 458 |
+
|
| 459 |
+
def __init__(
|
| 460 |
+
self,
|
| 461 |
+
shards,
|
| 462 |
+
*,
|
| 463 |
+
cache_size=int(1e12),
|
| 464 |
+
cache_dir=None,
|
| 465 |
+
lru_size=10,
|
| 466 |
+
dataset_name=None,
|
| 467 |
+
localname=None,
|
| 468 |
+
transformations="PIL",
|
| 469 |
+
keep=False,
|
| 470 |
+
base=None,
|
| 471 |
+
options=None,
|
| 472 |
+
):
|
| 473 |
+
"""Create a ShardListDataset.
|
| 474 |
+
|
| 475 |
+
Args:
|
| 476 |
+
shards: a list of (filename, length) pairs or a URL pointing to a JSON descriptor file
|
| 477 |
+
cache_size: the number of shards to keep in the cache
|
| 478 |
+
lru_size: the number of shards to keep in the LRU cache
|
| 479 |
+
localname: a function that maps URLs to local filenames
|
| 480 |
+
|
| 481 |
+
Note that there are two caches: an on-disk directory, and an in-memory LRU cache.
|
| 482 |
+
"""
|
| 483 |
+
if options is None:
|
| 484 |
+
options = {}
|
| 485 |
+
super().__init__()
|
| 486 |
+
# shards is a list of (filename, length) pairs. We'll need to
|
| 487 |
+
# keep track of the lengths and cumulative lengths to know how
|
| 488 |
+
# to map indices to shards and indices within shards.
|
| 489 |
+
if isinstance(shards, (str, io.IOBase)):
|
| 490 |
+
if base is None and isinstance(shards, str):
|
| 491 |
+
shards = osp.expanduser(shards)
|
| 492 |
+
base = urldir(shards)
|
| 493 |
+
self.base = base
|
| 494 |
+
self.spec = load_dsdesc_and_resolve(shards, options=options, base=base)
|
| 495 |
+
self.shards = self.spec.get("shardlist", [])
|
| 496 |
+
self.dataset_name = self.spec.get("name") or hash_dataset_name(str(shards))
|
| 497 |
+
else:
|
| 498 |
+
raise NotImplementedError("Only support taking path/url to JSON descriptor file.")
|
| 499 |
+
self.base = None
|
| 500 |
+
self.spec = options
|
| 501 |
+
self.shards = shards
|
| 502 |
+
self.dataset_name = dataset_name or hash_dataset_name(str(shards))
|
| 503 |
+
|
| 504 |
+
self.lengths = [shard["nsamples"] for shard in self.shards]
|
| 505 |
+
self.cum_lengths = np.cumsum(self.lengths)
|
| 506 |
+
self.total_length = self.cum_lengths[-1]
|
| 507 |
+
|
| 508 |
+
if cache_dir is not None:
|
| 509 |
+
# when a cache dir is explicitly given, we download files into
|
| 510 |
+
# that directory without any changes
|
| 511 |
+
self.cache_dir = cache_dir
|
| 512 |
+
self.localname = cache_localname(cache_dir)
|
| 513 |
+
elif localname is not None:
|
| 514 |
+
# when a localname function is given, we use that
|
| 515 |
+
self.cache_dir = None
|
| 516 |
+
self.localname = localname
|
| 517 |
+
else:
|
| 518 |
+
import getpass
|
| 519 |
+
|
| 520 |
+
# when no cache dir or localname are given, use the cache from the environment
|
| 521 |
+
self.cache_dir = os.environ.get("WIDS_CACHE", f"~/.cache/_wids_cache")
|
| 522 |
+
self.cache_dir = osp.expanduser(self.cache_dir)
|
| 523 |
+
self.localname = default_localname(self.cache_dir)
|
| 524 |
+
|
| 525 |
+
if True or int(os.environ.get("WIDS_VERBOSE", 0)):
|
| 526 |
+
nbytes = sum(shard.get("filesize", 0) for shard in self.shards)
|
| 527 |
+
nsamples = sum(shard["nsamples"] for shard in self.shards)
|
| 528 |
+
print(
|
| 529 |
+
"[WebShardedList]",
|
| 530 |
+
str(shards),
|
| 531 |
+
"base:",
|
| 532 |
+
self.base,
|
| 533 |
+
"name:",
|
| 534 |
+
self.spec.get("name"),
|
| 535 |
+
"nfiles:",
|
| 536 |
+
len(self.shards),
|
| 537 |
+
"nbytes:",
|
| 538 |
+
nbytes,
|
| 539 |
+
"samples:",
|
| 540 |
+
nsamples,
|
| 541 |
+
"cache:",
|
| 542 |
+
self.cache_dir,
|
| 543 |
+
file=sys.stderr,
|
| 544 |
+
)
|
| 545 |
+
self.transformations = interpret_transformations(transformations)
|
| 546 |
+
|
| 547 |
+
if lru_size > 200:
|
| 548 |
+
warnings.warn("LRU size is very large; consider reducing it to avoid running out of file descriptors")
|
| 549 |
+
self.cache = LRUShards(lru_size, localname=self.localname, keep=keep)
|
| 550 |
+
|
| 551 |
+
def add_transform(self, transform):
|
| 552 |
+
"""Add a transformation to the dataset."""
|
| 553 |
+
self.transformations.append(transform)
|
| 554 |
+
return self
|
| 555 |
+
|
| 556 |
+
def __len__(self):
|
| 557 |
+
"""Return the total number of samples in the dataset."""
|
| 558 |
+
return self.total_length
|
| 559 |
+
|
| 560 |
+
def get_stats(self):
|
| 561 |
+
"""Return the number of cache accesses and misses."""
|
| 562 |
+
return self.cache.accesses, self.cache.misses
|
| 563 |
+
|
| 564 |
+
def check_cache_misses(self):
|
| 565 |
+
"""Check if the cache miss rate is too high."""
|
| 566 |
+
accesses, misses = self.get_stats()
|
| 567 |
+
if accesses > 100 and misses / accesses > 0.3:
|
| 568 |
+
# output a warning only once
|
| 569 |
+
self.check_cache_misses = lambda: None
|
| 570 |
+
print(f"Warning: ShardListDataset has a cache miss rate of {misses * 100.0 / accesses:.1%}%")
|
| 571 |
+
|
| 572 |
+
def get_shard(self, index):
|
| 573 |
+
"""Get the shard and index within the shard corresponding to the given index."""
|
| 574 |
+
# Find the shard corresponding to the given index.
|
| 575 |
+
shard_idx = np.searchsorted(self.cum_lengths, index, side="right")
|
| 576 |
+
|
| 577 |
+
# Figure out which index within the shard corresponds to the
|
| 578 |
+
# given index.
|
| 579 |
+
if shard_idx == 0:
|
| 580 |
+
inner_idx = index
|
| 581 |
+
else:
|
| 582 |
+
inner_idx = index - self.cum_lengths[shard_idx - 1]
|
| 583 |
+
|
| 584 |
+
# Get the shard and return the corresponding element.
|
| 585 |
+
desc = self.shards[shard_idx]
|
| 586 |
+
url = desc["url"]
|
| 587 |
+
if url.startswith(("https://", "http://", "gs://", "/", "~")):
|
| 588 |
+
# absolute path or url path
|
| 589 |
+
url = url
|
| 590 |
+
else:
|
| 591 |
+
# concat relative path
|
| 592 |
+
if self.base is None and "base_path" not in self.spec:
|
| 593 |
+
raise FileNotFoundError("passing a relative path in shardlist but no base found.")
|
| 594 |
+
base_path = self.spec["base_path"] if "base_path" in self.spec else self.base
|
| 595 |
+
url = osp.abspath(osp.join(osp.expanduser(base_path), url))
|
| 596 |
+
|
| 597 |
+
desc["url"] = url
|
| 598 |
+
try:
|
| 599 |
+
shard = self.cache.get_shard(url)
|
| 600 |
+
except UnicodeDecodeError as e:
|
| 601 |
+
print("UnicodeDecodeError:", desc)
|
| 602 |
+
raise e
|
| 603 |
+
return shard, inner_idx, desc
|
| 604 |
+
|
| 605 |
+
def __getitem__(self, index):
|
| 606 |
+
"""Return the sample corresponding to the given index."""
|
| 607 |
+
shard, inner_idx, desc = self.get_shard(index)
|
| 608 |
+
sample = shard[inner_idx]
|
| 609 |
+
|
| 610 |
+
# Check if we're missing the cache too often.
|
| 611 |
+
self.check_cache_misses()
|
| 612 |
+
|
| 613 |
+
sample["__dataset__"] = desc.get("dataset")
|
| 614 |
+
sample["__index__"] = index
|
| 615 |
+
sample["__shard__"] = desc["url"]
|
| 616 |
+
sample["__shardindex__"] = inner_idx
|
| 617 |
+
|
| 618 |
+
# Apply transformations
|
| 619 |
+
for transform in self.transformations:
|
| 620 |
+
sample = transform(sample)
|
| 621 |
+
|
| 622 |
+
return sample
|
| 623 |
+
|
| 624 |
+
def close(self):
|
| 625 |
+
"""Close the dataset."""
|
| 626 |
+
self.cache.clear()
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def lengths_to_ranges(lengths):
|
| 630 |
+
"""Convert a list of lengths to a list of ranges."""
|
| 631 |
+
ranges = []
|
| 632 |
+
start = 0
|
| 633 |
+
for length in lengths:
|
| 634 |
+
ranges.append((start, start + length))
|
| 635 |
+
start += length
|
| 636 |
+
return ranges
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def intersect_range(a, b):
|
| 640 |
+
"""Return the intersection of the two half-open integer intervals."""
|
| 641 |
+
result = max(a[0], b[0]), min(a[1], b[1])
|
| 642 |
+
if result[0] >= result[1]:
|
| 643 |
+
return None
|
| 644 |
+
return result
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def intersect_ranges(rangelist, r):
|
| 648 |
+
"""Return the intersection of the half-open integer interval r with the list of half-open integer intervals."""
|
| 649 |
+
result = []
|
| 650 |
+
for a in rangelist:
|
| 651 |
+
x = intersect_range(a, r)
|
| 652 |
+
if x is not None:
|
| 653 |
+
result.append(x)
|
| 654 |
+
return result
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
def iterate_ranges(ranges, rng, indexshuffle=True, shardshuffle=True):
|
| 658 |
+
"""Iterate over the ranges in a random order."""
|
| 659 |
+
shard_indexes = list(range(len(ranges)))
|
| 660 |
+
if shardshuffle:
|
| 661 |
+
rng.shuffle(shard_indexes)
|
| 662 |
+
for i in shard_indexes:
|
| 663 |
+
lo, hi = ranges[i]
|
| 664 |
+
sample_indexes = list(range(lo, hi))
|
| 665 |
+
if indexshuffle:
|
| 666 |
+
rng.shuffle(sample_indexes)
|
| 667 |
+
yield from sample_indexes
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
class ShardListSampler(Sampler):
|
| 671 |
+
"""A sampler that samples consistent with a ShardListDataset.
|
| 672 |
+
|
| 673 |
+
This sampler is used to sample from a ShardListDataset in a way that
|
| 674 |
+
preserves locality.
|
| 675 |
+
|
| 676 |
+
This returns a permutation of the indexes by shard, then a permutation of
|
| 677 |
+
indexes within each shard. This ensures that the data is accessed in a
|
| 678 |
+
way that preserves locality.
|
| 679 |
+
|
| 680 |
+
Note that how this ends up splitting data between multiple workers ends up
|
| 681 |
+
on the details of the DataLoader. Generally, it will likely load samples from the
|
| 682 |
+
same shard in each worker.
|
| 683 |
+
|
| 684 |
+
Other more sophisticated shard-aware samplers are possible and will likely
|
| 685 |
+
be added.
|
| 686 |
+
"""
|
| 687 |
+
|
| 688 |
+
def __init__(self, dataset, *, lengths=None, seed=0, shufflefirst=False):
|
| 689 |
+
if lengths is None:
|
| 690 |
+
lengths = list(dataset.lengths)
|
| 691 |
+
self.ranges = lengths_to_ranges(lengths)
|
| 692 |
+
self.seed = seed
|
| 693 |
+
self.shufflefirst = shufflefirst
|
| 694 |
+
self.epoch = 0
|
| 695 |
+
|
| 696 |
+
def __iter__(self):
|
| 697 |
+
self.rng = random.Random(self.seed + 1289738273 * self.epoch)
|
| 698 |
+
shardshuffle = self.shufflefirst or self.epoch > 0
|
| 699 |
+
yield from iterate_ranges(self.ranges, self.rng, shardshuffle=shardshuffle)
|
| 700 |
+
self.epoch += 1
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
ShardedSampler = ShardListSampler
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
class ChunkedSampler(Sampler):
|
| 707 |
+
"""A sampler that samples in chunks and then shuffles the samples within each chunk.
|
| 708 |
+
|
| 709 |
+
This preserves locality of reference while still shuffling the data.
|
| 710 |
+
"""
|
| 711 |
+
|
| 712 |
+
def __init__(
|
| 713 |
+
self,
|
| 714 |
+
dataset,
|
| 715 |
+
*,
|
| 716 |
+
num_samples=None,
|
| 717 |
+
chunksize=2000,
|
| 718 |
+
seed=0,
|
| 719 |
+
shuffle=False,
|
| 720 |
+
shufflefirst=False,
|
| 721 |
+
):
|
| 722 |
+
if isinstance(num_samples, int):
|
| 723 |
+
lo, hi = 0, num_samples
|
| 724 |
+
elif num_samples is None:
|
| 725 |
+
lo, hi = 0, len(dataset)
|
| 726 |
+
else:
|
| 727 |
+
lo, hi = num_samples
|
| 728 |
+
self.ranges = [(i, min(i + chunksize, hi)) for i in range(lo, hi, chunksize)]
|
| 729 |
+
self.seed = seed
|
| 730 |
+
self.shuffle = shuffle
|
| 731 |
+
self.shufflefirst = shufflefirst
|
| 732 |
+
self.epoch = 0
|
| 733 |
+
|
| 734 |
+
def set_epoch(self, epoch):
|
| 735 |
+
self.epoch = epoch
|
| 736 |
+
|
| 737 |
+
def __iter__(self):
|
| 738 |
+
self.rng = random.Random(self.seed + 1289738273 * self.epoch)
|
| 739 |
+
shardshuffle = self.shufflefirst or self.epoch > 0
|
| 740 |
+
yield from iterate_ranges(
|
| 741 |
+
self.ranges,
|
| 742 |
+
self.rng,
|
| 743 |
+
indexshuffle=self.shuffle,
|
| 744 |
+
shardshuffle=(self.shuffle and shardshuffle),
|
| 745 |
+
)
|
| 746 |
+
self.epoch += 1
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def DistributedChunkedSampler(
|
| 750 |
+
dataset: Dataset,
|
| 751 |
+
*,
|
| 752 |
+
num_replicas: Optional[int] = None,
|
| 753 |
+
num_samples: Optional[int] = None,
|
| 754 |
+
rank: Optional[int] = None,
|
| 755 |
+
shuffle: bool = True,
|
| 756 |
+
shufflefirst: bool = False,
|
| 757 |
+
seed: int = 0,
|
| 758 |
+
drop_last: bool = None,
|
| 759 |
+
chunksize: int = 1000000,
|
| 760 |
+
) -> ChunkedSampler:
|
| 761 |
+
"""Return a ChunkedSampler for the current worker in distributed training.
|
| 762 |
+
|
| 763 |
+
Reverts to a simple ChunkedSampler if not running in distributed mode.
|
| 764 |
+
|
| 765 |
+
Since the split among workers takes place before the chunk shuffle,
|
| 766 |
+
workers end up with a fixed set of shards they need to download. The
|
| 767 |
+
more workers, the fewer shards are used by each worker.
|
| 768 |
+
"""
|
| 769 |
+
if drop_last is not None:
|
| 770 |
+
warnings.warn("DistributedChunkedSampler does not support drop_last, thus it will be ignored")
|
| 771 |
+
if not dist.is_initialized():
|
| 772 |
+
warnings.warn("DistributedChunkedSampler is called without distributed initialized; assuming single process")
|
| 773 |
+
num_replicas = 1
|
| 774 |
+
rank = 0
|
| 775 |
+
else:
|
| 776 |
+
num_replicas = num_replicas or dist.get_world_size()
|
| 777 |
+
rank = rank or dist.get_rank()
|
| 778 |
+
assert rank >= 0 and rank < num_replicas
|
| 779 |
+
|
| 780 |
+
num_samples = num_samples or len(dataset)
|
| 781 |
+
worker_chunk = (num_samples + num_replicas - 1) // num_replicas
|
| 782 |
+
worker_start = rank * worker_chunk
|
| 783 |
+
worker_end = min(worker_start + worker_chunk, num_samples)
|
| 784 |
+
return ChunkedSampler(
|
| 785 |
+
dataset,
|
| 786 |
+
num_samples=(worker_start, worker_end),
|
| 787 |
+
chunksize=chunksize,
|
| 788 |
+
seed=seed,
|
| 789 |
+
shuffle=shuffle,
|
| 790 |
+
shufflefirst=shufflefirst,
|
| 791 |
+
)
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
class DistributedLocalSampler(DistributedSampler):
|
| 795 |
+
def __iter__(self):
|
| 796 |
+
if self.shuffle:
|
| 797 |
+
# deterministically shuffle based on epoch and seed
|
| 798 |
+
g = torch.Generator()
|
| 799 |
+
g.manual_seed(self.seed + self.epoch)
|
| 800 |
+
indices = torch.randperm(len(self.dataset), generator=g).tolist() # type: ignore[arg-type]
|
| 801 |
+
else:
|
| 802 |
+
indices = list(range(len(self.dataset))) # type: ignore[arg-type]
|
| 803 |
+
|
| 804 |
+
if not self.drop_last:
|
| 805 |
+
# add extra samples to make it evenly divisible
|
| 806 |
+
padding_size = self.total_size - len(indices)
|
| 807 |
+
if padding_size <= len(indices):
|
| 808 |
+
indices += indices[:padding_size]
|
| 809 |
+
else:
|
| 810 |
+
indices += (indices * math.ceil(padding_size / len(indices)))[:padding_size]
|
| 811 |
+
else:
|
| 812 |
+
# remove tail of data to make it evenly divisible.
|
| 813 |
+
indices = indices[: self.total_size]
|
| 814 |
+
assert len(indices) == self.total_size
|
| 815 |
+
|
| 816 |
+
# subsample
|
| 817 |
+
# indices = indices[self.rank:self.total_size:self.num_replicas]
|
| 818 |
+
chunk_size = self.total_size // self.num_replicas
|
| 819 |
+
begin_idx = chunk_size * self.rank
|
| 820 |
+
stop_idx = chunk_size * (self.rank + 1)
|
| 821 |
+
indices = indices[begin_idx:stop_idx]
|
| 822 |
+
|
| 823 |
+
# print("[SamplerIndices: ]", indices)
|
| 824 |
+
assert len(indices) == self.num_samples
|
| 825 |
+
return iter(indices)
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_bench.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
from . import wids
|
| 5 |
+
from .compat import WebDataset
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def main_wids(args):
|
| 9 |
+
desc = json.load(open(args.dataset))
|
| 10 |
+
files = desc["files"]
|
| 11 |
+
dataset = wids.ShardListDataset(files, cache_size=4)
|
| 12 |
+
print(len(dataset))
|
| 13 |
+
for i in range(len(dataset)):
|
| 14 |
+
print(i, dataset[i]["__key__"])
|
| 15 |
+
dataset.close()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main_wds(args):
|
| 19 |
+
desc = json.load(open(args.dataset))
|
| 20 |
+
files = desc["files"]
|
| 21 |
+
urls = [f["url"] for f in files]
|
| 22 |
+
dataset = WebDataset(urls)
|
| 23 |
+
for i, sample in enumerate(dataset):
|
| 24 |
+
print(i, sample["__key__"])
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if __name__ == "__main__":
|
| 28 |
+
parser = argparse.ArgumentParser()
|
| 29 |
+
# there are two subcommands: wids and wds
|
| 30 |
+
subparsers = parser.add_subparsers(dest="command")
|
| 31 |
+
wids_parser = subparsers.add_parser("wids")
|
| 32 |
+
wds_parser = subparsers.add_parser("wds")
|
| 33 |
+
|
| 34 |
+
# wids subcommand
|
| 35 |
+
wids_parser.add_argument("dataset", help="dataset name")
|
| 36 |
+
|
| 37 |
+
# wds subcommand
|
| 38 |
+
wds_parser.add_argument("dataset", help="dataset name")
|
| 39 |
+
|
| 40 |
+
args = parser.parse_args()
|
| 41 |
+
|
| 42 |
+
if args.command == "wids":
|
| 43 |
+
main_wids(args)
|
| 44 |
+
elif args.command == "wds":
|
| 45 |
+
main_wds(args)
|
| 46 |
+
else:
|
| 47 |
+
raise ValueError(f"Unknown command: {args.command}")
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_cleanup.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module provides utilities for managing files in a directory.
|
| 3 |
+
|
| 4 |
+
It includes a function `keep_most_recent_files` that keeps the most recent
|
| 5 |
+
files in a directory, deleting the rest based on the maximum size of the directory
|
| 6 |
+
in bytes and the maximum number of files to keep.
|
| 7 |
+
|
| 8 |
+
The cleanup job can be run in the background using `create_cleanup_background_process`.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import errno
|
| 12 |
+
import fcntl
|
| 13 |
+
import glob
|
| 14 |
+
import os
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def keep_most_recent_files(pattern, maxsize=int(1e12), maxfiles=1000, debug=False):
|
| 21 |
+
"""Keep the most recent files in a directory, deleting the rest.
|
| 22 |
+
|
| 23 |
+
The maxsize is the maximum size of the directory in bytes. The maxfiles is
|
| 24 |
+
the maximum number of files to keep. The files are sorted by modification
|
| 25 |
+
time, and the most recent files are kept. If the directory is already
|
| 26 |
+
smaller than maxsize, then no files are deleted. If there are fewer than
|
| 27 |
+
maxfiles, then no files are deleted."""
|
| 28 |
+
|
| 29 |
+
# get the list of files in the directory
|
| 30 |
+
fnames = glob.glob(pattern)
|
| 31 |
+
# compute a list of (mtime, fname, size) triples
|
| 32 |
+
files = []
|
| 33 |
+
for fname in fnames:
|
| 34 |
+
try:
|
| 35 |
+
s = os.stat(fname)
|
| 36 |
+
except FileNotFoundError:
|
| 37 |
+
continue
|
| 38 |
+
files.append((s.st_mtime, fname, s.st_size))
|
| 39 |
+
# sort the list by mtime, most recent first
|
| 40 |
+
files.sort(reverse=True)
|
| 41 |
+
# compute an accumulated total of the file sizes in order using np.cumsum
|
| 42 |
+
sizes = np.cumsum([size for mtime, fname, size in files])
|
| 43 |
+
# compute a cutoff index based on maxsize
|
| 44 |
+
cutoff = np.searchsorted(sizes, maxsize)
|
| 45 |
+
# compute a cutoff index based on maxfiles
|
| 46 |
+
cutoff = min(cutoff, maxfiles)
|
| 47 |
+
# delete the files above the cutoff in reverse order
|
| 48 |
+
for mtime, fname, size in files[cutoff:][::-1]:
|
| 49 |
+
try:
|
| 50 |
+
os.unlink(fname)
|
| 51 |
+
except FileNotFoundError:
|
| 52 |
+
pass
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class ExclusiveLock:
|
| 56 |
+
"""A simple non-blocking exclusive lock using fcntl."""
|
| 57 |
+
|
| 58 |
+
def __init__(self, lockfile):
|
| 59 |
+
self.lockfile = lockfile
|
| 60 |
+
|
| 61 |
+
def try_lock(self):
|
| 62 |
+
try:
|
| 63 |
+
self.lock = open(self.lockfile, "w")
|
| 64 |
+
fcntl.flock(self.lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 65 |
+
return True
|
| 66 |
+
except OSError as e:
|
| 67 |
+
if e.errno in (errno.EAGAIN, errno.EWOULDBLOCK):
|
| 68 |
+
return False
|
| 69 |
+
else:
|
| 70 |
+
raise
|
| 71 |
+
|
| 72 |
+
def release_lock(self):
|
| 73 |
+
self.lock.close()
|
| 74 |
+
os.unlink(self.lockfile)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def create_cleanup_background_process(pattern, maxsize=int(1e12), maxfiles=1000, every=60):
|
| 78 |
+
"""Create a background process that keeps a directory below a certain size."""
|
| 79 |
+
|
| 80 |
+
def cleanup_worker(every):
|
| 81 |
+
# use a lock file to ensure that only one cleanup worker is running
|
| 82 |
+
lockfile = os.path.join(os.path.dirname(pattern), ".cleanup.lock")
|
| 83 |
+
lock = ExclusiveLock(lockfile)
|
| 84 |
+
if not lock.try_lock():
|
| 85 |
+
return
|
| 86 |
+
while True:
|
| 87 |
+
keep_most_recent_files(pattern, maxsize=maxsize, maxfiles=maxfiles)
|
| 88 |
+
time.sleep(every)
|
| 89 |
+
|
| 90 |
+
import multiprocessing
|
| 91 |
+
|
| 92 |
+
p = multiprocessing.Process(target=cleanup_worker, args=(every,))
|
| 93 |
+
p.start()
|
| 94 |
+
return p
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_dir.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
# dynamically create a shard index
|
| 3 |
+
class DirectoryDataset(ShardListDataset):
|
| 4 |
+
def __init__(self, directory):
|
| 5 |
+
pass
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
# randomly choose shards from a directory
|
| 10 |
+
class DirectoryQueueDataset(IterableDataset):
|
| 11 |
+
def __init__(self, directory, strategy="replace", choice="random", downloader=None, transformations="PIL"):
|
| 12 |
+
pass
|
| 13 |
+
def add_transform(self, transform):
|
| 14 |
+
pass
|
| 15 |
+
def __iter__(self):
|
| 16 |
+
# pick file according to strategy
|
| 17 |
+
# rename file to .active
|
| 18 |
+
# randomly yield samples from file
|
| 19 |
+
# rename file back to its original name or unlink it, according to strategy
|
| 20 |
+
pass
|
| 21 |
+
"""
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_dl.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import fcntl
|
| 2 |
+
import os
|
| 3 |
+
import shutil
|
| 4 |
+
import sys
|
| 5 |
+
import time
|
| 6 |
+
from collections import deque
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from urllib.parse import urlparse
|
| 9 |
+
|
| 10 |
+
recent_downloads = deque(maxlen=1000)
|
| 11 |
+
|
| 12 |
+
open_objects = {}
|
| 13 |
+
max_open_objects = 100
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ULockFile:
|
| 17 |
+
"""A simple locking class. We don't need any of the third
|
| 18 |
+
party libraries since we rely on POSIX semantics for linking
|
| 19 |
+
below anyway."""
|
| 20 |
+
|
| 21 |
+
def __init__(self, path):
|
| 22 |
+
self.lockfile_path = path
|
| 23 |
+
self.lockfile = None
|
| 24 |
+
|
| 25 |
+
def __enter__(self):
|
| 26 |
+
self.lockfile = open(self.lockfile_path, "w")
|
| 27 |
+
fcntl.flock(self.lockfile.fileno(), fcntl.LOCK_EX)
|
| 28 |
+
return self
|
| 29 |
+
|
| 30 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 31 |
+
fcntl.flock(self.lockfile.fileno(), fcntl.LOCK_UN)
|
| 32 |
+
self.lockfile.close()
|
| 33 |
+
self.lockfile = None
|
| 34 |
+
try:
|
| 35 |
+
os.unlink(self.lockfile_path)
|
| 36 |
+
except FileNotFoundError:
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def pipe_download(remote, local):
|
| 41 |
+
"""Perform a download for a pipe: url."""
|
| 42 |
+
assert remote.startswith("pipe:")
|
| 43 |
+
cmd = remote[5:]
|
| 44 |
+
cmd = cmd.format(local=local)
|
| 45 |
+
assert os.system(cmd) == 0, "Command failed: %s" % cmd
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def copy_file(remote, local):
|
| 49 |
+
remote = urlparse(remote)
|
| 50 |
+
assert remote.scheme in ["file", ""]
|
| 51 |
+
# use absolute path
|
| 52 |
+
remote = os.path.abspath(remote.path)
|
| 53 |
+
local = urlparse(local)
|
| 54 |
+
assert local.scheme in ["file", ""]
|
| 55 |
+
local = os.path.abspath(local.path)
|
| 56 |
+
if remote == local:
|
| 57 |
+
return
|
| 58 |
+
# check if the local file exists
|
| 59 |
+
shutil.copyfile(remote, local)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
verbose_cmd = int(os.environ.get("WIDS_VERBOSE_CMD", "0"))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def vcmd(flag, verbose_flag=""):
|
| 66 |
+
return verbose_flag if verbose_cmd else flag
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
default_cmds = {
|
| 70 |
+
"posixpath": copy_file,
|
| 71 |
+
"file": copy_file,
|
| 72 |
+
"pipe": pipe_download,
|
| 73 |
+
"http": "curl " + vcmd("-s") + " -L {url} -o {local}",
|
| 74 |
+
"https": "curl " + vcmd("-s") + " -L {url} -o {local}",
|
| 75 |
+
"ftp": "curl " + vcmd("-s") + " -L {url} -o {local}",
|
| 76 |
+
"ftps": "curl " + vcmd("-s") + " -L {url} -o {local}",
|
| 77 |
+
"gs": "gsutil " + vcmd("-q") + " cp {url} {local}",
|
| 78 |
+
"s3": "aws s3 cp {url} {local}",
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
# TODO(ligeng): change HTTPS download to python requests library
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def download_file_no_log(remote, local, handlers=default_cmds):
|
| 85 |
+
"""Download a file from a remote url to a local path.
|
| 86 |
+
The remote url can be a pipe: url, in which case the remainder of
|
| 87 |
+
the url is treated as a command template that is executed to perform the download.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
if remote.startswith("pipe:"):
|
| 91 |
+
schema = "pipe"
|
| 92 |
+
else:
|
| 93 |
+
schema = urlparse(remote).scheme
|
| 94 |
+
if schema is None or schema == "":
|
| 95 |
+
schema = "posixpath"
|
| 96 |
+
# get the handler
|
| 97 |
+
handler = handlers.get(schema)
|
| 98 |
+
if handler is None:
|
| 99 |
+
raise ValueError("Unknown schema: %s" % schema)
|
| 100 |
+
# call the handler
|
| 101 |
+
if callable(handler):
|
| 102 |
+
handler(remote, local)
|
| 103 |
+
else:
|
| 104 |
+
assert isinstance(handler, str)
|
| 105 |
+
cmd = handler.format(url=remote, local=local)
|
| 106 |
+
assert os.system(cmd) == 0, "Command failed: %s" % cmd
|
| 107 |
+
return local
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def download_file(remote, local, handlers=default_cmds, verbose=False):
|
| 111 |
+
start = time.time()
|
| 112 |
+
try:
|
| 113 |
+
return download_file_no_log(remote, local, handlers=handlers)
|
| 114 |
+
finally:
|
| 115 |
+
recent_downloads.append((remote, local, time.time(), time.time() - start))
|
| 116 |
+
if verbose:
|
| 117 |
+
print(
|
| 118 |
+
"downloaded",
|
| 119 |
+
remote,
|
| 120 |
+
"to",
|
| 121 |
+
local,
|
| 122 |
+
"in",
|
| 123 |
+
time.time() - start,
|
| 124 |
+
"seconds",
|
| 125 |
+
file=sys.stderr,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def download_and_open(remote, local, mode="rb", handlers=default_cmds, verbose=False):
|
| 130 |
+
with ULockFile(local + ".lock"):
|
| 131 |
+
if os.path.exists(remote):
|
| 132 |
+
# print("enter1", remote, local, mode)
|
| 133 |
+
result = open(remote, mode)
|
| 134 |
+
else:
|
| 135 |
+
# print("enter2", remote, local, mode)
|
| 136 |
+
if not os.path.exists(local):
|
| 137 |
+
if verbose:
|
| 138 |
+
print("downloading", remote, "to", local, file=sys.stderr)
|
| 139 |
+
download_file(remote, local, handlers=handlers)
|
| 140 |
+
else:
|
| 141 |
+
if verbose:
|
| 142 |
+
print("using cached", local, file=sys.stderr)
|
| 143 |
+
result = open(local, mode)
|
| 144 |
+
|
| 145 |
+
# input()
|
| 146 |
+
|
| 147 |
+
if open_objects is not None:
|
| 148 |
+
for k, v in list(open_objects.items()):
|
| 149 |
+
if v.closed:
|
| 150 |
+
del open_objects[k]
|
| 151 |
+
if len(open_objects) > max_open_objects:
|
| 152 |
+
raise RuntimeError("Too many open objects")
|
| 153 |
+
current_time = datetime.now().strftime("%Y%m%d%H%M%S")
|
| 154 |
+
key = tuple(str(x) for x in [remote, local, mode, current_time])
|
| 155 |
+
open_objects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
import os
|
| 4 |
+
import re
|
| 5 |
+
import sys
|
| 6 |
+
from urllib.parse import urlparse, urlunparse
|
| 7 |
+
|
| 8 |
+
import braceexpand
|
| 9 |
+
|
| 10 |
+
from . import wids, wids_dl
|
| 11 |
+
from .wids_specs import load_remote_dsdesc_raw
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def format_with_suffix(num):
|
| 15 |
+
suffixes = ["", "k", "M", "G", "T", "E"]
|
| 16 |
+
i = 0
|
| 17 |
+
while num >= 1000 and i < len(suffixes) - 1:
|
| 18 |
+
num /= 1000.0
|
| 19 |
+
i += 1
|
| 20 |
+
return f"{num:.1f}{suffixes[i]}"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class AtomicJsonUpdate:
|
| 24 |
+
def __init__(self, filename):
|
| 25 |
+
self.filename = filename
|
| 26 |
+
self.backup_filename = filename + ".bak"
|
| 27 |
+
self.temp_filename = filename + ".temp"
|
| 28 |
+
self.data = None
|
| 29 |
+
|
| 30 |
+
def __enter__(self):
|
| 31 |
+
# Read the original file
|
| 32 |
+
with open(self.filename) as file:
|
| 33 |
+
self.data = json.load(file)
|
| 34 |
+
return self.data
|
| 35 |
+
|
| 36 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 37 |
+
if exc_type is None:
|
| 38 |
+
# Write the modified data to the temporary file
|
| 39 |
+
with open(self.temp_filename, "w") as file:
|
| 40 |
+
json.dump(self.data, file, indent=2)
|
| 41 |
+
# Rename the original file to a backup
|
| 42 |
+
os.rename(self.filename, self.backup_filename)
|
| 43 |
+
# Rename the new file to the original file name
|
| 44 |
+
os.rename(self.temp_filename, self.filename)
|
| 45 |
+
elif os.path.exists(self.temp_filename):
|
| 46 |
+
os.remove(self.temp_filename)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def urldir(url):
|
| 50 |
+
"""Return the directory part of a url."""
|
| 51 |
+
parsed_url = urlparse(url)
|
| 52 |
+
path = parsed_url.path
|
| 53 |
+
directory = os.path.dirname(path)
|
| 54 |
+
return parsed_url._replace(path=directory).geturl()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def urlfile(url):
|
| 58 |
+
"""Return the file part of a url."""
|
| 59 |
+
parsed_url = urlparse(url)
|
| 60 |
+
path = parsed_url.path
|
| 61 |
+
filename = os.path.basename(path)
|
| 62 |
+
return filename
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def urldirbase(url):
|
| 66 |
+
# Parse the URL
|
| 67 |
+
parsed_url = urlparse(url)
|
| 68 |
+
|
| 69 |
+
# Use 'file' scheme if no scheme is given
|
| 70 |
+
scheme = parsed_url.scheme or "file"
|
| 71 |
+
|
| 72 |
+
# Handle file URLs and relative paths
|
| 73 |
+
if scheme == "file" and not parsed_url.netloc:
|
| 74 |
+
path = os.path.abspath(parsed_url.path)
|
| 75 |
+
else:
|
| 76 |
+
path = parsed_url.path
|
| 77 |
+
# Get the directory without the filename
|
| 78 |
+
path_without_filename = os.path.dirname(path)
|
| 79 |
+
|
| 80 |
+
# Reconstruct URL without filename
|
| 81 |
+
url_without_filename = urlunparse((scheme, parsed_url.netloc, path_without_filename, "", "", ""))
|
| 82 |
+
|
| 83 |
+
return url_without_filename
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def shorten_name(s):
|
| 87 |
+
l = re.split(r"[^a-zA-Z0-9_]+", s)
|
| 88 |
+
found = set()
|
| 89 |
+
result = []
|
| 90 |
+
for word in l:
|
| 91 |
+
if re.match(r"^[0-9]*$", word):
|
| 92 |
+
continue
|
| 93 |
+
if word not in found:
|
| 94 |
+
result.append(word)
|
| 95 |
+
found.add(word)
|
| 96 |
+
return "-".join(result)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def main_create(args):
|
| 100 |
+
"""Create a full shard index for a list of files."""
|
| 101 |
+
# set default output file name
|
| 102 |
+
if args.output is None:
|
| 103 |
+
args.output = "shardindex.json"
|
| 104 |
+
|
| 105 |
+
if args.name is None:
|
| 106 |
+
first = os.path.splitext(args.files[0])[0]
|
| 107 |
+
args.name = shorten_name(first)
|
| 108 |
+
print("setting name to", args.name)
|
| 109 |
+
|
| 110 |
+
# read the list of files from stdin if there is only one file and it is "-"
|
| 111 |
+
if len(args.files) == 1 and args.files[0] == "-":
|
| 112 |
+
args.files = [line.strip() for line in sys.stdin]
|
| 113 |
+
|
| 114 |
+
# expand any brace expressions in the file names
|
| 115 |
+
fnames = []
|
| 116 |
+
for f in args.files:
|
| 117 |
+
fnames.extend(braceexpand.braceexpand(f))
|
| 118 |
+
|
| 119 |
+
# create the shard index
|
| 120 |
+
downloader = wids_dl.SimpleDownloader()
|
| 121 |
+
files = []
|
| 122 |
+
for fname in fnames:
|
| 123 |
+
print(fname)
|
| 124 |
+
downloaded = downloader.download(fname, "/tmp/shard.tar")
|
| 125 |
+
md5sum = wids.compute_file_md5sum(downloaded)
|
| 126 |
+
nsamples = wids.compute_num_samples(downloaded)
|
| 127 |
+
filesize = os.stat(downloaded).st_size
|
| 128 |
+
files.append(dict(url=fname, md5sum=md5sum, nsamples=nsamples, filesize=filesize))
|
| 129 |
+
downloader.release(downloaded)
|
| 130 |
+
|
| 131 |
+
files = sorted(files, key=lambda x: x["url"])
|
| 132 |
+
|
| 133 |
+
# create the result dictionary
|
| 134 |
+
result = dict(
|
| 135 |
+
__kind__="wids-shard-index-v1",
|
| 136 |
+
wids_version=1,
|
| 137 |
+
shardlist=files,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if args.name != "":
|
| 141 |
+
result["name"] = args.name
|
| 142 |
+
|
| 143 |
+
if args.base is not None:
|
| 144 |
+
result["base"] = args.base
|
| 145 |
+
|
| 146 |
+
# add info if it is given
|
| 147 |
+
if args.info is not None:
|
| 148 |
+
info = open(args.info).read()
|
| 149 |
+
result["info"] = info
|
| 150 |
+
|
| 151 |
+
# write the result
|
| 152 |
+
with open(args.output, "w") as f:
|
| 153 |
+
json.dump(result, f, indent=2)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def main_update(args):
|
| 157 |
+
"""Update an existing file."""
|
| 158 |
+
with AtomicJsonUpdate(args.filename) as data:
|
| 159 |
+
if args.name != "":
|
| 160 |
+
data["name"] = args.name
|
| 161 |
+
if args.keep:
|
| 162 |
+
data["keep"] = True
|
| 163 |
+
if args.nokeep:
|
| 164 |
+
data["keep"] = False
|
| 165 |
+
if args.info != "":
|
| 166 |
+
data["info"] = args.info
|
| 167 |
+
if args.base != "":
|
| 168 |
+
data["base"] = args.base
|
| 169 |
+
if args.rebase:
|
| 170 |
+
bases = {urldirbase(shard["url"]) for shard in data["shardlist"]}
|
| 171 |
+
assert len(bases) == 1, f"multiple/no bases found: {bases}"
|
| 172 |
+
base = bases.pop()
|
| 173 |
+
print(f"rebasing to {base}")
|
| 174 |
+
data["base"] = base
|
| 175 |
+
if args.dir != "" or args.nodir or args.rebase:
|
| 176 |
+
shardlist = data["shardlist"]
|
| 177 |
+
for shard in shardlist:
|
| 178 |
+
url = shard["url"]
|
| 179 |
+
file = urlfile(url)
|
| 180 |
+
if args.nodir:
|
| 181 |
+
shard["url"] = file
|
| 182 |
+
else:
|
| 183 |
+
shard["url"] = os.path.join(args.dir, file)
|
| 184 |
+
data["shardlist"] = sorted(shardlist, key=lambda x: x["url"])
|
| 185 |
+
if "name" not in data:
|
| 186 |
+
parsed = urlparse(args.filename)
|
| 187 |
+
data["name"] = os.path.splitext(os.path.basename(parsed.path))[0]
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def print_long_info(data, filename):
|
| 191 |
+
print(" name:", data.get("name"))
|
| 192 |
+
print(" info:", data.get("info"))
|
| 193 |
+
print(" base:", data.get("base"), f"(assumed: {urldir(filename)})")
|
| 194 |
+
total_size = sum(shard["filesize"] for shard in data["shardlist"])
|
| 195 |
+
total_samples = sum(shard["nsamples"] for shard in data["shardlist"])
|
| 196 |
+
print(" total size:", format_with_suffix(total_size))
|
| 197 |
+
print(" total samples:", format_with_suffix(total_samples))
|
| 198 |
+
print(" avg sample size:", format_with_suffix(int(total_size / total_samples)))
|
| 199 |
+
print(
|
| 200 |
+
" avg shard size:",
|
| 201 |
+
format_with_suffix(int(total_size / len(data["shardlist"]))),
|
| 202 |
+
)
|
| 203 |
+
print(" first shard:", data["shardlist"][0]["url"])
|
| 204 |
+
print(" last shard:", data["shardlist"][-1]["url"])
|
| 205 |
+
if len(data.get("datasets", [])) > 0:
|
| 206 |
+
print(" datasets:")
|
| 207 |
+
for dataset in data.get("datasets", []):
|
| 208 |
+
print(" dataset name:", dataset.get("name"))
|
| 209 |
+
print(
|
| 210 |
+
" dataset url:",
|
| 211 |
+
dataset.get("source_url", len(data.get("shardlist", []))),
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def main_info(args):
|
| 216 |
+
"""Show info about an index file."""
|
| 217 |
+
if args.table:
|
| 218 |
+
print("file\tname\tnbytes\tnsamples\tbase\tlast\tdatasets")
|
| 219 |
+
for filename in args.filenames:
|
| 220 |
+
data = load_remote_dsdesc_raw(filename)
|
| 221 |
+
print(
|
| 222 |
+
filename,
|
| 223 |
+
data.get("name"),
|
| 224 |
+
sum(shard["filesize"] for shard in data["shardlist"]),
|
| 225 |
+
sum(shard["nsamples"] for shard in data["shardlist"]),
|
| 226 |
+
data.get("base"),
|
| 227 |
+
data["shardlist"][-1]["url"],
|
| 228 |
+
len(data.get("datasets", [])),
|
| 229 |
+
sep="\t",
|
| 230 |
+
)
|
| 231 |
+
else:
|
| 232 |
+
for filename in args.filenames:
|
| 233 |
+
data = load_remote_dsdesc_raw(filename)
|
| 234 |
+
print("filename:", filename)
|
| 235 |
+
print_long_info(data, filename)
|
| 236 |
+
print()
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def maybe_read(x):
|
| 240 |
+
try:
|
| 241 |
+
return x.read()
|
| 242 |
+
except AttributeError:
|
| 243 |
+
return x
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def maybe_decode(sample):
|
| 247 |
+
sample = {k: maybe_read(v) for k, v in sample.items()}
|
| 248 |
+
return sample
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def main_sample(args):
|
| 252 |
+
raw = args.raw or args.cat is not None
|
| 253 |
+
if raw:
|
| 254 |
+
ds = wids.ShardListDataset(args.filename, transformations=[maybe_decode])
|
| 255 |
+
else:
|
| 256 |
+
ds = wids.ShardListDataset(args.filename)
|
| 257 |
+
print("dataset size:", len(ds), file=sys.stderr)
|
| 258 |
+
sample = ds[args.index]
|
| 259 |
+
if args.cat is not None:
|
| 260 |
+
sys.stdout.buffer.write(sample[args.cat])
|
| 261 |
+
return 0
|
| 262 |
+
mkl = max(len(k) for k in sample.keys())
|
| 263 |
+
for k, v in sorted(sample.items()):
|
| 264 |
+
print(k.ljust(mkl), repr(v)[: args.width - mkl - 1])
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def main():
|
| 268 |
+
"""Commands for manipulating the shard index."""
|
| 269 |
+
# Create the top-level parser
|
| 270 |
+
parser = argparse.ArgumentParser(description="Command line tool with subcommands for file operations.")
|
| 271 |
+
subparsers = parser.add_subparsers(dest="command", required=True, help="Subcommands")
|
| 272 |
+
|
| 273 |
+
# Create the parser for the "create" command
|
| 274 |
+
create_parser = subparsers.add_parser("create", help="Create a new file")
|
| 275 |
+
create_parser.add_argument("files", nargs="+", help="files to index")
|
| 276 |
+
create_parser.add_argument("--output", "-o", help="output file name")
|
| 277 |
+
create_parser.add_argument("--name", "-n", help="name for dataset", default=None)
|
| 278 |
+
create_parser.add_argument("--info", "-i", help="description for dataset", default=None)
|
| 279 |
+
create_parser.add_argument("--base", "-b", help="base path", default=None)
|
| 280 |
+
|
| 281 |
+
# Create the parser for the "update" command
|
| 282 |
+
update_parser = subparsers.add_parser("update", help="Update an existing file")
|
| 283 |
+
update_parser.add_argument("filename", type=str, help="Name of the file to update")
|
| 284 |
+
update_parser.add_argument("-n", "--name", default="", help="set the dataset name")
|
| 285 |
+
update_parser.add_argument("-k", "--keep", default="store_true", help="set the keep flag")
|
| 286 |
+
update_parser.add_argument("-K", "--nokeep", default="store_true", help="clear the keep flag")
|
| 287 |
+
update_parser.add_argument("-i", "--info", default="", help="set the dataset info")
|
| 288 |
+
update_parser.add_argument("-D", "--nodir", action="store_true", help="remove the directory from the URLs")
|
| 289 |
+
update_parser.add_argument("-d", "--dir", default="", help="set the directory on the URLs")
|
| 290 |
+
update_parser.add_argument("-b", "--base", default="", help="set the base")
|
| 291 |
+
update_parser.add_argument("-B", "--rebase", action="store_true", help="rebase the URLs")
|
| 292 |
+
|
| 293 |
+
# Create the parser for the "info" command
|
| 294 |
+
info_parser = subparsers.add_parser("info", help="Show info about an index file")
|
| 295 |
+
info_parser.add_argument("filenames", type=str, nargs="*", help="Name of the file to display")
|
| 296 |
+
info_parser.add_argument("-t", "--table", action="store_true", help="output in table format")
|
| 297 |
+
|
| 298 |
+
# Create the parser for the "sample" command
|
| 299 |
+
sample_parser = subparsers.add_parser("sample", help="Show info about an index file")
|
| 300 |
+
sample_parser.add_argument("filename", type=str, help="Name of the file to update")
|
| 301 |
+
sample_parser.add_argument("index", type=int, default=0, help="Index of the sample to show")
|
| 302 |
+
sample_parser.add_argument("-p", "--python", action="store_true", help="Show raw sample")
|
| 303 |
+
sample_parser.add_argument("-r", "--raw", action="store_true", help="Show raw sample")
|
| 304 |
+
sample_parser.add_argument("-c", "--cat", type=str, default=None, help="Output the bytes for a given key")
|
| 305 |
+
sample_parser.add_argument("-w", "--width", type=int, default=250, help="Output the bytes for a given key")
|
| 306 |
+
|
| 307 |
+
# Parse the arguments
|
| 308 |
+
args = parser.parse_args() # Dynamically call the appropriate function based on the subcommand
|
| 309 |
+
|
| 310 |
+
try:
|
| 311 |
+
func = getattr(sys.modules[__name__], f"main_{args.command}")
|
| 312 |
+
except AttributeError:
|
| 313 |
+
parser.print_help()
|
| 314 |
+
|
| 315 |
+
func(args)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
if __name__ == "__main__":
|
| 319 |
+
main()
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_lru.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import OrderedDict
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class LRUCache:
|
| 5 |
+
def __init__(self, capacity: int, release_handler=None):
|
| 6 |
+
"""Initialize a new LRU cache with the given capacity."""
|
| 7 |
+
self.capacity = capacity
|
| 8 |
+
self.cache = OrderedDict()
|
| 9 |
+
self.release_handler = release_handler
|
| 10 |
+
|
| 11 |
+
def __getitem__(self, key):
|
| 12 |
+
"""Return the value associated with the given key, or None."""
|
| 13 |
+
if key not in self.cache:
|
| 14 |
+
return None
|
| 15 |
+
self.cache.move_to_end(key)
|
| 16 |
+
return self.cache[key]
|
| 17 |
+
|
| 18 |
+
def __setitem__(self, key, value):
|
| 19 |
+
"""Associate the given value with the given key."""
|
| 20 |
+
if key in self.cache:
|
| 21 |
+
self.cache.move_to_end(key)
|
| 22 |
+
self.cache[key] = value
|
| 23 |
+
if len(self.cache) > self.capacity:
|
| 24 |
+
key, value = self.cache.popitem(last=False)
|
| 25 |
+
if self.release_handler is not None:
|
| 26 |
+
self.release_handler(key, value)
|
| 27 |
+
|
| 28 |
+
def __delitem__(self, key):
|
| 29 |
+
"""Remove the given key from the cache."""
|
| 30 |
+
if key in self.cache:
|
| 31 |
+
if self.release_handler is not None:
|
| 32 |
+
value = self.cache[key]
|
| 33 |
+
self.release_handler(key, value)
|
| 34 |
+
del self.cache[key]
|
| 35 |
+
|
| 36 |
+
def __len__(self):
|
| 37 |
+
"""Return the number of entries in the cache."""
|
| 38 |
+
return len(self.cache)
|
| 39 |
+
|
| 40 |
+
def __contains__(self, key):
|
| 41 |
+
"""Return whether the cache contains the given key."""
|
| 42 |
+
return key in self.cache
|
| 43 |
+
|
| 44 |
+
def items(self):
|
| 45 |
+
"""Return an iterator over the keys of the cache."""
|
| 46 |
+
return self.cache.items()
|
| 47 |
+
|
| 48 |
+
def keys(self):
|
| 49 |
+
"""Return an iterator over the keys of the cache."""
|
| 50 |
+
return self.cache.keys()
|
| 51 |
+
|
| 52 |
+
def values(self):
|
| 53 |
+
"""Return an iterator over the values of the cache."""
|
| 54 |
+
return self.cache.values()
|
| 55 |
+
|
| 56 |
+
def clear(self):
|
| 57 |
+
for key in list(self.keys()):
|
| 58 |
+
value = self.cache[key]
|
| 59 |
+
if self.release_handler is not None:
|
| 60 |
+
self.release_handler(key, value)
|
| 61 |
+
del self[key]
|
| 62 |
+
|
| 63 |
+
def __del__(self):
|
| 64 |
+
self.clear()
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_mmtar.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
import fcntl
|
| 3 |
+
import io
|
| 4 |
+
import mmap
|
| 5 |
+
import os
|
| 6 |
+
import struct
|
| 7 |
+
|
| 8 |
+
TarHeader = collections.namedtuple(
|
| 9 |
+
"TarHeader",
|
| 10 |
+
[
|
| 11 |
+
"name",
|
| 12 |
+
"mode",
|
| 13 |
+
"uid",
|
| 14 |
+
"gid",
|
| 15 |
+
"size",
|
| 16 |
+
"mtime",
|
| 17 |
+
"chksum",
|
| 18 |
+
"typeflag",
|
| 19 |
+
"linkname",
|
| 20 |
+
"magic",
|
| 21 |
+
"version",
|
| 22 |
+
"uname",
|
| 23 |
+
"gname",
|
| 24 |
+
"devmajor",
|
| 25 |
+
"devminor",
|
| 26 |
+
"prefix",
|
| 27 |
+
],
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def parse_tar_header(header_bytes):
|
| 32 |
+
header = struct.unpack("!100s8s8s8s12s12s8s1s100s6s2s32s32s8s8s155s", header_bytes)
|
| 33 |
+
return TarHeader(*header)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def next_header(offset, header):
|
| 37 |
+
block_size = 512
|
| 38 |
+
size = header.size.decode("utf-8").strip("\x00")
|
| 39 |
+
if size == "":
|
| 40 |
+
return -1
|
| 41 |
+
size = int(size, 8)
|
| 42 |
+
# compute the file size rounded up to the next block size if it is a partial block
|
| 43 |
+
padded_file_size = (size + block_size - 1) // block_size * block_size
|
| 44 |
+
return offset + block_size + padded_file_size
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# TODO(ligeng): support gzip stream
|
| 48 |
+
class MMIndexedTar:
|
| 49 |
+
def __init__(self, fname, index_file=None, verbose=True, cleanup_callback=None):
|
| 50 |
+
self.verbose = verbose
|
| 51 |
+
self.cleanup_callback = cleanup_callback
|
| 52 |
+
if isinstance(fname, str):
|
| 53 |
+
self.stream = open(fname, "rb")
|
| 54 |
+
self.fname = fname
|
| 55 |
+
elif isinstance(fname, io.IOBase):
|
| 56 |
+
self.stream = fname
|
| 57 |
+
self.fname = None
|
| 58 |
+
self.mmapped_file = mmap.mmap(self.stream.fileno(), 0, access=mmap.ACCESS_READ)
|
| 59 |
+
if cleanup_callback:
|
| 60 |
+
cleanup_callback(fname, self.stream.fileno(), "start")
|
| 61 |
+
self._build_index()
|
| 62 |
+
|
| 63 |
+
def close(self, dispose=False):
|
| 64 |
+
if self.cleanup_callback:
|
| 65 |
+
self.cleanup_callback(self.fname, self.stream.fileno(), "end")
|
| 66 |
+
self.mmapped_file.close()
|
| 67 |
+
self.stream.close()
|
| 68 |
+
|
| 69 |
+
def _build_index(self):
|
| 70 |
+
self.by_name = {}
|
| 71 |
+
self.by_index = []
|
| 72 |
+
offset = 0
|
| 73 |
+
while offset >= 0 and offset < len(self.mmapped_file):
|
| 74 |
+
header = parse_tar_header(self.mmapped_file[offset : offset + 500])
|
| 75 |
+
name = header.name.decode("utf-8").strip("\x00")
|
| 76 |
+
typeflag = header.typeflag.decode("utf-8").strip("\x00")
|
| 77 |
+
if name != "" and name != "././@PaxHeader" and typeflag in ["0", ""]:
|
| 78 |
+
try:
|
| 79 |
+
size = int(header.size.decode("utf-8")[:-1], 8)
|
| 80 |
+
except ValueError as exn:
|
| 81 |
+
print(header)
|
| 82 |
+
raise exn
|
| 83 |
+
self.by_name[name] = offset
|
| 84 |
+
self.by_index.append((name, offset, size))
|
| 85 |
+
offset = next_header(offset, header)
|
| 86 |
+
|
| 87 |
+
def names(self):
|
| 88 |
+
return self.by_name.keys()
|
| 89 |
+
|
| 90 |
+
def get_at_offset(self, offset):
|
| 91 |
+
header = parse_tar_header(self.mmapped_file[offset : offset + 500])
|
| 92 |
+
name = header.name.decode("utf-8").strip("\x00")
|
| 93 |
+
start = offset + 512
|
| 94 |
+
end = start + int(header.size.decode("utf-8")[:-1], 8)
|
| 95 |
+
return name, self.mmapped_file[start:end]
|
| 96 |
+
|
| 97 |
+
def get_at_index(self, index):
|
| 98 |
+
name, offset, size = self.by_index[index]
|
| 99 |
+
return self.get_at_offset(offset)
|
| 100 |
+
|
| 101 |
+
def get_by_name(self, name):
|
| 102 |
+
offset = self.by_name[name]
|
| 103 |
+
return self.get_at_offset(offset)
|
| 104 |
+
|
| 105 |
+
def __iter__(self):
|
| 106 |
+
for name, offset, size in self.by_index:
|
| 107 |
+
yield name, self.mmapped_file[offset + 512 : offset + 512 + size]
|
| 108 |
+
|
| 109 |
+
def __getitem__(self, key):
|
| 110 |
+
if isinstance(key, int):
|
| 111 |
+
return self.get_at_index(key)
|
| 112 |
+
else:
|
| 113 |
+
return self.get_by_name(key)
|
| 114 |
+
|
| 115 |
+
def __len__(self):
|
| 116 |
+
return len(self.by_index)
|
| 117 |
+
|
| 118 |
+
def get_file(self, i):
|
| 119 |
+
fname, data = self.get_at_index(i)
|
| 120 |
+
return fname, io.BytesIO(data)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def keep_while_reading(fname, fd, phase, delay=0.0):
|
| 124 |
+
"""This is a possible cleanup callback for cleanup_callback of MIndexedTar.
|
| 125 |
+
|
| 126 |
+
It assumes that as long as there are some readers for a file,
|
| 127 |
+
more readers may be trying to open it.
|
| 128 |
+
|
| 129 |
+
Note that on Linux, unlinking the file doesn't matter after
|
| 130 |
+
it has been mmapped. The contents will only be deleted when
|
| 131 |
+
all readers close the file. The unlinking merely makes the file
|
| 132 |
+
unavailable to new readers, since the downloader checks first
|
| 133 |
+
whether the file exists.
|
| 134 |
+
"""
|
| 135 |
+
assert delay == 0.0, "delay not implemented"
|
| 136 |
+
if fd < 0 or fname is None:
|
| 137 |
+
return
|
| 138 |
+
if phase == "start":
|
| 139 |
+
fcntl.flock(fd, fcntl.LOCK_SH)
|
| 140 |
+
elif phase == "end":
|
| 141 |
+
try:
|
| 142 |
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 143 |
+
os.unlink(fname)
|
| 144 |
+
except FileNotFoundError:
|
| 145 |
+
# someone else deleted it already
|
| 146 |
+
pass
|
| 147 |
+
except BlockingIOError:
|
| 148 |
+
# we couldn't get an exclusive lock, so someone else is still reading
|
| 149 |
+
pass
|
| 150 |
+
else:
|
| 151 |
+
raise ValueError(f"Unknown phase {phase}")
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_specs.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import tempfile
|
| 5 |
+
from urllib.parse import urlparse, urlunparse
|
| 6 |
+
|
| 7 |
+
from .wids_dl import download_and_open
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def urldir(url):
|
| 11 |
+
"""Return the directory part of a url."""
|
| 12 |
+
parsed_url = urlparse(url)
|
| 13 |
+
path = parsed_url.path
|
| 14 |
+
directory = os.path.dirname(path)
|
| 15 |
+
return parsed_url._replace(path=directory).geturl()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def urlmerge(base, url):
|
| 19 |
+
"""Merge a base URL and a relative URL.
|
| 20 |
+
|
| 21 |
+
The function fills in any missing part of the url from the base,
|
| 22 |
+
except for params, query, and fragment, which are taken only from the 'url'.
|
| 23 |
+
For the pathname component, it merges the paths like os.path.join:
|
| 24 |
+
an absolute path in 'url' overrides the base path, otherwise the paths are merged.
|
| 25 |
+
|
| 26 |
+
Parameters:
|
| 27 |
+
base (str): The base URL.
|
| 28 |
+
url (str): The URL to merge with the base.
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
str: The merged URL.
|
| 32 |
+
"""
|
| 33 |
+
# Parse the base and the relative URL
|
| 34 |
+
parsed_base = urlparse(base)
|
| 35 |
+
parsed_url = urlparse(url)
|
| 36 |
+
|
| 37 |
+
# Merge paths using os.path.join
|
| 38 |
+
# If the url path is absolute, it overrides the base path
|
| 39 |
+
if parsed_url.path.startswith("/"):
|
| 40 |
+
merged_path = parsed_url.path
|
| 41 |
+
else:
|
| 42 |
+
merged_path = os.path.normpath(os.path.join(parsed_base.path, parsed_url.path))
|
| 43 |
+
|
| 44 |
+
# Construct the merged URL
|
| 45 |
+
merged_url = urlunparse(
|
| 46 |
+
(
|
| 47 |
+
parsed_url.scheme or parsed_base.scheme,
|
| 48 |
+
parsed_url.netloc or parsed_base.netloc,
|
| 49 |
+
merged_path,
|
| 50 |
+
parsed_url.params, # Use params from the url only
|
| 51 |
+
parsed_url.query, # Use query from the url only
|
| 52 |
+
parsed_url.fragment, # Use fragment from the url only
|
| 53 |
+
)
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
return merged_url
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def check_shards(l):
|
| 60 |
+
"""Check that a list of shards is well-formed.
|
| 61 |
+
|
| 62 |
+
This checks that the list is a list of dictionaries, and that
|
| 63 |
+
each dictionary has a "url" and a "nsamples" key.
|
| 64 |
+
"""
|
| 65 |
+
assert isinstance(l, list)
|
| 66 |
+
for shard in l:
|
| 67 |
+
assert isinstance(shard, dict)
|
| 68 |
+
assert "url" in shard
|
| 69 |
+
assert "nsamples" in shard
|
| 70 |
+
return l
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def set_all(l, k, v):
|
| 74 |
+
"""Set a key to a value in a list of dictionaries."""
|
| 75 |
+
if v is None:
|
| 76 |
+
return
|
| 77 |
+
for x in l:
|
| 78 |
+
if k not in x:
|
| 79 |
+
x[k] = v
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def load_remote_dsdesc_raw(source):
|
| 83 |
+
"""Load a remote or local dataset description in JSON format."""
|
| 84 |
+
if isinstance(source, str):
|
| 85 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 86 |
+
dlname = os.path.join(tmpdir, "dataset.json")
|
| 87 |
+
with download_and_open(source, dlname) as f:
|
| 88 |
+
dsdesc = json.load(f)
|
| 89 |
+
elif isinstance(source, io.IOBase):
|
| 90 |
+
dsdesc = json.load(source)
|
| 91 |
+
else:
|
| 92 |
+
# FIXME: use gopen
|
| 93 |
+
import requests
|
| 94 |
+
|
| 95 |
+
jsondata = requests.get(source).text
|
| 96 |
+
dsdesc = json.loads(jsondata)
|
| 97 |
+
return dsdesc
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def rebase_shardlist(shardlist, base):
|
| 101 |
+
"""Rebase the URLs in a shardlist."""
|
| 102 |
+
if base is None:
|
| 103 |
+
return shardlist
|
| 104 |
+
for shard in shardlist:
|
| 105 |
+
shard["url"] = urlmerge(base, shard["url"])
|
| 106 |
+
return shardlist
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def resolve_dsdesc(dsdesc, *, options=None, base=None):
|
| 110 |
+
"""Resolve a dataset description.
|
| 111 |
+
|
| 112 |
+
This rebases the shards as necessary and loads any remote references.
|
| 113 |
+
|
| 114 |
+
Dataset descriptions are JSON files. They must have the following format;
|
| 115 |
+
|
| 116 |
+
{
|
| 117 |
+
"wids_version": 1,
|
| 118 |
+
# optional immediate shardlist
|
| 119 |
+
"shardlist": [
|
| 120 |
+
{"url": "http://example.com/file.tar", "nsamples": 1000},
|
| 121 |
+
...
|
| 122 |
+
],
|
| 123 |
+
# sub-datasets
|
| 124 |
+
"datasets": [
|
| 125 |
+
{"source_url": "http://example.com/dataset.json"},
|
| 126 |
+
{"shardlist": [
|
| 127 |
+
{"url": "http://example.com/file.tar", "nsamples": 1000},
|
| 128 |
+
...
|
| 129 |
+
]}
|
| 130 |
+
...
|
| 131 |
+
]
|
| 132 |
+
}
|
| 133 |
+
"""
|
| 134 |
+
if options is None:
|
| 135 |
+
options = {}
|
| 136 |
+
assert isinstance(dsdesc, dict)
|
| 137 |
+
dsdesc = dict(dsdesc, **options)
|
| 138 |
+
shardlist = rebase_shardlist(dsdesc.get("shardlist", []), base)
|
| 139 |
+
assert shardlist is not None
|
| 140 |
+
set_all(shardlist, "weight", dsdesc.get("weight"))
|
| 141 |
+
set_all(shardlist, "name", dsdesc.get("name"))
|
| 142 |
+
check_shards(shardlist)
|
| 143 |
+
assert "wids_version" in dsdesc, "No wids_version in dataset description"
|
| 144 |
+
assert dsdesc["wids_version"] == 1, "Unknown wids_version"
|
| 145 |
+
for component in dsdesc.get("datasets", []):
|
| 146 |
+
# we use the weight from the reference to the dataset,
|
| 147 |
+
# regardless of remote loading
|
| 148 |
+
weight = component.get("weight")
|
| 149 |
+
# follow any source_url dsdescs through remote loading
|
| 150 |
+
source_url = None
|
| 151 |
+
if "source_url" in component:
|
| 152 |
+
source_url = component["source_url"]
|
| 153 |
+
component = load_remote_dsdesc_raw(source_url)
|
| 154 |
+
assert "source_url" not in component, "double indirection in dataset description"
|
| 155 |
+
assert "shardlist" in component, "no shardlist in dataset description"
|
| 156 |
+
# if the component has a base, use it to rebase the shardlist
|
| 157 |
+
# otherwise use the base from the source_url, if any
|
| 158 |
+
subbase = component.get("base", urldir(source_url) if source_url else None)
|
| 159 |
+
if subbase is not None:
|
| 160 |
+
rebase_shardlist(component["shardlist"], subbase)
|
| 161 |
+
l = check_shards(component["shardlist"])
|
| 162 |
+
set_all(l, "weight", weight)
|
| 163 |
+
set_all(l, "source_url", source_url)
|
| 164 |
+
set_all(l, "dataset", component.get("name"))
|
| 165 |
+
shardlist.extend(l)
|
| 166 |
+
assert len(shardlist) > 0, "No shards found"
|
| 167 |
+
dsdesc["shardlist"] = shardlist
|
| 168 |
+
return dsdesc
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def load_dsdesc_and_resolve(source, *, options=None, base=None):
|
| 172 |
+
if options is None:
|
| 173 |
+
options = {}
|
| 174 |
+
dsdesc = load_remote_dsdesc_raw(source)
|
| 175 |
+
return resolve_dsdesc(dsdesc, base=base, options=options)
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_lift/llava/wids/wids_tar.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import os
|
| 3 |
+
import os.path
|
| 4 |
+
import pickle
|
| 5 |
+
import re
|
| 6 |
+
import tarfile
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def find_index_file(file):
|
| 12 |
+
prefix, last_ext = os.path.splitext(file)
|
| 13 |
+
if re.match("._[0-9]+_$", last_ext):
|
| 14 |
+
return prefix + ".index"
|
| 15 |
+
else:
|
| 16 |
+
return file + ".index"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TarFileReader:
|
| 20 |
+
def __init__(self, file, index_file=find_index_file, verbose=True):
|
| 21 |
+
self.verbose = verbose
|
| 22 |
+
if callable(index_file):
|
| 23 |
+
index_file = index_file(file)
|
| 24 |
+
self.index_file = index_file
|
| 25 |
+
|
| 26 |
+
# Open the tar file and keep it open
|
| 27 |
+
if isinstance(file, str):
|
| 28 |
+
self.tar_file = tarfile.open(file, "r")
|
| 29 |
+
else:
|
| 30 |
+
self.tar_file = tarfile.open(fileobj=file, mode="r")
|
| 31 |
+
|
| 32 |
+
# Create the index
|
| 33 |
+
self._create_tar_index()
|
| 34 |
+
|
| 35 |
+
def _create_tar_index(self):
|
| 36 |
+
if self.index_file is not None and os.path.exists(self.index_file):
|
| 37 |
+
if self.verbose:
|
| 38 |
+
print("Loading tar index from", self.index_file)
|
| 39 |
+
with open(self.index_file, "rb") as stream:
|
| 40 |
+
self.fnames, self.index = pickle.load(stream)
|
| 41 |
+
return
|
| 42 |
+
# Create an empty list for the index
|
| 43 |
+
self.fnames = []
|
| 44 |
+
self.index = []
|
| 45 |
+
|
| 46 |
+
if self.verbose:
|
| 47 |
+
print("Creating tar index for", self.tar_file.name, "at", self.index_file)
|
| 48 |
+
# Iterate over the members of the tar file
|
| 49 |
+
for member in self.tar_file:
|
| 50 |
+
# If the member is a file, add it to the index
|
| 51 |
+
if member.isfile():
|
| 52 |
+
# Get the file's offset
|
| 53 |
+
offset = self.tar_file.fileobj.tell()
|
| 54 |
+
self.fnames.append(member.name)
|
| 55 |
+
self.index.append([offset, member.size])
|
| 56 |
+
if self.verbose:
|
| 57 |
+
print("Done creating tar index for", self.tar_file.name, "at", self.index_file)
|
| 58 |
+
self.index = np.array(self.index)
|
| 59 |
+
if self.index_file is not None:
|
| 60 |
+
if os.path.exists(self.index_file + ".temp"):
|
| 61 |
+
os.unlink(self.index_file + ".temp")
|
| 62 |
+
with open(self.index_file + ".temp", "wb") as stream:
|
| 63 |
+
pickle.dump((self.fnames, self.index), stream)
|
| 64 |
+
os.rename(self.index_file + ".temp", self.index_file)
|
| 65 |
+
|
| 66 |
+
def names(self):
|
| 67 |
+
return self.fnames
|
| 68 |
+
|
| 69 |
+
def __len__(self):
|
| 70 |
+
return len(self.index)
|
| 71 |
+
|
| 72 |
+
def get_file(self, i):
|
| 73 |
+
name = self.fnames[i]
|
| 74 |
+
offset, size = self.index[i]
|
| 75 |
+
self.tar_file.fileobj.seek(offset)
|
| 76 |
+
file_bytes = self.tar_file.fileobj.read(size)
|
| 77 |
+
return name, io.BytesIO(file_bytes)
|
| 78 |
+
|
| 79 |
+
def close(self):
|
| 80 |
+
# Close the tar file
|
| 81 |
+
self.tar_file.close()
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000850_n.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c14862dbc80dc0c7252f68c0b7c21184a11fe66602dc30f2e1a7058baee5efcd
|
| 3 |
+
size 755137
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000850_r.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7ad13b9dd39e7aa46e08aeed17fe56b4c83b12ed2671f74eaa9d81ba02781ca9
|
| 3 |
+
size 3609142
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000852_m.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1b012a2b9836274fb65b648010d1f31fc7876c987e9c8da7356a5c491c1e1b52
|
| 3 |
+
size 74633
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000855_i.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7ecb1cca04f67a83f4c007a55b1f76386232ca9986d074a7a464f456abe24755
|
| 3 |
+
size 699690
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000855_m.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7a260f61cc7702268fecd12ed1b95a69a137ae1248daf4feb2ad8e8b3a267d08
|
| 3 |
+
size 144241
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000863_f.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a601fb75dc9bd0f5342112a54086d493609c477fc07bdd60fcf2082618c1ed15
|
| 3 |
+
size 533098
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000872_e.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6702ef8f25cd2656c0b564d1fb67634bcc4111dcf8a7b55dfca30755bd78dd40
|
| 3 |
+
size 547377
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000876_c.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fc349710e912432c60a7448e3df9efa5bc74df4a5f32c5e66fbf71927b258124
|
| 3 |
+
size 353156
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/eg_videos/000892_e.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e7e48a18246ed6c6312d9350f048fcc484181d132a9b8aa301f81f006b5eca0a
|
| 3 |
+
size 213810
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_mllm/mllm_few_shot_egs.json
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"video_name": "000850_n",
|
| 4 |
+
"video_url": "https://molar-public.oss-cn-hangzhou.aliyuncs.com/VideoScore/0500_0999/videocrafter2/000850_n.mp4",
|
| 5 |
+
"prompt": "In an African setting, Kintu, an African man, walks into a massive garden that seems to never end, with a pot in his hands. Water droplets form on the blade of grass in the garden",
|
| 6 |
+
"visual_score": 2,
|
| 7 |
+
"visual_cmt_raw": "画质差,画面闪烁,颜色不稳定,草丛和人脸模糊变形",
|
| 8 |
+
"t2v_score": 3,
|
| 9 |
+
"t2v_cmt_raw": "手里没有锅,草叶上没有水滴",
|
| 10 |
+
"phy_score": 1,
|
| 11 |
+
"phy_cmt_raw": "像劣质动画,人物外形和人体比例不合理,人脸变形,背景的植物画风过于简单",
|
| 12 |
+
"thinking": "multi-dimensional analysis:\nLet me carefully analyze this video based on the frames provided and the text prompt.\n\nText prompt: 'In an African setting, Kintu, an African man, walks into a massive garden that seems to never end, with a pot in his hands. Water droplets form on the blade of grass in the garden'\n\nNow let me examine each dimension:\n\n**Visual Quality Analysis:**\n- The frames show a garden setting with an African man; resolution is acceptable but the output does not feel photorealistic.\n- The scene has some consistency across frames (the man, the garden, and distant vegetation).\n- However, notable issues persist:\n - Background vegetation appears artificial or stylized rather than truly natural.\n - The man’s facial features and body proportions look distorted; the overall rendering has a cartoon-like or animated quality.\n - Grass textures are simplified and the overall rendering quality leans toward non-photorealistic aesthetics.\n\nOverall, the visual quality is below average and lacks convincing realism.\n\n**Text-to-Video Alignment Analysis:**\n- The core prompt elements—an African setting and an African man—are broadly present, and the garden environment is suggested as expansive.\n- Crucially, the frame sequence does not clearly show the pot in his hands, and there is no observable water droplet phenomenon on the grass.\n- These omissions yield a moderate level of alignment: the scene captures the general idea but omits important details called for by the prompt.\n\n**Physical Consistency (Common-sense Consistency):**\n- The subject’s body and facial features appear unnaturally constructed, with distorted proportions.\n- Movement and choreography feel artificial rather than natural.\n- The garden setting, lighting, and shadows do not reflect realistic physics, contributing to a lack of plausible realism.\n- Taken together, the video exhibits severe inconsistencies in physical coherence, reading as animated rather than physically plausible.\n",
|
| 13 |
+
"user_prompt": "\n You are an expert for evaluating and thinking about the quality of AI videos from diverse dimensions.\n\nWe would like to evaluate its quality from three dimensions: 'visual quality', 'text-to-video alignment' and 'physical consistency'. Below is the definition of each dimension: \n(1) visual quality: \nThe dimension 'visual quality' cares about the video's visual and optical propertities, including resolution, overall clarity, local blurriness, smoothness, stability of brightness/contrast, distortion/misalignment, abrupt changes, and any other factors the affect the watching experience. \n(2) text-to-video alignment:\nThe dimension 't2v_alignment' mainly assesses whether the generated video fully and accurately depicts the elements mentioned in the text prompt, such as characters, actions, animals, etc., as well as background, quantity, color, weather, and so on. \n(3) physical/common-sense consistency:\nThe dimension 'physical/common-sense consistency' mainly examines whether there are any violations of common sense, physical laws, or any other aspects in the video that appear strange or unnatural.\n\nHere we provide an AI video generated by text-to-video models and its text prompt: \nIn an African setting, Kintu, an African man, walks into a massive garden that seems to never end, with a pot in his hands. Water droplets form on the blade of grass in the garden.\n\nBased on the video content and the dimension definitions, please evaluate the video and give the quality score. \nThe quality score must be integars in the range of 1 - 5.\n\nYour output must be in the following format:\nvisual quality: <v_score>; \ntext-to-video alignment: <t_score>,\nphysical/common-sense consistency: <p_score>\n\nDO NOT include any other things behind or after your output.",
|
| 14 |
+
"video_path": "eval_methods/utils_mllm/eg_videos/000850_n.mp4",
|
| 15 |
+
"response": "<think>multi-dimensional analysis:\nLet me carefully analyze this video based on the frames provided and the text prompt.\n\nText prompt: 'In an African setting, Kintu, an African man, walks into a massive garden that seems to never end, with a pot in his hands. Water droplets form on the blade of grass in the garden'\n\nNow let me examine each dimension:\n\n**Visual Quality Analysis:**\n- The frames show a garden setting with an African man; resolution is acceptable but the output does not feel photorealistic.\n- The scene has some consistency across frames (the man, the garden, and distant vegetation).\n- However, notable issues persist:\n - Background vegetation appears artificial or stylized rather than truly natural.\n - The man’s facial features and body proportions look distorted; the overall rendering has a cartoon-like or animated quality.\n - Grass textures are simplified and the overall rendering quality leans toward non-photorealistic aesthetics.\n\nOverall, the visual quality is below average and lacks convincing realism.\n\n**Text-to-Video Alignment Analysis:**\n- The core prompt elements—an African setting and an African man—are broadly present, and the garden environment is suggested as expansive.\n- Crucially, the frame sequence does not clearly show the pot in his hands, and there is no observable water droplet phenomenon on the grass.\n- These omissions yield a moderate level of alignment: the scene captures the general idea but omits important details called for by the prompt.\n\n**Physical Consistency (Common-sense Consistency):**\n- The subject’s body and facial features appear unnaturally constructed, with distorted proportions.\n- Movement and choreography feel artificial rather than natural.\n- The garden setting, lighting, and shadows do not reflect realistic physics, contributing to a lack of plausible realism.\n- Taken together, the video exhibits severe inconsistencies in physical coherence, reading as animated rather than physically plausible.\n<\\think>\n<answer>visual quality: 2; \ntext-to-video alignment: 3,\nphysical/common-sense consistency: 1"
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"video_name": "000852_m",
|
| 19 |
+
"video_url": "https://molar-public.oss-cn-hangzhou.aliyuncs.com/VideoScore/0500_0999/hotshot_xl/000852_m.mp4",
|
| 20 |
+
"prompt": "An Ottoman man is jumping from the roof of an old Ottoman house to another at night, with a background of the Istanbul panorama in an old gravure style",
|
| 21 |
+
"visual_score": 1,
|
| 22 |
+
"visual_cmt_raw": "Low resolution and bad clarity. Local blurriness is present. Frequent visual distortions and misalignments. Abrupt and unsmooth transitions between adjacent frames. Unpolished and visually unstable, detracting from its watchability.",
|
| 23 |
+
"t2v_score": 3,
|
| 24 |
+
"t2v_cmt_raw": "没看出奥斯曼房屋,没有雕刻风格的城市全景",
|
| 25 |
+
"phy_score": 1,
|
| 26 |
+
"phy_cmt_raw": "视频风格诡异,人物悬停空中,且姿势不合理不自然",
|
| 27 |
+
"thinking": "Visual Quality Analysis:\n- The frame exhibits extremely low visual fidelity with pronounced blur, jagged edges, and noticeable compression artifacts. There is severe resolution limitation, and lighting is inconsistent across the scene, with muddy textures on buildings and overall poor rendering quality.\n\nText-to-Video Alignment Analysis:\n- The scene captures elements like a nighttime rooftop setting and a city backdrop, which align somewhat with the prompt. However, critical Ottoman-specific cues remain unclear or absent (no clear Ottoman architectural features, no historically accurate attire, and the gravure aesthetic is not evident). The Istanbul panorama is not distinctly recognizable, yielding only a mid-level alignment rather than strong alignment with the full prompt.\n\nPhysical Consistency Analysis:\n- The motion and physics are fundamentally flawed: the jumping action lacks a believable arc, with awkward posture and timing that imply unrealistic gravity and interaction with surfaces. Lighting and shadows do not consistently match the scene, and proportions appear distorted, producing an uncanny impression.\n\nOverall scoring inferred from the ground-truth: Visual Quality = 1/5; Text-to-Video Alignment = 3/5; Physical Consistency = 1/5.",
|
| 28 |
+
"user_prompt": "\n You are an expert for evaluating and thinking about the quality of AI videos from diverse dimensions.\n\nWe would like to evaluate its quality from three dimensions: 'visual quality', 'text-to-video alignment' and 'physical consistency'. Below is the definition of each dimension: \n(1) visual quality: \nThe dimension 'visual quality' cares about the video's visual and optical propertities, including resolution, overall clarity, local blurriness, smoothness, stability of brightness/contrast, distortion/misalignment, abrupt changes, and any other factors the affect the watching experience. \n(2) text-to-video alignment:\nThe dimension 't2v_alignment' mainly assesses whether the generated video fully and accurately depicts the elements mentioned in the text prompt, such as characters, actions, animals, etc., as well as background, quantity, color, weather, and so on. \n(3) physical/common-sense consistency:\nThe dimension 'physical/common-sense consistency' mainly examines whether there are any violations of common sense, physical laws, or any other aspects in the video that appear strange or unnatural.\n\nHere we provide an AI video generated by text-to-video models and its text prompt: \nAn Ottoman man is jumping from the roof of an old Ottoman house to another at night, with a background of the Istanbul panorama in an old gravure style.\n\nBased on the video content and the dimension definitions, please evaluate the video and give the quality score. \nThe quality score must be integars in the range of 1 - 5.\n\nYour output must be in the following format:\nvisual quality: <v_score>; \ntext-to-video alignment: <t_score>,\nphysical/common-sense consistency: <p_score>\n\nDO NOT include any other things behind or after your output.",
|
| 29 |
+
"video_path": "eval_methods/utils_mllm/eg_videos/000852_m.mp4",
|
| 30 |
+
"response": "<think>Visual Quality Analysis:\n- The frame exhibits extremely low visual fidelity with pronounced blur, jagged edges, and noticeable compression artifacts. There is severe resolution limitation, and lighting is inconsistent across the scene, with muddy textures on buildings and overall poor rendering quality.\n\nText-to-Video Alignment Analysis:\n- The scene captures elements like a nighttime rooftop setting and a city backdrop, which align somewhat with the prompt. However, critical Ottoman-specific cues remain unclear or absent (no clear Ottoman architectural features, no historically accurate attire, and the gravure aesthetic is not evident). The Istanbul panorama is not distinctly recognizable, yielding only a mid-level alignment rather than strong alignment with the full prompt.\n\nPhysical Consistency Analysis:\n- The motion and physics are fundamentally flawed: the jumping action lacks a believable arc, with awkward posture and timing that imply unrealistic gravity and interaction with surfaces. Lighting and shadows do not consistently match the scene, and proportions appear distorted, producing an uncanny impression.\n\nOverall scoring inferred from the ground-truth: Visual Quality = 1/5; Text-to-Video Alignment = 3/5; Physical Consistency = 1/5.<\\think>\n<answer>visual quality: 1; \ntext-to-video alignment: 3,\nphysical/common-sense consistency: 1"
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"video_name": "000850_r",
|
| 34 |
+
"video_url": "https://molar-public.oss-cn-hangzhou.aliyuncs.com/VideoScore/0500_0999/kling/000850_r.mp4",
|
| 35 |
+
"prompt": "In an African setting, Kintu, an African man, walks into a massive garden that seems to never end, with a pot in his hands. Water droplets form on the blade of grass in the garden",
|
| 36 |
+
"visual_score": 5,
|
| 37 |
+
"visual_cmt_raw": "High resolution, good clarity. No noticeable visual issues",
|
| 38 |
+
"t2v_score": 3,
|
| 39 |
+
"t2v_cmt_raw": "主角不是非洲男人,手里不是锅,草叶上没有水滴",
|
| 40 |
+
"phy_score": 5,
|
| 41 |
+
"phy_cmt_raw": "Good physical and commonsense consistency. No noticable issues.",
|
| 42 |
+
"thinking": "multi-dimensional analysis:\nI evaluated this AI-generated video across three dimensions: visual quality, text-to-video alignment, and physical/common-sense consistency. Ground-truth scores: Visual Quality = 5, Text-to-Video Alignment = 3, Physical Consistency = 5.\n\nVisual Quality:\nThe video exhibits excellent visual fidelity throughout. Frames are sharp, with natural colors and rich detail in the garden setting. Lighting is consistent and realistic, camera work is steady, and transitions are smooth. There are no noticeable distortions or artifacts, supporting a top-tier visual experience.\n\nText-to-Video Alignment:\nThere is partial alignment with the prompt. It is correct that a figure carries a pot and the garden scene appears expansive, but several prompt specifics are not convincingly realized. The setting reads as a formal garden that reads more European than distinctly African, and the character’s ethnicity is not clearly established from the available perspective. Most notably, water droplets on grass blades described in the prompt are not observed in the frames. These gaps yield a moderate alignment level, consistent with a score around 3.\n\nPhysical Consistency:\nMotion, lighting, shadows, and spatial relationships maintain coherent real-world physics. The walking figure moves naturally, with plausible weight distribution when carrying the pot, and the garden environment responds consistently to movement. There are no obvious inconsistencies in gravity, perspective, or object interactions, supporting a high level of common-sense consistency.\n\nOverall, the video delivers high Visual Quality and strong Physical Consistency, while Text-to-Video Alignment reflects moderate alignment with the descriptive prompt due to mismatches in setting and moisture details.",
|
| 43 |
+
"user_prompt": "\n You are an expert for evaluating and thinking about the quality of AI videos from diverse dimensions.\n\nWe would like to evaluate its quality from three dimensions: 'visual quality', 'text-to-video alignment' and 'physical consistency'. Below is the definition of each dimension: \n(1) visual quality: \nThe dimension 'visual quality' cares about the video's visual and optical propertities, including resolution, overall clarity, local blurriness, smoothness, stability of brightness/contrast, distortion/misalignment, abrupt changes, and any other factors the affect the watching experience. \n(2) text-to-video alignment:\nThe dimension 't2v_alignment' mainly assesses whether the generated video fully and accurately depicts the elements mentioned in the text prompt, such as characters, actions, animals, etc., as well as background, quantity, color, weather, and so on. \n(3) physical/common-sense consistency:\nThe dimension 'physical/common-sense consistency' mainly examines whether there are any violations of common sense, physical laws, or any other aspects in the video that appear strange or unnatural.\n\nHere we provide an AI video generated by text-to-video models and its text prompt: \nIn an African setting, Kintu, an African man, walks into a massive garden that seems to never end, with a pot in his hands. Water droplets form on the blade of grass in the garden.\n\nBased on the video content and the dimension definitions, please evaluate the video and give the quality score. \nThe quality score must be integars in the range of 1 - 5.\n\nYour output must be in the following format:\nvisual quality: <v_score>; \ntext-to-video alignment: <t_score>,\nphysical/common-sense consistency: <p_score>\n\nDO NOT include any other things behind or after your output.",
|
| 44 |
+
"video_path": "eval_methods/utils_mllm/eg_videos/000850_r.mp4",
|
| 45 |
+
"response": "<think>multi-dimensional analysis:\nI evaluated this AI-generated video across three dimensions: visual quality, text-to-video alignment, and physical/common-sense consistency. Ground-truth scores: Visual Quality = 5, Text-to-Video Alignment = 3, Physical Consistency = 5.\n\nVisual Quality:\nThe video exhibits excellent visual fidelity throughout. Frames are sharp, with natural colors and rich detail in the garden setting. Lighting is consistent and realistic, camera work is steady, and transitions are smooth. There are no noticeable distortions or artifacts, supporting a top-tier visual experience.\n\nText-to-Video Alignment:\nThere is partial alignment with the prompt. It is correct that a figure carries a pot and the garden scene appears expansive, but several prompt specifics are not convincingly realized. The setting reads as a formal garden that reads more European than distinctly African, and the character’s ethnicity is not clearly established from the available perspective. Most notably, water droplets on grass blades described in the prompt are not observed in the frames. These gaps yield a moderate alignment level, consistent with a score around 3.\n\nPhysical Consistency:\nMotion, lighting, shadows, and spatial relationships maintain coherent real-world physics. The walking figure moves naturally, with plausible weight distribution when carrying the pot, and the garden environment responds consistently to movement. There are no obvious inconsistencies in gravity, perspective, or object interactions, supporting a high level of common-sense consistency.\n\nOverall, the video delivers high Visual Quality and strong Physical Consistency, while Text-to-Video Alignment reflects moderate alignment with the descriptive prompt due to mismatches in setting and moisture details.<\\think>\n<answer>visual quality: 5; \ntext-to-video alignment: 3,\nphysical/common-sense consistency: 5"
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"video_name": "000855_i",
|
| 49 |
+
"video_url": "https://molar-public.oss-cn-hangzhou.aliyuncs.com/VideoScore/0500_0999/ltx_video_091/000855_i.mp4",
|
| 50 |
+
"prompt": "Fueled by her newfound powers, she soared through the skies, her cape trailing behind her as she patrolled the city, always ready to respond to the call of distress",
|
| 51 |
+
"visual_score": 2,
|
| 52 |
+
"visual_cmt_raw": "Low resolution and bad clarity. Local blurriness is present. Frequent visual distortions and misalignments. Abrupt and unsmooth transitions between adjacent frames. Unpolished and visually unstable, detracting from its watchability.",
|
| 53 |
+
"t2v_score": 1,
|
| 54 |
+
"t2v_cmt_raw": "能看出超人漫画风格但是画面太混乱难以看出符合prompt的地方",
|
| 55 |
+
"phy_score": 2,
|
| 56 |
+
"phy_cmt_raw": "视频逻辑混乱",
|
| 57 |
+
"thinking": "multi-dimensional analysis:\nLet me analyze the video frames and the text prompt to evaluate the video quality across the three dimensions.\n\nFirst, let me understand the text prompt: Fueled by her newfound powers, she soared through the skies, her cape trailing behind her as she patrolled the city, always ready to respond to the call of distress. This prompt describes a female superhero character soaring through the skies with a cape, patrolling a city. The key elements are:\n- A female character with powers\n- Soaring through skies\n- A cape trailing behind her\n- Patrolling a city\n- Ready to respond to distress\n\nNow let me examine the video frames:\n\nLooking at the frames, I can see this appears to be in a comic book/graphic novel style. The frames show a superhero character in a blue outfit with cape-like elements. The setting appears to be urban/city-like with comic book panels visible in the background.\n\nVisual Quality Analysis:\n\nResolution and Clarity: The frames have a comic-book art style; resolution is reasonable for this style, but there are noticeable clarity issues with some pixelation and compression artifacts.\nLocal Blurriness: Some details are not sharp, especially in the background and on fine character details, with varying clarity in the panel backgrounds.\nSmoothness and Stability: Some inter-frame variation exists, but the composition remains relatively stable and the character’s pose is consistent.\nBrightness/Contrast: Colors are vibrant and contrast is adequate for the style; the blue costume stands out against the background.\nDistortion/Misalignment: No major distortions; panel structure remains legible.\n\nOverall Visual Experience: The aesthetic is coherent as a comic-book presentation, but the clarity limitations and compression artifacts prevent a higher Visual Quality rating.\n\nBased on the ground-truth evaluation for Dim-1 (Visual Quality) = 2, the video is characterized by modest visual clarity with notable artifacting, not a strong visual quality signal.\n\nText-to-Video Alignment:\n\nAlignment with prompt has limitations. The scene presents a female figure in a blue outfit in an urban setting, but the explicit elements described in the prompt (soaring motion, cape trailing, patrolling, and responding to distress) are not convincingly realized. The motion feels static rather than flight-driven, and the cape does not exhibit dynamic trailing. Gender presentation is not strongly specified and the narrative emphasis is ambiguous. Overall, there is only partial alignment between description and visuals.\n\nGiven the ground-truth Dim-2 score of 1, the video should be considered to have strong misalignment with the textual prompt.\n\nPhysical Consistency (Common-sense):\n\nThe representation adheres to a consistent comic-book style, with plausible character proportions within that context. However, the flight physics and cape dynamics are not convincingly grounded in real-world physics, and the motion is constrained by the artistic medium rather than natural movement. Within the stylized framework, internal consistency is maintained, but it does not fully satisfy common-sense expectations for kinetic flight and action sequences.\n\nGround-truth Dim-3 score = 2 indicates moderate consistency within the chosen aesthetic, despite the physics-level limitations.\n\nGround-truth summary: Visual Quality 2, Text-to-Video Alignment 1, Physical Consistency 2.",
|
| 58 |
+
"user_prompt": "\n You are an expert for evaluating and thinking about the quality of AI videos from diverse dimensions.\n\nWe would like to evaluate its quality from three dimensions: 'visual quality', 'text-to-video alignment' and 'physical consistency'. Below is the definition of each dimension: \n(1) visual quality: \nThe dimension 'visual quality' cares about the video's visual and optical propertities, including resolution, overall clarity, local blurriness, smoothness, stability of brightness/contrast, distortion/misalignment, abrupt changes, and any other factors the affect the watching experience. \n(2) text-to-video alignment:\nThe dimension 't2v_alignment' mainly assesses whether the generated video fully and accurately depicts the elements mentioned in the text prompt, such as characters, actions, animals, etc., as well as background, quantity, color, weather, and so on. \n(3) physical/common-sense consistency:\nThe dimension 'physical/common-sense consistency' mainly examines whether there are any violations of common sense, physical laws, or any other aspects in the video that appear strange or unnatural.\n\nHere we provide an AI video generated by text-to-video models and its text prompt: \nFueled by her newfound powers, she soared through the skies, her cape trailing behind her as she patrolled the city, always ready to respond to the call of distress.\n\nBased on the video content and the dimension definitions, please evaluate the video and give the quality score. \nThe quality score must be integars in the range of 1 - 5.\n\nYour output must be in the following format:\nvisual quality: <v_score>; \ntext-to-video alignment: <t_score>,\nphysical/common-sense consistency: <p_score>\n\nDO NOT include any other things behind or after your output.",
|
| 59 |
+
"video_path": "eval_methods/utils_mllm/eg_videos/000855_i.mp4",
|
| 60 |
+
"response": "<think>multi-dimensional analysis:\nLet me analyze the video frames and the text prompt to evaluate the video quality across the three dimensions.\n\nFirst, let me understand the text prompt: Fueled by her newfound powers, she soared through the skies, her cape trailing behind her as she patrolled the city, always ready to respond to the call of distress. This prompt describes a female superhero character soaring through the skies with a cape, patrolling a city. The key elements are:\n- A female character with powers\n- Soaring through skies\n- A cape trailing behind her\n- Patrolling a city\n- Ready to respond to distress\n\nNow let me examine the video frames:\n\nLooking at the frames, I can see this appears to be in a comic book/graphic novel style. The frames show a superhero character in a blue outfit with cape-like elements. The setting appears to be urban/city-like with comic book panels visible in the background.\n\nVisual Quality Analysis:\n\nResolution and Clarity: The frames have a comic-book art style; resolution is reasonable for this style, but there are noticeable clarity issues with some pixelation and compression artifacts.\nLocal Blurriness: Some details are not sharp, especially in the background and on fine character details, with varying clarity in the panel backgrounds.\nSmoothness and Stability: Some inter-frame variation exists, but the composition remains relatively stable and the character’s pose is consistent.\nBrightness/Contrast: Colors are vibrant and contrast is adequate for the style; the blue costume stands out against the background.\nDistortion/Misalignment: No major distortions; panel structure remains legible.\n\nOverall Visual Experience: The aesthetic is coherent as a comic-book presentation, but the clarity limitations and compression artifacts prevent a higher Visual Quality rating.\n\nBased on the ground-truth evaluation for Dim-1 (Visual Quality) = 2, the video is characterized by modest visual clarity with notable artifacting, not a strong visual quality signal.\n\nText-to-Video Alignment:\n\nAlignment with prompt has limitations. The scene presents a female figure in a blue outfit in an urban setting, but the explicit elements described in the prompt (soaring motion, cape trailing, patrolling, and responding to distress) are not convincingly realized. The motion feels static rather than flight-driven, and the cape does not exhibit dynamic trailing. Gender presentation is not strongly specified and the narrative emphasis is ambiguous. Overall, there is only partial alignment between description and visuals.\n\nGiven the ground-truth Dim-2 score of 1, the video should be considered to have strong misalignment with the textual prompt.\n\nPhysical Consistency (Common-sense):\n\nThe representation adheres to a consistent comic-book style, with plausible character proportions within that context. However, the flight physics and cape dynamics are not convincingly grounded in real-world physics, and the motion is constrained by the artistic medium rather than natural movement. Within the stylized framework, internal consistency is maintained, but it does not fully satisfy common-sense expectations for kinetic flight and action sequences.\n\nGround-truth Dim-3 score = 2 indicates moderate consistency within the chosen aesthetic, despite the physics-level limitations.\n\nGround-truth summary: Visual Quality 2, Text-to-Video Alignment 1, Physical Consistency 2.<\\think>\n<answer>visual quality: 2; \ntext-to-video alignment: 1,\nphysical/common-sense consistency: 2"
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"video_name": "000855_m",
|
| 64 |
+
"video_url": "https://molar-public.oss-cn-hangzhou.aliyuncs.com/VideoScore/0500_0999/hotshot_xl/000855_m.mp4",
|
| 65 |
+
"prompt": "Fueled by her newfound powers, she soared through the skies, her cape trailing behind her as she patrolled the city, always ready to respond to the call of distress",
|
| 66 |
+
"visual_score": 3,
|
| 67 |
+
"visual_cmt_raw": "画面颜色和光线不稳定,人物扭曲模糊",
|
| 68 |
+
"t2v_score": 4,
|
| 69 |
+
"t2v_cmt_raw": "不像新获得的力量",
|
| 70 |
+
"phy_score": 3,
|
| 71 |
+
"phy_cmt_raw": "人物身体完全不成形,悬停空中且斗篷不动",
|
| 72 |
+
"thinking": "multi-dimensional analysis:\nLet me carefully analyze this video based on the prompt and the frames provided. The text prompt describes: \"Fueled by her newfound powers, she soared through the skies, her cape trailing behind her as she patrolled the city, always ready to respond to the call of distress\" \nLooking at the frame provided, I can see a figure in what appears to be a superhero-style pose with a cape, flying above a cityscape with buildings. Let me analyze each dimension:\n\nVisual Quality Analysis:\nFrom the frame, the concept is conveyed, but the overall visual fidelity is mid-range. The image is not as sharp as high-end renders; there is noticeable softness in textures and some minor artifacting in distant buildings. The character is readable and the cape is visible, but fine details (facial features, fabric textures) are not highly crisp. Lighting is broadly consistent with the scene, though some shading nuances are limited, which reduces realism. On balance, visual quality is moderate rather than strong.\n\nText-to-Video Alignment Analysis:\nThe video aligns well with the prompt overall:\n- The character is clearly in a flying pose above a city, implying powers in use.\n- A cape is present and appears to trail behind, consistent with flight motion.\n- The urban setting supports the idea of patrolling the city.\n- The notion of \"calling to distress\" is a narrative cue that isn’t directly visualized, but the heroic posture communicates readiness. Overall, alignment is strong and coherent with the core elements.\n\nPhysical Consistency Analysis:\nFlight dynamics and cape movement are plausible but not flawless. The pose suggests controlled aerial motion, and the cape responds to motion, yet there are occasional small inconsistencies in wind effects and perspective cues. The scale between the hero and the city is generally reasonable, but some frames hint at mild depth/perspective mismatches. Overall, physical/common-sense consistency is acceptable but not exemplary.\n",
|
| 73 |
+
"user_prompt": "\n You are an expert for evaluating and thinking about the quality of AI videos from diverse dimensions.\n\nWe would like to evaluate its quality from three dimensions: 'visual quality', 'text-to-video alignment' and 'physical consistency'. Below is the definition of each dimension: \n(1) visual quality: \nThe dimension 'visual quality' cares about the video's visual and optical propertities, including resolution, overall clarity, local blurriness, smoothness, stability of brightness/contrast, distortion/misalignment, abrupt changes, and any other factors the affect the watching experience. \n(2) text-to-video alignment:\nThe dimension 't2v_alignment' mainly assesses whether the generated video fully and accurately depicts the elements mentioned in the text prompt, such as characters, actions, animals, etc., as well as background, quantity, color, weather, and so on. \n(3) physical/common-sense consistency:\nThe dimension 'physical/common-sense consistency' mainly examines whether there are any violations of common sense, physical laws, or any other aspects in the video that appear strange or unnatural.\n\nHere we provide an AI video generated by text-to-video models and its text prompt: \nFueled by her newfound powers, she soared through the skies, her cape trailing behind her as she patrolled the city, always ready to respond to the call of distress.\n\nBased on the video content and the dimension definitions, please evaluate the video and give the quality score. \nThe quality score must be integars in the range of 1 - 5.\n\nYour output must be in the following format:\nvisual quality: <v_score>; \ntext-to-video alignment: <t_score>,\nphysical/common-sense consistency: <p_score>\n\nDO NOT include any other things behind or after your output.",
|
| 74 |
+
"video_path": "eval_methods/utils_mllm/eg_videos/000855_m.mp4",
|
| 75 |
+
"response": "<think>multi-dimensional analysis:\nLet me carefully analyze this video based on the prompt and the frames provided. The text prompt describes: \"Fueled by her newfound powers, she soared through the skies, her cape trailing behind her as she patrolled the city, always ready to respond to the call of distress\" \nLooking at the frame provided, I can see a figure in what appears to be a superhero-style pose with a cape, flying above a cityscape with buildings. Let me analyze each dimension:\n\nVisual Quality Analysis:\nFrom the frame, the concept is conveyed, but the overall visual fidelity is mid-range. The image is not as sharp as high-end renders; there is noticeable softness in textures and some minor artifacting in distant buildings. The character is readable and the cape is visible, but fine details (facial features, fabric textures) are not highly crisp. Lighting is broadly consistent with the scene, though some shading nuances are limited, which reduces realism. On balance, visual quality is moderate rather than strong.\n\nText-to-Video Alignment Analysis:\nThe video aligns well with the prompt overall:\n- The character is clearly in a flying pose above a city, implying powers in use.\n- A cape is present and appears to trail behind, consistent with flight motion.\n- The urban setting supports the idea of patrolling the city.\n- The notion of \"calling to distress\" is a narrative cue that isn’t directly visualized, but the heroic posture communicates readiness. Overall, alignment is strong and coherent with the core elements.\n\nPhysical Consistency Analysis:\nFlight dynamics and cape movement are plausible but not flawless. The pose suggests controlled aerial motion, and the cape responds to motion, yet there are occasional small inconsistencies in wind effects and perspective cues. The scale between the hero and the city is generally reasonable, but some frames hint at mild depth/perspective mismatches. Overall, physical/common-sense consistency is acceptable but not exemplary.\n<\\think>\n<answer>visual quality: 3; \ntext-to-video alignment: 4,\nphysical/common-sense consistency: 3"
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"video_name": "000863_f",
|
| 79 |
+
"video_url": "https://molar-public.oss-cn-hangzhou.aliyuncs.com/VideoScore/0500_0999/cogvideox_5b/000863_f.mp4",
|
| 80 |
+
"prompt": "Illustrate Tilly the panda savoring bamboo shoots, capturing the tranquility of her bamboo forest and her love for her unique diet",
|
| 81 |
+
"visual_score": 4,
|
| 82 |
+
"visual_cmt_raw": "竹笋和熊猫嘴模糊",
|
| 83 |
+
"t2v_score": 4,
|
| 84 |
+
"t2v_cmt_raw": "吃的不是竹笋",
|
| 85 |
+
"phy_score": 3,
|
| 86 |
+
"phy_cmt_raw": "视频像被加速,嚼竹子的动作不自然,嘴一直没闭上",
|
| 87 |
+
"thinking": "multi-dimensional analysis:\nLet me carefully analyze this video based on the text prompt and the frames provided.\n\nText prompt: \"Illustrate Tilly the panda savoring bamboo shoots, capturing the tranquility of her bamboo forest and her love for her unique diet\"\n\nLooking at the frames provided:\n1. The video shows a panda in what appears to be a bamboo forest setting\n2. The panda is holding what looks like bamboo stalks/shoots\n3. The panda's mouth is open in several frames, appearing to be eating or chewing\n4. There are bamboo stalks visible in the background\n5. The setting appears to be natural with green foliage\n\nNow let me evaluate each dimension:\n\nVisual Quality Analysis:\nLooking at the frames, I can assess the visual properties:\n- Resolution: The frames appear to have decent resolution, though not exceptionally high\n- Overall clarity: The main subject (panda) is generally clear and well-defined\n- Local blurriness: There appears to be some blurriness around the bamboo the panda is holding and possibly around the mouth area during eating motion\n- Smoothness: From the sequence of frames, the motion appears relatively smooth\n- Stability of brightness/contrast: The lighting and contrast appear consistent across frames\n- Distortion/misalignment: No obvious distortion issues visible\n- The panda's features are well-rendered with good detail in the fur texture and facial features\n\nOverall, the visual quality is solid with only minor blurriness and small imperfections, which is consistent with a score around 4.\n\nText-to-Video Alignment Analysis:\nComparing the video content to the prompt requirements:\n- \"Tilly the panda\" - There is a panda present\n- \"savoring bamboo shoots\" - The panda appears to be eating something that looks like bamboo stalks/shoots\n- \"capturing the tranquility of her bamboo forest\" - The setting shows bamboo and greenery that represents a forest environment\n- \"her love for her unique diet\" - The panda is shown actively eating bamboo\n\nThe video largely satisfies the prompt, with the panda's eating activity and the bamboo-rich setting conveying the intended mood. The alignment is strong, with only minor deviations in motion timing or subtle visuals that do not significantly detract from the overall prompt fulfillment, supporting a high (near-4) alignment rating.\n\nPhysical Consistency / Common-sense Analysis:\nThe sequence demonstrates generally plausible behavior, but some motions appear slightly mechanical and lack the full fluidity of a real panda’s eating gestures. These subtleties are noticeable but do not completely break the sense of realism in the scene. In aggregate, the video communicates a believable panda-eating moment in a bamboo setting, though there is moderate room for improvement in naturalism, aligning with a mid-level score around 3.\n\nThe overall assessment remains consistent with the intended scoring: Visual Quality 4, Text-to-Video Alignment 4, Physical Consistency 3.",
|
| 88 |
+
"user_prompt": "\n You are an expert for evaluating and thinking about the quality of AI videos from diverse dimensions.\n\nWe would like to evaluate its quality from three dimensions: 'visual quality', 'text-to-video alignment' and 'physical consistency'. Below is the definition of each dimension: \n(1) visual quality: \nThe dimension 'visual quality' cares about the video's visual and optical propertities, including resolution, overall clarity, local blurriness, smoothness, stability of brightness/contrast, distortion/misalignment, abrupt changes, and any other factors the affect the watching experience. \n(2) text-to-video alignment:\nThe dimension 't2v_alignment' mainly assesses whether the generated video fully and accurately depicts the elements mentioned in the text prompt, such as characters, actions, animals, etc., as well as background, quantity, color, weather, and so on. \n(3) physical/common-sense consistency:\nThe dimension 'physical/common-sense consistency' mainly examines whether there are any violations of common sense, physical laws, or any other aspects in the video that appear strange or unnatural.\n\nHere we provide an AI video generated by text-to-video models and its text prompt: \nIllustrate Tilly the panda savoring bamboo shoots, capturing the tranquility of her bamboo forest and her love for her unique diet.\n\nBased on the video content and the dimension definitions, please evaluate the video and give the quality score. \nThe quality score must be integars in the range of 1 - 5.\n\nYour output must be in the following format:\nvisual quality: <v_score>; \ntext-to-video alignment: <t_score>,\nphysical/common-sense consistency: <p_score>\n\nDO NOT include any other things behind or after your output.",
|
| 89 |
+
"video_path": "eval_methods/utils_mllm/eg_videos/000863_f.mp4",
|
| 90 |
+
"response": "<think>multi-dimensional analysis:\nLet me carefully analyze this video based on the text prompt and the frames provided.\n\nText prompt: \"Illustrate Tilly the panda savoring bamboo shoots, capturing the tranquility of her bamboo forest and her love for her unique diet\"\n\nLooking at the frames provided:\n1. The video shows a panda in what appears to be a bamboo forest setting\n2. The panda is holding what looks like bamboo stalks/shoots\n3. The panda's mouth is open in several frames, appearing to be eating or chewing\n4. There are bamboo stalks visible in the background\n5. The setting appears to be natural with green foliage\n\nNow let me evaluate each dimension:\n\nVisual Quality Analysis:\nLooking at the frames, I can assess the visual properties:\n- Resolution: The frames appear to have decent resolution, though not exceptionally high\n- Overall clarity: The main subject (panda) is generally clear and well-defined\n- Local blurriness: There appears to be some blurriness around the bamboo the panda is holding and possibly around the mouth area during eating motion\n- Smoothness: From the sequence of frames, the motion appears relatively smooth\n- Stability of brightness/contrast: The lighting and contrast appear consistent across frames\n- Distortion/misalignment: No obvious distortion issues visible\n- The panda's features are well-rendered with good detail in the fur texture and facial features\n\nOverall, the visual quality is solid with only minor blurriness and small imperfections, which is consistent with a score around 4.\n\nText-to-Video Alignment Analysis:\nComparing the video content to the prompt requirements:\n- \"Tilly the panda\" - There is a panda present\n- \"savoring bamboo shoots\" - The panda appears to be eating something that looks like bamboo stalks/shoots\n- \"capturing the tranquility of her bamboo forest\" - The setting shows bamboo and greenery that represents a forest environment\n- \"her love for her unique diet\" - The panda is shown actively eating bamboo\n\nThe video largely satisfies the prompt, with the panda's eating activity and the bamboo-rich setting conveying the intended mood. The alignment is strong, with only minor deviations in motion timing or subtle visuals that do not significantly detract from the overall prompt fulfillment, supporting a high (near-4) alignment rating.\n\nPhysical Consistency / Common-sense Analysis:\nThe sequence demonstrates generally plausible behavior, but some motions appear slightly mechanical and lack the full fluidity of a real panda’s eating gestures. These subtleties are noticeable but do not completely break the sense of realism in the scene. In aggregate, the video communicates a believable panda-eating moment in a bamboo setting, though there is moderate room for improvement in naturalism, aligning with a mid-level score around 3.\n\nThe overall assessment remains consistent with the intended scoring: Visual Quality 4, Text-to-Video Alignment 4, Physical Consistency 3.<\\think>\n<answer>visual quality: 4; \ntext-to-video alignment: 4,\nphysical/common-sense consistency: 3"
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"video_name": "000876_c",
|
| 94 |
+
"video_url": "https://molar-public.oss-cn-hangzhou.aliyuncs.com/VideoScore/0500_0999/mochi1_preview/000876_c.mp4",
|
| 95 |
+
"prompt": "A red fox with a bushy tail and black ears walks on a dirt path through a forest with tall trees and colorful leaves. Rays of sunlight and mist create a magical atmosphere in this morning wildlife photography",
|
| 96 |
+
"visual_score": 3,
|
| 97 |
+
"visual_cmt_raw": "画面模糊,色调偏灰",
|
| 98 |
+
"t2v_score": 4,
|
| 99 |
+
"t2v_cmt_raw": "Aligns well with prompt. Key elements are clearly represented.",
|
| 100 |
+
"phy_score": 5,
|
| 101 |
+
"phy_cmt_raw": "Good physical and commonsense consistency. No noticable issues.",
|
| 102 |
+
"thinking": "multi-dimensional analysis: Let me analyze this video based on the text prompt and the frames provided. The text prompt is: A red fox with a bushy tail and black ears walks on a dirt path through a forest with tall trees and colorful leaves. Rays of sunlight and mist create a magical atmosphere in this morning wildlife photography. From the frames provided, I can see: Visual Quality Analysis: The overall image quality is moderate with some issues in clarity and sharpness. The frames are slightly soft and the contrast is restrained, giving a muted vibrancy. The warm color grading and atmospheric glow align with the prompt but do not render the image with high punch. Lighting is consistent across the sequence and there are no major distortions or abrupt changes. The resolution is sufficient, but the detail is not consistently crisp. The mist and lighting contribute to atmosphere, though the rendering reads as slightly subdued rather than striking. Text-to-Video Alignment Analysis: The frames capture the main prompt elements with strong fidelity. The red fox with a bushy tail and dark ears is present and in motion on a dirt path within a forest with tall trees and colorful leaves. Rays of sunlight and mist are visible, and the overall mood resembles a magical morning wildlife scene. The alignment is robust with minor deviations such as occasional background detail variance or timing of the motion which do not significantly detract from the prompt adherence, supporting a near excellent but not perfect alignment score. Physical Consistency Analysis: The fox moves with natural gait and anatomically plausible proportions, and the environmental interactions such as lighting, mist and path texture are coherent. There are no evident physical contradictions between the subject and the scene, and scale relationships remain consistent throughout the sequence, yielding a high level of common-sense and physical consistency. Visual Quality Assessment: The video communicates the prompt effectively, but technical rendering is not pristine. Clarity is acceptable but not sharp, and color grading is muted rather than vivid. Despite these limitations, the scene successfully conveys a magical morning forest environment with the fox as the central subject. The overall assessment reflects a moderate Visual Quality, strong Text-to-Video Alignment, and excellent Physical Consistency.",
|
| 103 |
+
"user_prompt": "\n You are an expert for evaluating and thinking about the quality of AI videos from diverse dimensions.\n\nWe would like to evaluate its quality from three dimensions: 'visual quality', 'text-to-video alignment' and 'physical consistency'. Below is the definition of each dimension: \n(1) visual quality: \nThe dimension 'visual quality' cares about the video's visual and optical propertities, including resolution, overall clarity, local blurriness, smoothness, stability of brightness/contrast, distortion/misalignment, abrupt changes, and any other factors the affect the watching experience. \n(2) text-to-video alignment:\nThe dimension 't2v_alignment' mainly assesses whether the generated video fully and accurately depicts the elements mentioned in the text prompt, such as characters, actions, animals, etc., as well as background, quantity, color, weather, and so on. \n(3) physical/common-sense consistency:\nThe dimension 'physical/common-sense consistency' mainly examines whether there are any violations of common sense, physical laws, or any other aspects in the video that appear strange or unnatural.\n\nHere we provide an AI video generated by text-to-video models and its text prompt: \nA red fox with a bushy tail and black ears walks on a dirt path through a forest with tall trees and colorful leaves. Rays of sunlight and mist create a magical atmosphere in this morning wildlife photography.\n\nBased on the video content and the dimension definitions, please evaluate the video and give the quality score. \nThe quality score must be integars in the range of 1 - 5.\n\nYour output must be in the following format:\nvisual quality: <v_score>; \ntext-to-video alignment: <t_score>,\nphysical/common-sense consistency: <p_score>\n\nDO NOT include any other things behind or after your output.",
|
| 104 |
+
"video_path": "eval_methods/utils_mllm/eg_videos/000876_c.mp4",
|
| 105 |
+
"response": "<think>multi-dimensional analysis: Let me analyze this video based on the text prompt and the frames provided. The text prompt is: A red fox with a bushy tail and black ears walks on a dirt path through a forest with tall trees and colorful leaves. Rays of sunlight and mist create a magical atmosphere in this morning wildlife photography. From the frames provided, I can see: Visual Quality Analysis: The overall image quality is moderate with some issues in clarity and sharpness. The frames are slightly soft and the contrast is restrained, giving a muted vibrancy. The warm color grading and atmospheric glow align with the prompt but do not render the image with high punch. Lighting is consistent across the sequence and there are no major distortions or abrupt changes. The resolution is sufficient, but the detail is not consistently crisp. The mist and lighting contribute to atmosphere, though the rendering reads as slightly subdued rather than striking. Text-to-Video Alignment Analysis: The frames capture the main prompt elements with strong fidelity. The red fox with a bushy tail and dark ears is present and in motion on a dirt path within a forest with tall trees and colorful leaves. Rays of sunlight and mist are visible, and the overall mood resembles a magical morning wildlife scene. The alignment is robust with minor deviations such as occasional background detail variance or timing of the motion which do not significantly detract from the prompt adherence, supporting a near excellent but not perfect alignment score. Physical Consistency Analysis: The fox moves with natural gait and anatomically plausible proportions, and the environmental interactions such as lighting, mist and path texture are coherent. There are no evident physical contradictions between the subject and the scene, and scale relationships remain consistent throughout the sequence, yielding a high level of common-sense and physical consistency. Visual Quality Assessment: The video communicates the prompt effectively, but technical rendering is not pristine. Clarity is acceptable but not sharp, and color grading is muted rather than vivid. Despite these limitations, the scene successfully conveys a magical morning forest environment with the fox as the central subject. The overall assessment reflects a moderate Visual Quality, strong Text-to-Video Alignment, and excellent Physical Consistency.<\\think>\n<answer>visual quality: 3; \ntext-to-video alignment: 4,\nphysical/common-sense consistency: 5"
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"video_name": "000892_e",
|
| 109 |
+
"video_url": "https://molar-public.oss-cn-hangzhou.aliyuncs.com/VideoScore/0500_0999/cogvideox_2b/000892_e.mp4",
|
| 110 |
+
"prompt": "A person reading an eBook on a tablet while sitting on a bench in a park with trees and flowers",
|
| 111 |
+
"visual_score": 3,
|
| 112 |
+
"visual_cmt_raw": "画质差",
|
| 113 |
+
"t2v_score": 5,
|
| 114 |
+
"t2v_cmt_raw": "Aligns well with prompt. Key elements are clearly represented.",
|
| 115 |
+
"phy_score": 3,
|
| 116 |
+
"phy_cmt_raw": "人物颜色和光线失真,和背景不够融洽,手部外形不合理,且只有三根手指",
|
| 117 |
+
"thinking": "multi-dimensional analysis:\nLet me analyze this video frame by frame to evaluate it across the three dimensions.\n\nVisual Quality Analysis:\n- Overall Visual Quality score (ground truth): 3/5. The video has moderate visual quality. The frames are generally intelligible, but they lack the sharpness and fidelity of high-definition footage. There is a slightly artificial or processed look that hints at AI-generated content, reducing overall realism.\n- Resolution and Clarity: Acceptable but not outstanding; the main subject and park setting are discernible.\n- Stability: Very stable with minimal camera shake or jitter; the subject remains consistently positioned.\n- Consistency: Lighting and color balance are stable; colors remain coherent throughout the sequence.\n- Smoothness: Transitions between frames appear smooth with no abrupt changes.\n- Distortion/Misalignment: No obvious distortions, though the overall texture suggests synthetic rendering which affects the perceived quality.\n\nText-to-Video Alignment Analysis:\n- Ground-truth score: 5/5. The scene aligns perfectly with the prompt: a person reading an eBook on a tablet while sitting on a bench in a park with trees and flowers. All elements are present and represented as described.\n- Person: present\n- Reading: the person appears to be looking down at and interacting with a device consistent with reading\n- eBook on a tablet: a tablet device is clearly visible\n- Sitting: the person is seated\n- Bench: wooden bench evident\n- Park: setting includes grass/trees\n- Trees: present in the background\n- Flowers: pink flowers visible\n\nPhysical Consistency Analysis:\n- Ground-truth score: 3/5. The overall composition is plausible, with the person and tablet interaction appearing natural and daylight lighting supporting a coherent scene. However, subtle artefacts in hand rendering and finger articulation introduce mild inconsistencies in physical realism. The spatial arrangement of bench, person, and background elements remains believable, giving moderate overall physical coherence.",
|
| 118 |
+
"user_prompt": "\n You are an expert for evaluating and thinking about the quality of AI videos from diverse dimensions.\n\nWe would like to evaluate its quality from three dimensions: 'visual quality', 'text-to-video alignment' and 'physical consistency'. Below is the definition of each dimension: \n(1) visual quality: \nThe dimension 'visual quality' cares about the video's visual and optical propertities, including resolution, overall clarity, local blurriness, smoothness, stability of brightness/contrast, distortion/misalignment, abrupt changes, and any other factors the affect the watching experience. \n(2) text-to-video alignment:\nThe dimension 't2v_alignment' mainly assesses whether the generated video fully and accurately depicts the elements mentioned in the text prompt, such as characters, actions, animals, etc., as well as background, quantity, color, weather, and so on. \n(3) physical/common-sense consistency:\nThe dimension 'physical/common-sense consistency' mainly examines whether there are any violations of common sense, physical laws, or any other aspects in the video that appear strange or unnatural.\n\nHere we provide an AI video generated by text-to-video models and its text prompt: \nA person reading an eBook on a tablet while sitting on a bench in a park with trees and flowers.\n\nBased on the video content and the dimension definitions, please evaluate the video and give the quality score. \nThe quality score must be integars in the range of 1 - 5.\n\nYour output must be in the following format:\nvisual quality: <v_score>; \ntext-to-video alignment: <t_score>,\nphysical/common-sense consistency: <p_score>\n\nDO NOT include any other things behind or after your output.",
|
| 119 |
+
"video_path": "eval_methods/utils_mllm/eg_videos/000892_e.mp4",
|
| 120 |
+
"response": "<think>multi-dimensional analysis:\nLet me analyze this video frame by frame to evaluate it across the three dimensions.\n\nVisual Quality Analysis:\n- Overall Visual Quality score (ground truth): 3/5. The video has moderate visual quality. The frames are generally intelligible, but they lack the sharpness and fidelity of high-definition footage. There is a slightly artificial or processed look that hints at AI-generated content, reducing overall realism.\n- Resolution and Clarity: Acceptable but not outstanding; the main subject and park setting are discernible.\n- Stability: Very stable with minimal camera shake or jitter; the subject remains consistently positioned.\n- Consistency: Lighting and color balance are stable; colors remain coherent throughout the sequence.\n- Smoothness: Transitions between frames appear smooth with no abrupt changes.\n- Distortion/Misalignment: No obvious distortions, though the overall texture suggests synthetic rendering which affects the perceived quality.\n\nText-to-Video Alignment Analysis:\n- Ground-truth score: 5/5. The scene aligns perfectly with the prompt: a person reading an eBook on a tablet while sitting on a bench in a park with trees and flowers. All elements are present and represented as described.\n- Person: present\n- Reading: the person appears to be looking down at and interacting with a device consistent with reading\n- eBook on a tablet: a tablet device is clearly visible\n- Sitting: the person is seated\n- Bench: wooden bench evident\n- Park: setting includes grass/trees\n- Trees: present in the background\n- Flowers: pink flowers visible\n\nPhysical Consistency Analysis:\n- Ground-truth score: 3/5. The overall composition is plausible, with the person and tablet interaction appearing natural and daylight lighting supporting a coherent scene. However, subtle artefacts in hand rendering and finger articulation introduce mild inconsistencies in physical realism. The spatial arrangement of bench, person, and background elements remains believable, giving moderate overall physical coherence.<\\think>\n<answer>visual quality: 3; \ntext-to-video alignment: 5,\nphysical/common-sense consistency: 3"
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"video_name": "000872_e",
|
| 124 |
+
"video_url": "https://molar-public.oss-cn-hangzhou.aliyuncs.com/VideoScore/0500_0999/cogvideox_2b/000872_e.mp4",
|
| 125 |
+
"prompt": "Layla walking back through the forest, a sense of awe and understanding in her eyes. She is carrying the satchel over her shoulder, and a soft smile graces her lips",
|
| 126 |
+
"visual_score": 2,
|
| 127 |
+
"visual_cmt_raw": "人物扭曲模糊变形",
|
| 128 |
+
"t2v_score": 3,
|
| 129 |
+
"t2v_cmt_raw": "没有敬畏的神情,包没有挎在肩上",
|
| 130 |
+
"phy_score": 1,
|
| 131 |
+
"phy_cmt_raw": "人物走路速度太快,外形在变,不成人形,五官诡异",
|
| 132 |
+
"thinking": "multi-dimensional analysis: Let me carefully analyze the video frames to evaluate the quality across three dimensions: visual quality, text-to-video alignment, and physical/common-sense consistency. Text Prompt Analysis: The prompt describes Layla walking back through the forest, a sense of awe and understanding in her eyes. She is carrying the satchel over her shoulder, and a soft smile graces her lips. Key elements to look for: Character named Layla (female figure); walking through forest; expression of awe and understanding in her eyes; carrying a satchel over her shoulder; soft smile on her lips. Visual Quality Analysis: Looking at the frames: 1. Resolution and Clarity: The forest background is presentable, but character rendering is notably unstable. Some frames show blurriness around the head and face, and there are inconsistent facial features as the camera moves. 2. Character rendering: The female figure shows distortions and morphing artifacts; facial features vary between frames, reducing realism. 3. Lighting and contrast: Lighting across the sequence remains generally natural, with believable shadows between trees; however, this does not compensate for character-level issues. 4. Stability: The sequence suffers from noticeable instability in the character appearance, suggesting morphing or inconsistent rendering over time. 5. Motion blur: Some motion blur occurs during movement, likely tied to rendering inconsistencies rather than intended motion. Overall, the visual quality is limited by recurrent character rendering flaws, while the environment remains relatively decent. Text-to-Video Alignment Analysis: 1. Character: A female figure is present, aligning with the prompt. 2. Setting: The forest setting with trees and forest floor is depicted. 3. Action: The character is seen walking through the forest, matching walking back through the forest. I note the satchel is yellow or gold in several frames, but its position over the shoulder is inconsistent and not reliably maintained. The facial expression does not convincingly convey the specified sense of awe and understanding because of rendering fluctuations. The green or teal outfit remains plausible but does not fully resolve the alignment gaps. Overall, the scene captures the core elements only moderately well; precise nuances such as satchel placement and emotional tone are obscured by artifacts. The character is broadly human in appearance and moves with a basic walking motion, but subtle morphing artifacts disrupt continuity. The forest interaction with lighting and shadows remains authentic, yet rendering flaws limit faithful adherence to the prompt. The rendering quality presents notable challenges. While the background remains relatively crisp, character details suffer from distortion, reducing alignment to the prompt. The scene partially matches the description - a woman walking in a forest with a bag - but key nuances such as emotional tone and satchel positioning are muddled by artifacts. Fundamentally, the physical inconsistencies stem from perceptual morphing rather than physical law violations. The general motion and environment maintain plausible realism, yet persistent rendering flaws undermine consistent interpretation.",
|
| 133 |
+
"user_prompt": "\n You are an expert for evaluating and thinking about the quality of AI videos from diverse dimensions.\n\nWe would like to evaluate its quality from three dimensions: 'visual quality', 'text-to-video alignment' and 'physical consistency'. Below is the definition of each dimension: \n(1) visual quality: \nThe dimension 'visual quality' cares about the video's visual and optical propertities, including resolution, overall clarity, local blurriness, smoothness, stability of brightness/contrast, distortion/misalignment, abrupt changes, and any other factors the affect the watching experience. \n(2) text-to-video alignment:\nThe dimension 't2v_alignment' mainly assesses whether the generated video fully and accurately depicts the elements mentioned in the text prompt, such as characters, actions, animals, etc., as well as background, quantity, color, weather, and so on. \n(3) physical/common-sense consistency:\nThe dimension 'physical/common-sense consistency' mainly examines whether there are any violations of common sense, physical laws, or any other aspects in the video that appear strange or unnatural.\n\nHere we provide an AI video generated by text-to-video models and its text prompt: \nLayla walking back through the forest, a sense of awe and understanding in her eyes. She is carrying the satchel over her shoulder, and a soft smile graces her lips.\n\nBased on the video content and the dimension definitions, please evaluate the video and give the quality score. \nThe quality score must be integars in the range of 1 - 5.\n\nYour output must be in the following format:\nvisual quality: <v_score>; \ntext-to-video alignment: <t_score>,\nphysical/common-sense consistency: <p_score>\n\nDO NOT include any other things behind or after your output.",
|
| 134 |
+
"video_path": "eval_methods/utils_mllm/eg_videos/000872_e.mp4",
|
| 135 |
+
"response": "<think>multi-dimensional analysis: Let me carefully analyze the video frames to evaluate the quality across three dimensions: visual quality, text-to-video alignment, and physical/common-sense consistency. Text Prompt Analysis: The prompt describes Layla walking back through the forest, a sense of awe and understanding in her eyes. She is carrying the satchel over her shoulder, and a soft smile graces her lips. Key elements to look for: Character named Layla (female figure); walking through forest; expression of awe and understanding in her eyes; carrying a satchel over her shoulder; soft smile on her lips. Visual Quality Analysis: Looking at the frames: 1. Resolution and Clarity: The forest background is presentable, but character rendering is notably unstable. Some frames show blurriness around the head and face, and there are inconsistent facial features as the camera moves. 2. Character rendering: The female figure shows distortions and morphing artifacts; facial features vary between frames, reducing realism. 3. Lighting and contrast: Lighting across the sequence remains generally natural, with believable shadows between trees; however, this does not compensate for character-level issues. 4. Stability: The sequence suffers from noticeable instability in the character appearance, suggesting morphing or inconsistent rendering over time. 5. Motion blur: Some motion blur occurs during movement, likely tied to rendering inconsistencies rather than intended motion. Overall, the visual quality is limited by recurrent character rendering flaws, while the environment remains relatively decent. Text-to-Video Alignment Analysis: 1. Character: A female figure is present, aligning with the prompt. 2. Setting: The forest setting with trees and forest floor is depicted. 3. Action: The character is seen walking through the forest, matching walking back through the forest. I note the satchel is yellow or gold in several frames, but its position over the shoulder is inconsistent and not reliably maintained. The facial expression does not convincingly convey the specified sense of awe and understanding because of rendering fluctuations. The green or teal outfit remains plausible but does not fully resolve the alignment gaps. Overall, the scene captures the core elements only moderately well; precise nuances such as satchel placement and emotional tone are obscured by artifacts. The character is broadly human in appearance and moves with a basic walking motion, but subtle morphing artifacts disrupt continuity. The forest interaction with lighting and shadows remains authentic, yet rendering flaws limit faithful adherence to the prompt. The rendering quality presents notable challenges. While the background remains relatively crisp, character details suffer from distortion, reducing alignment to the prompt. The scene partially matches the description - a woman walking in a forest with a bag - but key nuances such as emotional tone and satchel positioning are muddled by artifacts. Fundamentally, the physical inconsistencies stem from perceptual morphing rather than physical law violations. The general motion and environment maintain plausible realism, yet persistent rendering flaws undermine consistent interpretation.<\\think>\n<answer>visual quality: 2; \ntext-to-video alignment: 3,\nphysical/common-sense consistency: 1"
|
| 136 |
+
}
|
| 137 |
+
]
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_q_align/q_align/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .model import MPLUGOwl2LlamaForCausalLM
|
| 2 |
+
from .evaluate import QAlignScorer, QAlignAestheticScorer, QAlignVideoScorer
|
| 3 |
+
from .load_video import load_video
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_q_align/q_align/constants.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CONTROLLER_HEART_BEAT_EXPIRATION = 30
|
| 2 |
+
WORKER_HEART_BEAT_INTERVAL = 15
|
| 3 |
+
|
| 4 |
+
LOGDIR = "./demo_logs"
|
| 5 |
+
|
| 6 |
+
# Model Constants
|
| 7 |
+
IGNORE_INDEX = -100
|
| 8 |
+
IMAGE_TOKEN_INDEX = -200
|
| 9 |
+
DEFAULT_IMAGE_TOKEN = "<|image|>"
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_q_align/q_align/conversation.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
from enum import auto, Enum
|
| 3 |
+
from typing import List, Tuple
|
| 4 |
+
from q_align.constants import DEFAULT_IMAGE_TOKEN
|
| 5 |
+
|
| 6 |
+
class SeparatorStyle(Enum):
|
| 7 |
+
"""Different separator style."""
|
| 8 |
+
SINGLE = auto()
|
| 9 |
+
TWO = auto()
|
| 10 |
+
TWO_NO_SYS = auto()
|
| 11 |
+
MPT = auto()
|
| 12 |
+
PLAIN = auto()
|
| 13 |
+
LLAMA_2 = auto()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclasses.dataclass
|
| 17 |
+
class Conversation:
|
| 18 |
+
"""A class that keeps all conversation history."""
|
| 19 |
+
system: str
|
| 20 |
+
roles: List[str]
|
| 21 |
+
messages: List[List[str]]
|
| 22 |
+
offset: int
|
| 23 |
+
sep_style: SeparatorStyle = SeparatorStyle.SINGLE
|
| 24 |
+
sep: str = "###"
|
| 25 |
+
sep2: str = None
|
| 26 |
+
version: str = "Unknown"
|
| 27 |
+
|
| 28 |
+
skip_next: bool = False
|
| 29 |
+
|
| 30 |
+
def get_prompt(self):
|
| 31 |
+
messages = self.messages
|
| 32 |
+
if len(messages) > 0 and type(messages[0][1]) is tuple:
|
| 33 |
+
messages = self.messages.copy()
|
| 34 |
+
init_role, init_msg = messages[0].copy()
|
| 35 |
+
# init_msg = init_msg[0].replace("<image>", "").strip()
|
| 36 |
+
# if 'mmtag' in self.version:
|
| 37 |
+
# messages[0] = (init_role, init_msg)
|
| 38 |
+
# messages.insert(0, (self.roles[0], "<Image><image></Image>"))
|
| 39 |
+
# messages.insert(1, (self.roles[1], "Received."))
|
| 40 |
+
# else:
|
| 41 |
+
# messages[0] = (init_role, "<image>\n" + init_msg)
|
| 42 |
+
init_msg = init_msg[0].replace(DEFAULT_IMAGE_TOKEN, "").strip()
|
| 43 |
+
messages[0] = (init_role, DEFAULT_IMAGE_TOKEN + init_msg)
|
| 44 |
+
|
| 45 |
+
if self.sep_style == SeparatorStyle.SINGLE:
|
| 46 |
+
ret = self.system + self.sep
|
| 47 |
+
for role, message in messages:
|
| 48 |
+
if message:
|
| 49 |
+
if type(message) is tuple:
|
| 50 |
+
message, _, _ = message
|
| 51 |
+
ret += role + ": " + message + self.sep
|
| 52 |
+
else:
|
| 53 |
+
ret += role + ":"
|
| 54 |
+
elif self.sep_style == SeparatorStyle.TWO:
|
| 55 |
+
seps = [self.sep, self.sep2]
|
| 56 |
+
ret = self.system + seps[0]
|
| 57 |
+
for i, (role, message) in enumerate(messages):
|
| 58 |
+
if message:
|
| 59 |
+
if type(message) is tuple:
|
| 60 |
+
message, _, _ = message
|
| 61 |
+
ret += role + ": " + message + seps[i % 2]
|
| 62 |
+
else:
|
| 63 |
+
ret += role + ":"
|
| 64 |
+
elif self.sep_style == SeparatorStyle.TWO_NO_SYS:
|
| 65 |
+
seps = [self.sep, self.sep2]
|
| 66 |
+
ret = ""
|
| 67 |
+
for i, (role, message) in enumerate(messages):
|
| 68 |
+
if message:
|
| 69 |
+
if type(message) is tuple:
|
| 70 |
+
message, _, _ = message
|
| 71 |
+
ret += role + ": " + message + seps[i % 2]
|
| 72 |
+
else:
|
| 73 |
+
ret += role + ":"
|
| 74 |
+
elif self.sep_style == SeparatorStyle.MPT:
|
| 75 |
+
ret = self.system + self.sep
|
| 76 |
+
for role, message in messages:
|
| 77 |
+
if message:
|
| 78 |
+
if type(message) is tuple:
|
| 79 |
+
message, _, _ = message
|
| 80 |
+
ret += role + message + self.sep
|
| 81 |
+
else:
|
| 82 |
+
ret += role
|
| 83 |
+
elif self.sep_style == SeparatorStyle.LLAMA_2:
|
| 84 |
+
wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n"
|
| 85 |
+
wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
|
| 86 |
+
ret = ""
|
| 87 |
+
|
| 88 |
+
for i, (role, message) in enumerate(messages):
|
| 89 |
+
if i == 0:
|
| 90 |
+
assert message, "first message should not be none"
|
| 91 |
+
assert role == self.roles[0], "first message should come from user"
|
| 92 |
+
if message:
|
| 93 |
+
if type(message) is tuple:
|
| 94 |
+
message, _, _ = message
|
| 95 |
+
if i == 0: message = wrap_sys(self.system) + message
|
| 96 |
+
if i % 2 == 0:
|
| 97 |
+
message = wrap_inst(message)
|
| 98 |
+
ret += self.sep + message
|
| 99 |
+
else:
|
| 100 |
+
ret += " " + message + " " + self.sep2
|
| 101 |
+
else:
|
| 102 |
+
ret += ""
|
| 103 |
+
ret = ret.lstrip(self.sep)
|
| 104 |
+
elif self.sep_style == SeparatorStyle.PLAIN:
|
| 105 |
+
seps = [self.sep, self.sep2]
|
| 106 |
+
ret = self.system
|
| 107 |
+
for i, (role, message) in enumerate(messages):
|
| 108 |
+
if message:
|
| 109 |
+
if type(message) is tuple:
|
| 110 |
+
message, _, _ = message
|
| 111 |
+
ret += message + seps[i % 2]
|
| 112 |
+
else:
|
| 113 |
+
ret += ""
|
| 114 |
+
else:
|
| 115 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
| 116 |
+
|
| 117 |
+
return ret
|
| 118 |
+
|
| 119 |
+
def append_message(self, role, message):
|
| 120 |
+
self.messages.append([role, message])
|
| 121 |
+
|
| 122 |
+
def get_images(self, return_pil=False):
|
| 123 |
+
images = []
|
| 124 |
+
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
| 125 |
+
if i % 2 == 0:
|
| 126 |
+
if type(msg) is tuple:
|
| 127 |
+
import base64
|
| 128 |
+
from io import BytesIO
|
| 129 |
+
from PIL import Image
|
| 130 |
+
msg, image, image_process_mode = msg
|
| 131 |
+
if image_process_mode == "Pad":
|
| 132 |
+
def expand2square(pil_img, background_color=(122, 116, 104)):
|
| 133 |
+
width, height = pil_img.size
|
| 134 |
+
if width == height:
|
| 135 |
+
return pil_img
|
| 136 |
+
elif width > height:
|
| 137 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
| 138 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
| 139 |
+
return result
|
| 140 |
+
else:
|
| 141 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
| 142 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
| 143 |
+
return result
|
| 144 |
+
image = expand2square(image)
|
| 145 |
+
elif image_process_mode in ["Default", "Crop"]:
|
| 146 |
+
pass
|
| 147 |
+
elif image_process_mode == "Resize":
|
| 148 |
+
image = image.resize((336, 336))
|
| 149 |
+
else:
|
| 150 |
+
raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
|
| 151 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
| 152 |
+
aspect_ratio = max_hw / min_hw
|
| 153 |
+
max_len, min_len = 800, 400
|
| 154 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
| 155 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
| 156 |
+
W, H = image.size
|
| 157 |
+
if longest_edge != max(image.size):
|
| 158 |
+
if H > W:
|
| 159 |
+
H, W = longest_edge, shortest_edge
|
| 160 |
+
else:
|
| 161 |
+
H, W = shortest_edge, longest_edge
|
| 162 |
+
image = image.resize((W, H))
|
| 163 |
+
if return_pil:
|
| 164 |
+
images.append(image)
|
| 165 |
+
else:
|
| 166 |
+
buffered = BytesIO()
|
| 167 |
+
image.save(buffered, format="PNG")
|
| 168 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 169 |
+
images.append(img_b64_str)
|
| 170 |
+
return images
|
| 171 |
+
|
| 172 |
+
def to_gradio_chatbot(self):
|
| 173 |
+
ret = []
|
| 174 |
+
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
| 175 |
+
if i % 2 == 0:
|
| 176 |
+
if type(msg) is tuple:
|
| 177 |
+
import base64
|
| 178 |
+
from io import BytesIO
|
| 179 |
+
msg, image, image_process_mode = msg
|
| 180 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
| 181 |
+
aspect_ratio = max_hw / min_hw
|
| 182 |
+
max_len, min_len = 800, 400
|
| 183 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
| 184 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
| 185 |
+
W, H = image.size
|
| 186 |
+
if H > W:
|
| 187 |
+
H, W = longest_edge, shortest_edge
|
| 188 |
+
else:
|
| 189 |
+
H, W = shortest_edge, longest_edge
|
| 190 |
+
image = image.resize((W, H))
|
| 191 |
+
buffered = BytesIO()
|
| 192 |
+
image.save(buffered, format="JPEG")
|
| 193 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 194 |
+
img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="user upload image" />'
|
| 195 |
+
msg = img_str + msg.replace('<|image|>', '').strip()
|
| 196 |
+
ret.append([msg, None])
|
| 197 |
+
else:
|
| 198 |
+
ret.append([msg, None])
|
| 199 |
+
else:
|
| 200 |
+
ret[-1][-1] = msg
|
| 201 |
+
return ret
|
| 202 |
+
|
| 203 |
+
def copy(self):
|
| 204 |
+
return Conversation(
|
| 205 |
+
system=self.system,
|
| 206 |
+
roles=self.roles,
|
| 207 |
+
messages=[[x, y] for x, y in self.messages],
|
| 208 |
+
offset=self.offset,
|
| 209 |
+
sep_style=self.sep_style,
|
| 210 |
+
sep=self.sep,
|
| 211 |
+
sep2=self.sep2,
|
| 212 |
+
version=self.version)
|
| 213 |
+
|
| 214 |
+
def dict(self):
|
| 215 |
+
if len(self.get_images()) > 0:
|
| 216 |
+
return {
|
| 217 |
+
"system": self.system,
|
| 218 |
+
"roles": self.roles,
|
| 219 |
+
"messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
|
| 220 |
+
"offset": self.offset,
|
| 221 |
+
"sep": self.sep,
|
| 222 |
+
"sep2": self.sep2,
|
| 223 |
+
}
|
| 224 |
+
return {
|
| 225 |
+
"system": self.system,
|
| 226 |
+
"roles": self.roles,
|
| 227 |
+
"messages": self.messages,
|
| 228 |
+
"offset": self.offset,
|
| 229 |
+
"sep": self.sep,
|
| 230 |
+
"sep2": self.sep2,
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
conv_vicuna_v0 = Conversation(
|
| 235 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
| 236 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
| 237 |
+
roles=("Human", "Assistant"),
|
| 238 |
+
messages=(
|
| 239 |
+
("Human", "What are the key differences between renewable and non-renewable energy sources?"),
|
| 240 |
+
("Assistant",
|
| 241 |
+
"Renewable energy sources are those that can be replenished naturally in a relatively "
|
| 242 |
+
"short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
|
| 243 |
+
"Non-renewable energy sources, on the other hand, are finite and will eventually be "
|
| 244 |
+
"depleted, such as coal, oil, and natural gas. Here are some key differences between "
|
| 245 |
+
"renewable and non-renewable energy sources:\n"
|
| 246 |
+
"1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
|
| 247 |
+
"energy sources are finite and will eventually run out.\n"
|
| 248 |
+
"2. Environmental impact: Renewable energy sources have a much lower environmental impact "
|
| 249 |
+
"than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
|
| 250 |
+
"and other negative effects.\n"
|
| 251 |
+
"3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
|
| 252 |
+
"have lower operational costs than non-renewable sources.\n"
|
| 253 |
+
"4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
|
| 254 |
+
"locations than non-renewable sources.\n"
|
| 255 |
+
"5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
|
| 256 |
+
"situations and needs, while non-renewable sources are more rigid and inflexible.\n"
|
| 257 |
+
"6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
|
| 258 |
+
"non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
|
| 259 |
+
),
|
| 260 |
+
offset=2,
|
| 261 |
+
sep_style=SeparatorStyle.SINGLE,
|
| 262 |
+
sep="###",
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
conv_vicuna_v1 = Conversation(
|
| 266 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
| 267 |
+
"The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
| 268 |
+
roles=("USER", "ASSISTANT"),
|
| 269 |
+
version="v1",
|
| 270 |
+
messages=(),
|
| 271 |
+
offset=0,
|
| 272 |
+
sep_style=SeparatorStyle.TWO,
|
| 273 |
+
sep=" ",
|
| 274 |
+
sep2="</s>",
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
conv_mplug_owl2 = Conversation(
|
| 278 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
| 279 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
| 280 |
+
roles=("USER", "ASSISTANT"),
|
| 281 |
+
version="v1",
|
| 282 |
+
messages=(),
|
| 283 |
+
offset=0,
|
| 284 |
+
sep_style=SeparatorStyle.TWO_NO_SYS,
|
| 285 |
+
sep=" ",
|
| 286 |
+
sep2="</s>",
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
# default_conversation = conv_vicuna_v1
|
| 290 |
+
default_conversation = conv_mplug_owl2
|
| 291 |
+
conv_templates = {
|
| 292 |
+
"default": conv_vicuna_v0,
|
| 293 |
+
"v0": conv_vicuna_v0,
|
| 294 |
+
"v1": conv_vicuna_v1,
|
| 295 |
+
"vicuna_v1": conv_vicuna_v1,
|
| 296 |
+
"mplug_owl2": conv_mplug_owl2,
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
if __name__ == "__main__":
|
| 301 |
+
print(default_conversation.get_prompt())
|
video_gen_14d/third_party/VideoScore2/eval/eval_methods/utils_q_align/q_align/evaluate/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .scorer import QAlignScorer, QAlignAestheticScorer, QAlignVideoScorer
|