|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""Algorithm classes.""" |
| 3 | + |
| 4 | +from abc import ABC, ABCMeta |
| 5 | +from typing import Dict |
| 6 | + |
| 7 | +from trinity.buffer.schema.sql_schema import DPODataModel, ExperienceModel, SFTDataModel |
| 8 | +from trinity.common.config import Config |
| 9 | +from trinity.common.constants import SyncMethod |
| 10 | +from trinity.common.experience import Experience, Experiences |
| 11 | +from trinity.utils.log import get_logger |
| 12 | +from trinity.utils.registry import Registry |
| 13 | + |
| 14 | +logger = get_logger(__name__) |
| 15 | + |
| 16 | +ALGORITHM_TYPE = Registry("algorithm") |
| 17 | + |
| 18 | + |
| 19 | +class ConstantMeta(ABCMeta): |
| 20 | + def __setattr__(cls, name, value): |
| 21 | + if name in cls.__dict__: |
| 22 | + raise AttributeError(f"{name} is already defined in {cls.__name__}") |
| 23 | + return super().__setattr__(name, value) |
| 24 | + |
| 25 | + |
| 26 | +class AlgorithmType(ABC, metaclass=ConstantMeta): |
| 27 | + use_critic: bool |
| 28 | + use_reference: bool |
| 29 | + use_advantage: bool |
| 30 | + use_rollout: bool |
| 31 | + can_balance_batch: bool |
| 32 | + schema: type |
| 33 | + |
| 34 | + @classmethod |
| 35 | + def gather_experience(cls, exps: list[Experience], pad_token_id: int = 0) -> Experiences: |
| 36 | + return Experiences.gather_experiences(exps, pad_token_id) |
| 37 | + |
| 38 | + @classmethod |
| 39 | + def get_default_config(cls) -> Dict: |
| 40 | + raise NotImplementedError |
| 41 | + |
| 42 | + @classmethod |
| 43 | + def name(cls) -> str: |
| 44 | + return cls._name |
| 45 | + |
| 46 | + @classmethod |
| 47 | + def check_config(cls, config: Config) -> None: |
| 48 | + pass |
| 49 | + |
| 50 | + |
| 51 | +@ALGORITHM_TYPE.register_module("sft") |
| 52 | +class SFTAlgorithm(AlgorithmType): |
| 53 | + """SFT Algorithm.""" |
| 54 | + |
| 55 | + use_critic: bool = False |
| 56 | + use_reference: bool = False |
| 57 | + use_advantage: bool = False |
| 58 | + use_rollout: bool = False |
| 59 | + can_balance_batch: bool = True |
| 60 | + schema: type = SFTDataModel |
| 61 | + |
| 62 | + @classmethod |
| 63 | + def get_default_config(cls) -> Dict: |
| 64 | + return { |
| 65 | + "policy_loss_fn": "sft", |
| 66 | + "kl_loss_fn": "none", |
| 67 | + "entropy_loss_fn": "none", |
| 68 | + } |
| 69 | + |
| 70 | + |
| 71 | +@ALGORITHM_TYPE.register_module("ppo") |
| 72 | +class PPOAlgorithm(AlgorithmType): |
| 73 | + """PPO Algorithm.""" |
| 74 | + |
| 75 | + use_critic: bool = True |
| 76 | + use_reference: bool = True |
| 77 | + use_advantage: bool = True |
| 78 | + use_rollout: bool = True |
| 79 | + can_balance_batch: bool = True |
| 80 | + schema: type = ExperienceModel |
| 81 | + |
| 82 | + @classmethod |
| 83 | + def get_default_config(cls) -> Dict: |
| 84 | + return { |
| 85 | + "repeat_times": 1, |
| 86 | + "policy_loss_fn": "ppo", |
| 87 | + "advantage_fn": "ppo", |
| 88 | + "kl_penalty_fn": "none", |
| 89 | + "kl_loss_fn": "k2", |
| 90 | + "entropy_loss_fn": "basic", |
| 91 | + } |
| 92 | + |
| 93 | + |
| 94 | +@ALGORITHM_TYPE.register_module("grpo") |
| 95 | +class GRPOAlgorithm(AlgorithmType): |
| 96 | + """GRPO algorithm.""" |
| 97 | + |
| 98 | + use_critic: bool = False |
| 99 | + use_reference: bool = True |
| 100 | + use_advantage: bool = True |
| 101 | + use_rollout: bool = True |
| 102 | + can_balance_batch: bool = True |
| 103 | + schema: type = ExperienceModel |
| 104 | + |
| 105 | + @classmethod |
| 106 | + def get_default_config(cls) -> Dict: |
| 107 | + return { |
| 108 | + "repeat_times": 2, |
| 109 | + "policy_loss_fn": "ppo", |
| 110 | + "advantage_fn": "grpo", |
| 111 | + "kl_penalty_fn": "none", |
| 112 | + "kl_loss_fn": "k2", |
| 113 | + "entropy_loss_fn": "basic", |
| 114 | + } |
| 115 | + |
| 116 | + |
| 117 | +@ALGORITHM_TYPE.register_module("opmd") |
| 118 | +class OPMDAlgorithm(AlgorithmType): |
| 119 | + """OPMD algorithm.""" |
| 120 | + |
| 121 | + use_critic: bool = False |
| 122 | + use_reference: bool = True |
| 123 | + use_advantage: bool = True |
| 124 | + use_rollout: bool = True |
| 125 | + can_balance_batch: bool = True |
| 126 | + schema: type = ExperienceModel |
| 127 | + |
| 128 | + @classmethod |
| 129 | + def get_default_config(cls) -> Dict: |
| 130 | + return { |
| 131 | + "repeat_times": 2, |
| 132 | + "policy_loss_fn": "opmd", |
| 133 | + "advantage_fn": "opmd", |
| 134 | + "kl_penalty_fn": "none", |
| 135 | + "kl_loss_fn": "k2", |
| 136 | + "entropy_loss_fn": "basic", |
| 137 | + } |
| 138 | + |
| 139 | + |
| 140 | +@ALGORITHM_TYPE.register_module("dpo") |
| 141 | +class DPOAlgorithm(AlgorithmType): |
| 142 | + """DPO algorithm.""" |
| 143 | + |
| 144 | + use_critic: bool = False |
| 145 | + use_reference: bool = True |
| 146 | + use_advantage: bool = False |
| 147 | + use_rollout: bool = False |
| 148 | + can_balance_batch: bool = False |
| 149 | + schema: type = DPODataModel |
| 150 | + |
| 151 | + @classmethod |
| 152 | + def gather_experience(cls, exps: list[Experience], pad_token_id: int = 0) -> Experiences: |
| 153 | + return Experiences.gather_dpo_experiences(exps, pad_token_id) |
| 154 | + |
| 155 | + @classmethod |
| 156 | + def get_default_config(cls) -> Dict: |
| 157 | + return { |
| 158 | + "repeat_times": 2, # fake repeat times |
| 159 | + "policy_loss_fn": "dpo", |
| 160 | + "kl_loss_fn": "k2", |
| 161 | + "entropy_loss_fn": "basic", |
| 162 | + } |
| 163 | + |
| 164 | + @classmethod |
| 165 | + def check_config(cls, config: Config) -> None: |
| 166 | + if config.model == "train": |
| 167 | + if ( |
| 168 | + config.buffer.trainer_input.experience_buffer is None |
| 169 | + or not config.buffer.trainer_input.experience_buffer.path |
| 170 | + ): |
| 171 | + raise ValueError( |
| 172 | + "`buffer.trainer_input.experience_buffer.path` is required when `algorithm.algorithm_type == dpo`" |
| 173 | + ) |
| 174 | + elif config.mode in ["both", "explore"]: |
| 175 | + raise ValueError(f"DPO does not support `{config.mode}` mode") |
| 176 | + |
| 177 | + if config.synchronizer.sync_method != SyncMethod.CHECKPOINT: |
| 178 | + config.synchronizer.sync_method = SyncMethod.CHECKPOINT |
| 179 | + logger.warning( |
| 180 | + "DPO only supports checkpoint synchronization, set `synchronizer.sync_method` to `checkpoint`." |
| 181 | + ) |
| 182 | + if config.algorithm.repeat_times != 2: |
| 183 | + config.algorithm.repeat_times = 2 |
| 184 | + logger.warning( |
| 185 | + "DPO only supports 2 repeat times, set `algorithm.repeat_times` to 2." |
| 186 | + ) # no need to warn |
0 commit comments