|
| 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 | +from typing import Any, Dict, List |
| 16 | + |
| 17 | +import numpy as np |
| 18 | +import torch |
| 19 | + |
| 20 | +from ..protocol import DataProto |
| 21 | + |
| 22 | + |
| 23 | +def _compute_response_info(batch: DataProto) -> Dict[str, Any]: |
| 24 | + response_length = batch.batch["responses"].shape[-1] |
| 25 | + prompt_mask = batch.batch["attention_mask"][:, :-response_length] |
| 26 | + response_mask = batch.batch["attention_mask"][:, -response_length:] |
| 27 | + prompt_length = prompt_mask.sum(-1).float() |
| 28 | + response_length = response_mask.sum(-1).float() # (batch_size,) |
| 29 | + return dict( |
| 30 | + response_mask=response_mask, |
| 31 | + prompt_length=prompt_length, |
| 32 | + response_length=response_length, |
| 33 | + ) |
| 34 | + |
| 35 | + |
| 36 | +def reduce_metrics(metrics: Dict[str, List[Any]]) -> Dict[str, Any]: |
| 37 | + return {key: np.mean(value) for key, value in metrics.items()} |
| 38 | + |
| 39 | + |
| 40 | +def compute_data_metrics(batch: DataProto, use_critic: bool = False) -> Dict[str, Any]: |
| 41 | + sequence_score = batch.batch["token_level_scores"].sum(-1) |
| 42 | + sequence_reward = batch.batch["token_level_rewards"].sum(-1) |
| 43 | + |
| 44 | + advantages = batch.batch["advantages"] |
| 45 | + returns = batch.batch["returns"] |
| 46 | + |
| 47 | + max_response_length = batch.batch["responses"].size(-1) |
| 48 | + |
| 49 | + prompt_mask = batch.batch["attention_mask"][:, :-max_response_length].bool() |
| 50 | + response_mask = batch.batch["attention_mask"][:, -max_response_length:].bool() |
| 51 | + |
| 52 | + max_prompt_length = prompt_mask.size(-1) |
| 53 | + |
| 54 | + response_info = _compute_response_info(batch) |
| 55 | + prompt_length = response_info["prompt_length"] |
| 56 | + response_length = response_info["response_length"] |
| 57 | + |
| 58 | + valid_adv = torch.masked_select(advantages, response_mask) |
| 59 | + valid_returns = torch.masked_select(returns, response_mask) |
| 60 | + |
| 61 | + if use_critic: |
| 62 | + values = batch.batch["values"] |
| 63 | + valid_values = torch.masked_select(values, response_mask) |
| 64 | + return_diff_var = torch.var(valid_returns - valid_values) |
| 65 | + return_var = torch.var(valid_returns) |
| 66 | + |
| 67 | + metrics = { |
| 68 | + # score |
| 69 | + "critic/score/mean": torch.mean(sequence_score).detach().item(), |
| 70 | + "critic/score/max": torch.max(sequence_score).detach().item(), |
| 71 | + "critic/score/min": torch.min(sequence_score).detach().item(), |
| 72 | + # reward |
| 73 | + "critic/rewards/mean": torch.mean(sequence_reward).detach().item(), |
| 74 | + "critic/rewards/max": torch.max(sequence_reward).detach().item(), |
| 75 | + "critic/rewards/min": torch.min(sequence_reward).detach().item(), |
| 76 | + # adv |
| 77 | + "critic/advantages/mean": torch.mean(valid_adv).detach().item(), |
| 78 | + "critic/advantages/max": torch.max(valid_adv).detach().item(), |
| 79 | + "critic/advantages/min": torch.min(valid_adv).detach().item(), |
| 80 | + # returns |
| 81 | + "critic/returns/mean": torch.mean(valid_returns).detach().item(), |
| 82 | + "critic/returns/max": torch.max(valid_returns).detach().item(), |
| 83 | + "critic/returns/min": torch.min(valid_returns).detach().item(), |
| 84 | + **( |
| 85 | + { |
| 86 | + # values |
| 87 | + "critic/values/mean": torch.mean(valid_values).detach().item(), |
| 88 | + "critic/values/max": torch.max(valid_values).detach().item(), |
| 89 | + "critic/values/min": torch.min(valid_values).detach().item(), |
| 90 | + # vf explained var |
| 91 | + "critic/vf_explained_var": (1.0 - return_diff_var / (return_var + 1e-5)).detach().item(), |
| 92 | + } |
| 93 | + if use_critic |
| 94 | + else {} |
| 95 | + ), |
| 96 | + # response length |
| 97 | + "response_length/mean": torch.mean(response_length).detach().item(), |
| 98 | + "response_length/max": torch.max(response_length).detach().item(), |
| 99 | + "response_length/min": torch.min(response_length).detach().item(), |
| 100 | + "response_length/clip_ratio": torch.mean(torch.eq(response_length, max_response_length).float()) |
| 101 | + .detach() |
| 102 | + .item(), |
| 103 | + # prompt length |
| 104 | + "prompt_length/mean": torch.mean(prompt_length).detach().item(), |
| 105 | + "prompt_length/max": torch.max(prompt_length).detach().item(), |
| 106 | + "prompt_length/min": torch.min(prompt_length).detach().item(), |
| 107 | + "prompt_length/clip_ratio": torch.mean(torch.eq(prompt_length, max_prompt_length).float()).detach().item(), |
| 108 | + } |
| 109 | + return metrics |
| 110 | + |
| 111 | + |
| 112 | +def compute_timing_metrics(batch: DataProto, timing_raw: Dict[str, float]) -> Dict[str, Any]: |
| 113 | + response_info = _compute_response_info(batch) |
| 114 | + num_prompt_tokens = torch.sum(response_info["prompt_length"]).item() |
| 115 | + num_response_tokens = torch.sum(response_info["response_length"]).item() |
| 116 | + num_overall_tokens = num_prompt_tokens + num_response_tokens |
| 117 | + num_tokens_of_section = { |
| 118 | + "gen": num_response_tokens, |
| 119 | + **{name: num_overall_tokens for name in ["ref", "values", "adv", "update_critic", "update_actor"]}, |
| 120 | + } |
| 121 | + return { |
| 122 | + **{f"timing_s/{name}": value for name, value in timing_raw.items()}, |
| 123 | + **{ |
| 124 | + f"timing_per_token_ms/{name}": timing_raw[name] * 1000 / num_tokens_of_section[name] |
| 125 | + for name in set(num_tokens_of_section.keys()) & set(timing_raw.keys()) |
| 126 | + }, |
| 127 | + } |
| 128 | + |
| 129 | + |
| 130 | +def compute_throughout_metrics(batch: DataProto, timing_raw: Dict[str, float], n_gpus: int) -> Dict[str, Any]: |
| 131 | + total_num_tokens = sum(batch.meta_info["global_token_num"]) |
| 132 | + time = timing_raw["step"] |
| 133 | + return { |
| 134 | + "perf/total_num_tokens": total_num_tokens, |
| 135 | + "perf/time_per_step": time, |
| 136 | + "perf/throughput": total_num_tokens / (time * n_gpus), |
| 137 | + } |
0 commit comments