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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its 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 |
+
Implement Actor
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
from typing import Any, Dict, Optional
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.distributed as dist
|
| 24 |
+
from einops import rearrange
|
| 25 |
+
from ray.experimental.tqdm_ray import tqdm
|
| 26 |
+
from torch import nn
|
| 27 |
+
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
|
| 28 |
+
|
| 29 |
+
from ...protocol import DataProto, batch_collate
|
| 30 |
+
from ...trainer.core_algos import average_loss, compute_kl, compute_policy_loss
|
| 31 |
+
from ...utils import torch_functional as VF
|
| 32 |
+
from ...utils.py_functional import append_to_dict
|
| 33 |
+
from ...utils.seqlen_balancing import prepare_dynamic_batch, restore_dynamic_batch
|
| 34 |
+
from ...utils.ulysses import gather_outputs_and_unpad, ulysses_pad_and_slice_inputs
|
| 35 |
+
from .base import BasePPOActor
|
| 36 |
+
from .config import ActorConfig
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, rearrange, unpad_input
|
| 41 |
+
except ImportError:
|
| 42 |
+
pass
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
__all__ = ["DataParallelPPOActor"]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class DataParallelPPOActor(BasePPOActor):
|
| 49 |
+
def __init__(
|
| 50 |
+
self,
|
| 51 |
+
config: ActorConfig,
|
| 52 |
+
actor_module: nn.Module,
|
| 53 |
+
actor_optimizer: Optional[torch.optim.Optimizer] = None,
|
| 54 |
+
):
|
| 55 |
+
"""
|
| 56 |
+
When optimizer is None, it is Reference Policy
|
| 57 |
+
"""
|
| 58 |
+
super().__init__(config)
|
| 59 |
+
self.rank = int(os.getenv("RANK", "0"))
|
| 60 |
+
self.world_size = int(os.getenv("WORLD_SIZE", "1"))
|
| 61 |
+
self.actor_module = actor_module
|
| 62 |
+
self.actor_optimizer = actor_optimizer
|
| 63 |
+
if config.use_torch_compile:
|
| 64 |
+
self.log_probs_from_logits = torch.compile(VF.log_probs_from_logits, dynamic=True)
|
| 65 |
+
else:
|
| 66 |
+
self.log_probs_from_logits = VF.log_probs_from_logits
|
| 67 |
+
|
| 68 |
+
def _forward_micro_batch(self, micro_batch: Dict[str, torch.Tensor], temperature: float) -> torch.Tensor:
|
| 69 |
+
"""
|
| 70 |
+
Returns:
|
| 71 |
+
log_probs: # (bs, response_len)
|
| 72 |
+
"""
|
| 73 |
+
input_ids = micro_batch["input_ids"]
|
| 74 |
+
batch_size, seqlen = input_ids.shape
|
| 75 |
+
attention_mask = micro_batch["attention_mask"]
|
| 76 |
+
position_ids = micro_batch["position_ids"]
|
| 77 |
+
responses = micro_batch["responses"]
|
| 78 |
+
response_length = responses.size(-1)
|
| 79 |
+
if position_ids.dim() == 3: # qwen2vl mrope
|
| 80 |
+
position_ids = position_ids.transpose(0, 1) # (bsz, 3, seqlen) -> (3, bsz, seqlen)
|
| 81 |
+
|
| 82 |
+
multi_modal_inputs = defaultdict(list)
|
| 83 |
+
if "multi_modal_inputs" in micro_batch:
|
| 84 |
+
multi_modal_inputs = batch_collate(micro_batch["multi_modal_inputs"])
|
| 85 |
+
multi_modal_inputs = {key: torch.cat(value, dim=0) for key, value in multi_modal_inputs.items()}
|
| 86 |
+
else:
|
| 87 |
+
multi_modal_inputs = {}
|
| 88 |
+
|
| 89 |
+
if self.config.padding_free:
|
| 90 |
+
input_ids_rmpad, indices, *_ = unpad_input(input_ids.unsqueeze(-1), attention_mask) # (total_nnz, 1)
|
| 91 |
+
input_ids_rmpad = input_ids_rmpad.transpose(0, 1) # (1, total_nnz)
|
| 92 |
+
|
| 93 |
+
# unpad the position_ids to align the rotary
|
| 94 |
+
if position_ids.dim() == 3:
|
| 95 |
+
position_ids_rmpad = (
|
| 96 |
+
index_first_axis(rearrange(position_ids, "c b s ... -> (b s) c ..."), indices)
|
| 97 |
+
.transpose(0, 1)
|
| 98 |
+
.unsqueeze(1)
|
| 99 |
+
) # (3, bsz, seqlen) -> (3, 1, bsz * seqlen)
|
| 100 |
+
else:
|
| 101 |
+
position_ids_rmpad = index_first_axis(
|
| 102 |
+
rearrange(position_ids.unsqueeze(-1), "b s ... -> (b s) ..."), indices
|
| 103 |
+
).transpose(0, 1)
|
| 104 |
+
|
| 105 |
+
# for compute the log_prob
|
| 106 |
+
input_ids_rmpad_rolled = torch.roll(input_ids_rmpad, shifts=-1, dims=1) # (1, total_nnz)
|
| 107 |
+
|
| 108 |
+
# pad and slice the inputs if sp > 1
|
| 109 |
+
if self.config.ulysses_size > 1:
|
| 110 |
+
input_ids_rmpad, position_ids_rmpad, pad_size = ulysses_pad_and_slice_inputs(
|
| 111 |
+
input_ids_rmpad, position_ids_rmpad, sp_size=self.config.ulysses_size
|
| 112 |
+
)
|
| 113 |
+
input_ids_rmpad_rolled, _, _ = ulysses_pad_and_slice_inputs(
|
| 114 |
+
input_ids_rmpad_rolled, None, self.config.ulysses_size
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
input_ids_rmpad_rolled = input_ids_rmpad_rolled.squeeze(0) # ((total_nnz / sp) + pad)
|
| 118 |
+
|
| 119 |
+
# only pass input_ids and position_ids to enable flash_attn_varlen
|
| 120 |
+
output = self.actor_module(
|
| 121 |
+
input_ids=input_ids_rmpad,
|
| 122 |
+
attention_mask=None,
|
| 123 |
+
position_ids=position_ids_rmpad,
|
| 124 |
+
**multi_modal_inputs,
|
| 125 |
+
use_cache=False,
|
| 126 |
+
) # prevent model thinks we are generating
|
| 127 |
+
logits_rmpad = output.logits.squeeze(0) # (total_nnz, vocab_size)
|
| 128 |
+
logits_rmpad.div_(temperature)
|
| 129 |
+
# ((total_nnz / sp) + pad)
|
| 130 |
+
log_probs = self.log_probs_from_logits(logits=logits_rmpad, labels=input_ids_rmpad_rolled)
|
| 131 |
+
|
| 132 |
+
# gather log_prob if sp > 1
|
| 133 |
+
if self.config.ulysses_size > 1:
|
| 134 |
+
# gather and unpad for the ulysses sp
|
| 135 |
+
log_probs = gather_outputs_and_unpad(log_probs, gather_dim=0, unpad_dim=0, padding_size=pad_size)
|
| 136 |
+
|
| 137 |
+
# pad back to (bsz, seqlen)
|
| 138 |
+
full_log_probs = pad_input(
|
| 139 |
+
hidden_states=log_probs.unsqueeze(-1), indices=indices, batch=batch_size, seqlen=seqlen
|
| 140 |
+
)
|
| 141 |
+
log_probs = full_log_probs.squeeze(-1)[:, -response_length - 1 : -1] # (bsz, response_length)
|
| 142 |
+
else:
|
| 143 |
+
output = self.actor_module(
|
| 144 |
+
input_ids=input_ids,
|
| 145 |
+
attention_mask=attention_mask,
|
| 146 |
+
position_ids=position_ids,
|
| 147 |
+
**multi_modal_inputs,
|
| 148 |
+
use_cache=False,
|
| 149 |
+
)
|
| 150 |
+
logits: torch.Tensor = output.logits
|
| 151 |
+
logits.div_(temperature)
|
| 152 |
+
logits = logits[:, -response_length - 1 : -1, :] # (bsz, response_length, vocab_size)
|
| 153 |
+
log_probs = self.log_probs_from_logits(logits, responses) # (bsz, response_length)
|
| 154 |
+
|
| 155 |
+
return log_probs
|
| 156 |
+
|
| 157 |
+
def _optimizer_step(self) -> torch.Tensor:
|
| 158 |
+
if isinstance(self.actor_module, FSDP):
|
| 159 |
+
grad_norm = self.actor_module.clip_grad_norm_(self.config.max_grad_norm)
|
| 160 |
+
else:
|
| 161 |
+
grad_norm = nn.utils.clip_grad_norm_(self.actor_module.parameters(), max_norm=self.config.max_grad_norm)
|
| 162 |
+
|
| 163 |
+
if not torch.isfinite(grad_norm):
|
| 164 |
+
print("Gradient norm is not finite. Skip update.")
|
| 165 |
+
else:
|
| 166 |
+
self.actor_optimizer.step()
|
| 167 |
+
|
| 168 |
+
self.actor_optimizer.zero_grad()
|
| 169 |
+
return grad_norm
|
| 170 |
+
|
| 171 |
+
@torch.no_grad()
|
| 172 |
+
def compute_log_prob(self, data: DataProto) -> torch.Tensor:
|
| 173 |
+
"""Compute the log probability of the responses given input_ids, attention_mask and position_ids
|
| 174 |
+
|
| 175 |
+
Args:
|
| 176 |
+
data (DataProto): a DataProto containing keys
|
| 177 |
+
|
| 178 |
+
``input_ids``: tensor of shape [batch_size, sequence_length]. torch.int64. Note that input_ids is the
|
| 179 |
+
concatenation of prompt and response. Note that ``sequence_length = prompt_length + response_length``.
|
| 180 |
+
|
| 181 |
+
``attention_mask``: tensor of shape [batch_size, sequence_length]. torch.int64.
|
| 182 |
+
|
| 183 |
+
``position_ids``: tensor of shape [batch_size, sequence_length]. torch.int64.
|
| 184 |
+
|
| 185 |
+
``responses``: tensor of shape [batch_size, response_length]. torch.int64.
|
| 186 |
+
|
| 187 |
+
Returns:
|
| 188 |
+
torch.Tensor: the log_prob tensor
|
| 189 |
+
"""
|
| 190 |
+
self.actor_module.eval()
|
| 191 |
+
|
| 192 |
+
temperature = data.meta_info["temperature"]
|
| 193 |
+
select_keys = ["input_ids", "attention_mask", "position_ids", "responses"]
|
| 194 |
+
non_tensor_select_keys = ["multi_modal_inputs"]
|
| 195 |
+
|
| 196 |
+
data = data.select(select_keys, non_tensor_select_keys)
|
| 197 |
+
if self.config.dynamic_batching:
|
| 198 |
+
max_token_len = self.config.micro_batch_size_per_device_for_experience * data.batch["input_ids"].size(-1)
|
| 199 |
+
micro_batches, batch_idx_list = prepare_dynamic_batch(data, max_token_len=max_token_len)
|
| 200 |
+
else:
|
| 201 |
+
micro_batches = data.split(self.config.micro_batch_size_per_device_for_experience)
|
| 202 |
+
|
| 203 |
+
log_probs_lst = []
|
| 204 |
+
if self.rank == 0:
|
| 205 |
+
micro_batches = tqdm(micro_batches, desc="Compute log probs", position=1)
|
| 206 |
+
|
| 207 |
+
for micro_batch in micro_batches:
|
| 208 |
+
model_inputs = {**micro_batch.batch, **micro_batch.non_tensor_batch}
|
| 209 |
+
log_probs = self._forward_micro_batch(model_inputs, temperature=temperature)
|
| 210 |
+
log_probs_lst.append(log_probs)
|
| 211 |
+
|
| 212 |
+
log_probs = torch.concat(log_probs_lst, dim=0)
|
| 213 |
+
|
| 214 |
+
if self.config.dynamic_batching:
|
| 215 |
+
log_probs = restore_dynamic_batch(log_probs, batch_idx_list)
|
| 216 |
+
|
| 217 |
+
return log_probs
|
| 218 |
+
|
| 219 |
+
def update_policy(self, data: DataProto) -> Dict[str, Any]:
|
| 220 |
+
self.actor_module.train()
|
| 221 |
+
|
| 222 |
+
temperature = data.meta_info["temperature"] # temperature must be in the data.meta_info to avoid slient error
|
| 223 |
+
select_keys = ["input_ids", "attention_mask", "position_ids", "responses", "response_mask"]
|
| 224 |
+
select_keys.extend(["old_log_probs", "ref_log_probs", "advantages"])
|
| 225 |
+
non_tensor_select_keys = ["multi_modal_inputs"]
|
| 226 |
+
|
| 227 |
+
# Split to make minibatch iterator for updating the actor
|
| 228 |
+
# See PPO paper for details. https://arxiv.org/abs/1707.06347
|
| 229 |
+
mini_batches = data.select(select_keys, non_tensor_select_keys).split(self.config.global_batch_size_per_device)
|
| 230 |
+
|
| 231 |
+
metrics = defaultdict(list)
|
| 232 |
+
for _ in range(self.config.ppo_epochs):
|
| 233 |
+
if self.rank == 0:
|
| 234 |
+
mini_batches = tqdm(mini_batches, desc="Train mini-batches", position=1)
|
| 235 |
+
|
| 236 |
+
for mini_batch in mini_batches:
|
| 237 |
+
total_response_tokens = torch.sum(mini_batch.batch["response_mask"])
|
| 238 |
+
dist.all_reduce(total_response_tokens, op=dist.ReduceOp.SUM)
|
| 239 |
+
|
| 240 |
+
if self.config.dynamic_batching:
|
| 241 |
+
max_input_len = mini_batch.batch["input_ids"].size(-1)
|
| 242 |
+
max_token_len = self.config.micro_batch_size_per_device_for_update * max_input_len
|
| 243 |
+
micro_batches, _ = prepare_dynamic_batch(mini_batch, max_token_len=max_token_len)
|
| 244 |
+
else:
|
| 245 |
+
micro_batches = mini_batch.split(self.config.micro_batch_size_per_device_for_update)
|
| 246 |
+
|
| 247 |
+
if self.rank == 0:
|
| 248 |
+
micro_batches = tqdm(micro_batches, desc="Update policy", position=2)
|
| 249 |
+
|
| 250 |
+
for micro_batch in micro_batches:
|
| 251 |
+
model_inputs = {**micro_batch.batch, **micro_batch.non_tensor_batch}
|
| 252 |
+
response_mask = model_inputs["response_mask"]
|
| 253 |
+
old_log_probs = model_inputs["old_log_probs"]
|
| 254 |
+
advantages = model_inputs["advantages"]
|
| 255 |
+
|
| 256 |
+
# all return: (bsz, response_length)
|
| 257 |
+
log_probs = self._forward_micro_batch(model_inputs, temperature=temperature)
|
| 258 |
+
|
| 259 |
+
pg_loss, pg_metrics = compute_policy_loss(
|
| 260 |
+
old_log_probs=old_log_probs,
|
| 261 |
+
log_probs=log_probs,
|
| 262 |
+
advantages=advantages,
|
| 263 |
+
response_mask=response_mask,
|
| 264 |
+
clip_ratio_low=self.config.clip_ratio_low,
|
| 265 |
+
clip_ratio_high=self.config.clip_ratio_high,
|
| 266 |
+
clip_ratio_dual=self.config.clip_ratio_dual,
|
| 267 |
+
loss_avg_mode=self.config.loss_avg_mode,
|
| 268 |
+
)
|
| 269 |
+
if self.config.use_kl_loss and "ref_log_probs" in model_inputs:
|
| 270 |
+
ref_log_probs = model_inputs["ref_log_probs"]
|
| 271 |
+
# compute kl loss
|
| 272 |
+
kld = compute_kl(
|
| 273 |
+
log_probs=log_probs,
|
| 274 |
+
ref_log_probs=ref_log_probs,
|
| 275 |
+
kl_penalty=self.config.kl_penalty,
|
| 276 |
+
)
|
| 277 |
+
kl_loss = average_loss(kld, response_mask, mode=self.config.loss_avg_mode)
|
| 278 |
+
loss = pg_loss + kl_loss * self.config.kl_coef
|
| 279 |
+
metrics["actor/kl_loss"] = kl_loss.detach().item()
|
| 280 |
+
metrics["actor/kl_coef"] = self.config.kl_coef
|
| 281 |
+
else:
|
| 282 |
+
loss = pg_loss
|
| 283 |
+
|
| 284 |
+
loss = loss * torch.sum(response_mask) * self.world_size / total_response_tokens
|
| 285 |
+
loss.backward()
|
| 286 |
+
|
| 287 |
+
batch_metrics = {
|
| 288 |
+
"actor/pg_loss": pg_loss.detach().item(),
|
| 289 |
+
"actor/pg_clipfrac_higher": pg_metrics["pg_clipfrac_higher"],
|
| 290 |
+
"actor/pg_clipfrac_lower": pg_metrics["pg_clipfrac_lower"],
|
| 291 |
+
"actor/entropy_loss": pg_metrics["entropy_loss"],
|
| 292 |
+
"actor/ppo_kl": pg_metrics["ppo_kl"],
|
| 293 |
+
}
|
| 294 |
+
append_to_dict(metrics, batch_metrics)
|
| 295 |
+
|
| 296 |
+
grad_norm = self._optimizer_step()
|
| 297 |
+
append_to_dict(metrics, {"actor/grad_norm": grad_norm.detach().item()})
|
| 298 |
+
|
| 299 |
+
return metrics
|