|
| 1 | +# Copyright 2025 The Kubeflow Authors. |
| 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 importlib import resources |
| 16 | +from pathlib import Path |
| 17 | +from typing import Dict, List, Optional |
| 18 | + |
| 19 | +import yaml |
| 20 | +from kubeflow.trainer import models |
| 21 | +from kubeflow.trainer.api.abstract_trainer_client import AbstractTrainerClient |
| 22 | +from kubeflow.trainer.constants import constants |
| 23 | +from kubeflow.trainer.job_runners import DockerJobRunner, JobRunner |
| 24 | +from kubeflow.trainer.types import types |
| 25 | +from kubeflow.trainer.utils import utils |
| 26 | + |
| 27 | + |
| 28 | +class LocalTrainerClient(AbstractTrainerClient): |
| 29 | + """LocalTrainerClient exposes functionality for running training jobs locally. |
| 30 | +
|
| 31 | + A Kubernetes cluster is not required. |
| 32 | + It exposes the same interface as the TrainerClient. |
| 33 | +
|
| 34 | + Args: |
| 35 | + local_runtimes_path: The path to the directory containing runtime YAML files. |
| 36 | + Defaults to the runtimes included with the package. |
| 37 | + job_runner: The job runner to use for local training. |
| 38 | + Options include the DockerJobRunner and PodmanJobRunner. |
| 39 | + Defaults to the Docker job runner. |
| 40 | + """ |
| 41 | + |
| 42 | + def __init__( |
| 43 | + self, |
| 44 | + local_runtimes_path: Optional[Path] = None, |
| 45 | + job_runner: Optional[JobRunner] = None, |
| 46 | + ): |
| 47 | + print( |
| 48 | + "Warning: LocalTrainerClient is an alpha feature for Kubeflow Trainer. " |
| 49 | + "Some features may be unstable or unimplemented." |
| 50 | + ) |
| 51 | + |
| 52 | + if local_runtimes_path is None: |
| 53 | + self.local_runtimes_path = ( |
| 54 | + resources.files(constants.PACKAGE_NAME) / constants.LOCAL_RUNTIMES_PATH |
| 55 | + ) |
| 56 | + else: |
| 57 | + self.local_runtimes_path = local_runtimes_path |
| 58 | + |
| 59 | + if job_runner is None: |
| 60 | + self.job_runner = DockerJobRunner() |
| 61 | + else: |
| 62 | + self.job_runner = job_runner |
| 63 | + |
| 64 | + def list_runtimes(self) -> List[types.Runtime]: |
| 65 | + """Lists all runtimes. |
| 66 | +
|
| 67 | + Returns: |
| 68 | + A list of runtime objects. |
| 69 | + """ |
| 70 | + runtimes = [] |
| 71 | + for cr in self.__list_runtime_crs(): |
| 72 | + runtimes.append(utils.get_runtime_from_crd(cr)) |
| 73 | + return runtimes |
| 74 | + |
| 75 | + def get_runtime(self, name: str) -> types.Runtime: |
| 76 | + """Get a specific runtime by name. |
| 77 | +
|
| 78 | + Args: |
| 79 | + name: The name of the runtime. |
| 80 | +
|
| 81 | + Returns: |
| 82 | + A runtime object. |
| 83 | +
|
| 84 | + Raises: |
| 85 | + RuntimeError: if the specified runtime cannot be found. |
| 86 | + """ |
| 87 | + for r in self.list_runtimes(): |
| 88 | + if r.name == name: |
| 89 | + return r |
| 90 | + raise RuntimeError(f"No runtime found with name '{name}'") |
| 91 | + |
| 92 | + def train( |
| 93 | + self, |
| 94 | + runtime: types.Runtime = types.DEFAULT_RUNTIME, |
| 95 | + initializer: Optional[types.Initializer] = None, |
| 96 | + trainer: Optional[types.CustomTrainer] = None, |
| 97 | + ) -> str: |
| 98 | + """Starts a training job. |
| 99 | +
|
| 100 | + Args: |
| 101 | + runtime: Config for the train job's runtime. |
| 102 | + trainer: Config for the function that encapsulates the model training process. |
| 103 | + initializer: Config for dataset and model initialization. |
| 104 | +
|
| 105 | + Returns: |
| 106 | + The generated name of the training job. |
| 107 | +
|
| 108 | + Raises: |
| 109 | + RuntimeError: if the specified runtime cannot be found, |
| 110 | + or the runtime container cannot be found, |
| 111 | + or the runtime container image is not specified. |
| 112 | + """ |
| 113 | + runtime_cr = self.__get_runtime_cr(runtime.name) |
| 114 | + if runtime_cr is None: |
| 115 | + raise RuntimeError(f"No runtime found with name '{runtime.name}'") |
| 116 | + |
| 117 | + runtime_container = utils.get_runtime_trainer_container( |
| 118 | + runtime_cr.spec.template.spec.replicated_jobs |
| 119 | + ) |
| 120 | + if runtime_container is None: |
| 121 | + raise RuntimeError("No runtime container found") |
| 122 | + |
| 123 | + image = runtime_container.image |
| 124 | + if image is None: |
| 125 | + raise RuntimeError("No runtime container image specified") |
| 126 | + |
| 127 | + if trainer and trainer.func: |
| 128 | + entrypoint, command = utils.get_entrypoint_using_train_func( |
| 129 | + runtime, |
| 130 | + trainer.func, |
| 131 | + trainer.func_args, |
| 132 | + trainer.pip_index_url, |
| 133 | + trainer.packages_to_install, |
| 134 | + ) |
| 135 | + else: |
| 136 | + entrypoint = runtime_container.command |
| 137 | + command = runtime_container.args |
| 138 | + |
| 139 | + if trainer and trainer.num_nodes: |
| 140 | + num_nodes = trainer.num_nodes |
| 141 | + else: |
| 142 | + num_nodes = 1 |
| 143 | + |
| 144 | + train_job_name = self.job_runner.create_job( |
| 145 | + image=image, |
| 146 | + entrypoint=entrypoint, |
| 147 | + command=command, |
| 148 | + num_nodes=num_nodes, |
| 149 | + framework=runtime.trainer.framework, |
| 150 | + runtime_name=runtime.name, |
| 151 | + ) |
| 152 | + return train_job_name |
| 153 | + |
| 154 | + def list_jobs( |
| 155 | + self, runtime: Optional[types.Runtime] = None |
| 156 | + ) -> List[types.TrainJob]: |
| 157 | + """Lists all training jobs. |
| 158 | +
|
| 159 | + Args: |
| 160 | + runtime: If provided, only return jobs that use the given runtime. |
| 161 | +
|
| 162 | + Returns: |
| 163 | + A list of training jobs. |
| 164 | + """ |
| 165 | + runtime_name = runtime.name if runtime else None |
| 166 | + container_jobs = self.job_runner.list_jobs(runtime_name) |
| 167 | + |
| 168 | + train_jobs = [] |
| 169 | + for container_job in container_jobs: |
| 170 | + train_jobs.append(self.__container_job_to_train_job(container_job)) |
| 171 | + return train_jobs |
| 172 | + |
| 173 | + def get_job(self, name: str) -> types.TrainJob: |
| 174 | + """Get a specific training job by name. |
| 175 | +
|
| 176 | + Args: |
| 177 | + name: The name of the training job to get. |
| 178 | +
|
| 179 | + Returns: |
| 180 | + A training job. |
| 181 | + """ |
| 182 | + container_job = self.job_runner.get_job(name) |
| 183 | + return self.__container_job_to_train_job(container_job) |
| 184 | + |
| 185 | + def get_job_logs( |
| 186 | + self, |
| 187 | + name: str, |
| 188 | + follow: Optional[bool] = False, |
| 189 | + step: str = constants.NODE, |
| 190 | + node_rank: int = 0, |
| 191 | + ) -> Dict[str, str]: |
| 192 | + """Gets logs for the specified training job |
| 193 | + Args: |
| 194 | + name (str): The name of the training job |
| 195 | + follow (bool): If true, follows job logs and prints them to standard out (default False) |
| 196 | + step (int): The training job step to target (default "node") |
| 197 | + node_rank (int): The node rank to retrieve logs from (default 0) |
| 198 | +
|
| 199 | + Returns: |
| 200 | + Dict[str, str]: The logs of the training job, where the key is the |
| 201 | + step and node rank, and the value is the logs for that node. |
| 202 | + """ |
| 203 | + return self.job_runner.get_job_logs( |
| 204 | + job_name=name, follow=follow, step=step, node_rank=node_rank |
| 205 | + ) |
| 206 | + |
| 207 | + def delete_job(self, name: str): |
| 208 | + """Deletes a specific training job. |
| 209 | +
|
| 210 | + Args: |
| 211 | + name: The name of the training job to delete. |
| 212 | + """ |
| 213 | + self.job_runner.delete_job(job_name=name) |
| 214 | + |
| 215 | + def __list_runtime_crs(self) -> List[models.TrainerV1alpha1ClusterTrainingRuntime]: |
| 216 | + runtime_crs = [] |
| 217 | + for filename in self.local_runtimes_path.iterdir(): |
| 218 | + with open(filename, "r") as f: |
| 219 | + cr_str = f.read() |
| 220 | + cr_dict = yaml.safe_load(cr_str) |
| 221 | + cr = models.TrainerV1alpha1ClusterTrainingRuntime.from_dict(cr_dict) |
| 222 | + if cr is not None: |
| 223 | + runtime_crs.append(cr) |
| 224 | + return runtime_crs |
| 225 | + |
| 226 | + def __get_runtime_cr( |
| 227 | + self, |
| 228 | + name: str, |
| 229 | + ) -> Optional[models.TrainerV1alpha1ClusterTrainingRuntime]: |
| 230 | + for cr in self.__list_runtime_crs(): |
| 231 | + if cr.metadata.name == name: |
| 232 | + return cr |
| 233 | + return None |
| 234 | + |
| 235 | + def __container_job_to_train_job( |
| 236 | + self, container_job: types.ContainerJob |
| 237 | + ) -> types.TrainJob: |
| 238 | + return types.TrainJob( |
| 239 | + name=container_job.name, |
| 240 | + creation_timestamp=container_job.creation_timestamp, |
| 241 | + steps=[container.to_step() for container in container_job.containers], |
| 242 | + runtime=self.get_runtime(container_job.runtime_name), |
| 243 | + status=container_job.status, |
| 244 | + ) |
0 commit comments