| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | from datetime import datetime |
| 8 | from enum import Enum |
| 9 | |
| 10 | from typing import Any, Dict, List, Optional, Protocol |
| 11 | |
| 12 | from llama_models.schema_utils import json_schema_type, webmethod |
| 13 | |
| 14 | from pydantic import BaseModel, Field |
| 15 | |
| 16 | from llama_models.llama3.api.datatypes import * # noqa: F403 |
| 17 | from llama_stack.apis.dataset import * # noqa: F403 |
| 18 | from llama_stack.apis.common.training_types import * # noqa: F403 |
| 19 | |
| 20 | |
| 21 | class OptimizerType(Enum): |
| 22 | adam = "adam" |
| 23 | adamw = "adamw" |
| 24 | sgd = "sgd" |
| 25 | |
| 26 | |
| 27 | @json_schema_type |
| 28 | class OptimizerConfig(BaseModel): |
| 29 | optimizer_type: OptimizerType |
| 30 | lr: float |
| 31 | lr_min: float |
| 32 | weight_decay: float |
| 33 | |
| 34 | |
| 35 | @json_schema_type |
| 36 | class TrainingConfig(BaseModel): |
| 37 | n_epochs: int |
| 38 | batch_size: int |
| 39 | shuffle: bool |
| 40 | n_iters: int |
| 41 | |
| 42 | enable_activation_checkpointing: bool |
| 43 | memory_efficient_fsdp_wrap: bool |
| 44 | fsdp_cpu_offload: bool |
| 45 | |
| 46 | |
| 47 | @json_schema_type |
| 48 | class FinetuningAlgorithm(Enum): |
| 49 | full = "full" |
| 50 | lora = "lora" |
| 51 | qlora = "qlora" |
| 52 | dora = "dora" |
| 53 | |
| 54 | |
| 55 | @json_schema_type |
| 56 | class LoraFinetuningConfig(BaseModel): |
| 57 | lora_attn_modules: List[str] |
| 58 | apply_lora_to_mlp: bool |
| 59 | apply_lora_to_output: bool |
| 60 | rank: int |
| 61 | alpha: int |
| 62 | |
| 63 | |
| 64 | @json_schema_type |
| 65 | class QLoraFinetuningConfig(LoraFinetuningConfig): |
| 66 | pass |
| 67 | |
| 68 | |
| 69 | @json_schema_type |
| 70 | class DoraFinetuningConfig(LoraFinetuningConfig): |
| 71 | pass |
| 72 | |
| 73 | |
| 74 | @json_schema_type |
| 75 | class PostTrainingJobLogStream(BaseModel): |
| 76 | """Stream of logs from a finetuning job.""" |
| 77 | |
| 78 | job_uuid: str |
| 79 | log_lines: List[str] |
| 80 | |
| 81 | |
| 82 | @json_schema_type |
| 83 | class PostTrainingJobStatus(Enum): |
| 84 | running = "running" |
| 85 | completed = "completed" |
| 86 | failed = "failed" |
| 87 | scheduled = "scheduled" |
| 88 | |
| 89 | |
| 90 | @json_schema_type |
| 91 | class RLHFAlgorithm(Enum): |
| 92 | dpo = "dpo" |
| 93 | |
| 94 | |
| 95 | @json_schema_type |
| 96 | class DPOAlignmentConfig(BaseModel): |
| 97 | reward_scale: float |
| 98 | reward_clip: float |
| 99 | epsilon: float |
| 100 | gamma: float |
| 101 | |
| 102 | |
| 103 | @json_schema_type |
| 104 | class PostTrainingSFTRequest(BaseModel): |
| 105 | """Request to finetune a model.""" |
| 106 | |
| 107 | job_uuid: str |
| 108 | |
| 109 | model: str |
| 110 | dataset: TrainEvalDataset |
| 111 | validation_dataset: TrainEvalDataset |
| 112 | |
| 113 | algorithm: FinetuningAlgorithm |
| 114 | algorithm_config: Union[ |
| 115 | LoraFinetuningConfig, QLoraFinetuningConfig, DoraFinetuningConfig |
| 116 | ] |
| 117 | |
| 118 | optimizer_config: OptimizerConfig |
| 119 | training_config: TrainingConfig |
| 120 | |
| 121 | # TODO: define these |
| 122 | hyperparam_search_config: Dict[str, Any] |
| 123 | logger_config: Dict[str, Any] |
| 124 | |
| 125 | |
| 126 | @json_schema_type |
| 127 | class PostTrainingRLHFRequest(BaseModel): |
| 128 | """Request to finetune a model.""" |
| 129 | |
| 130 | job_uuid: str |
| 131 | |
| 132 | finetuned_model: URL |
| 133 | |
| 134 | dataset: TrainEvalDataset |
| 135 | validation_dataset: TrainEvalDataset |
| 136 | |
| 137 | algorithm: RLHFAlgorithm |
| 138 | algorithm_config: Union[DPOAlignmentConfig] |
| 139 | |
| 140 | optimizer_config: OptimizerConfig |
| 141 | training_config: TrainingConfig |
| 142 | |
| 143 | # TODO: define these |
| 144 | hyperparam_search_config: Dict[str, Any] |
| 145 | logger_config: Dict[str, Any] |
| 146 | |
| 147 | |
| 148 | class PostTrainingJob(BaseModel): |
| 149 | job_uuid: str |
| 150 | |
| 151 | |
| 152 | @json_schema_type |
| 153 | class PostTrainingJobStatusResponse(BaseModel): |
| 154 | """Status of a finetuning job.""" |
| 155 | |
| 156 | job_uuid: str |
| 157 | status: PostTrainingJobStatus |
| 158 | |
| 159 | scheduled_at: Optional[datetime] = None |
| 160 | started_at: Optional[datetime] = None |
| 161 | completed_at: Optional[datetime] = None |
| 162 | |
| 163 | resources_allocated: Optional[Dict[str, Any]] = None |
| 164 | |
| 165 | checkpoints: List[Checkpoint] = Field(default_factory=list) |
| 166 | |
| 167 | |
| 168 | @json_schema_type |
| 169 | class PostTrainingJobArtifactsResponse(BaseModel): |
| 170 | """Artifacts of a finetuning job.""" |
| 171 | |
| 172 | job_uuid: str |
| 173 | checkpoints: List[Checkpoint] = Field(default_factory=list) |
| 174 | |
| 175 | # TODO(ashwin): metrics, evals |
| 176 | |
| 177 | |
| 178 | class PostTraining(Protocol): |
| 179 | @webmethod(route="/post_training/supervised_fine_tune") |
| 180 | def supervised_fine_tune( |
| 181 | self, |
| 182 | job_uuid: str, |
| 183 | model: str, |
| 184 | dataset: TrainEvalDataset, |
| 185 | validation_dataset: TrainEvalDataset, |
| 186 | algorithm: FinetuningAlgorithm, |
| 187 | algorithm_config: Union[ |
| 188 | LoraFinetuningConfig, QLoraFinetuningConfig, DoraFinetuningConfig |
| 189 | ], |
| 190 | optimizer_config: OptimizerConfig, |
| 191 | training_config: TrainingConfig, |
| 192 | hyperparam_search_config: Dict[str, Any], |
| 193 | logger_config: Dict[str, Any], |
| 194 | ) -> PostTrainingJob: ... |
| 195 | |
| 196 | @webmethod(route="/post_training/preference_optimize") |
| 197 | def preference_optimize( |
| 198 | self, |
| 199 | job_uuid: str, |
| 200 | finetuned_model: URL, |
| 201 | dataset: TrainEvalDataset, |
| 202 | validation_dataset: TrainEvalDataset, |
| 203 | algorithm: RLHFAlgorithm, |
| 204 | algorithm_config: Union[DPOAlignmentConfig], |
| 205 | optimizer_config: OptimizerConfig, |
| 206 | training_config: TrainingConfig, |
| 207 | hyperparam_search_config: Dict[str, Any], |
| 208 | logger_config: Dict[str, Any], |
| 209 | ) -> PostTrainingJob: ... |
| 210 | |
| 211 | @webmethod(route="/post_training/jobs") |
| 212 | def get_training_jobs(self) -> List[PostTrainingJob]: ... |
| 213 | |
| 214 | # sends SSE stream of logs |
| 215 | @webmethod(route="/post_training/job/logs") |
| 216 | def get_training_job_logstream(self, job_uuid: str) -> PostTrainingJobLogStream: ... |
| 217 | |
| 218 | @webmethod(route="/post_training/job/status") |
| 219 | def get_training_job_status( |
| 220 | self, job_uuid: str |
| 221 | ) -> PostTrainingJobStatusResponse: ... |
| 222 | |
| 223 | @webmethod(route="/post_training/job/cancel") |
| 224 | def cancel_training_job(self, job_uuid: str) -> None: ... |
| 225 | |
| 226 | @webmethod(route="/post_training/job/artifacts") |
| 227 | def get_training_job_artifacts( |
| 228 | self, job_uuid: str |
| 229 | ) -> PostTrainingJobArtifactsResponse: ... |