forked from opendatahub-io/training-operator
-
Notifications
You must be signed in to change notification settings - Fork 5
/
training_client.py
1271 lines (1111 loc) · 50.8 KB
/
training_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2023 The Kubeflow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import multiprocessing
import logging
import time
import json
from typing import Optional, Callable, Tuple, List, Dict, Any, Set, Union
import queue
from kubernetes import client, config, watch
from kubeflow.training import models
from kubeflow.training.api_client import ApiClient
from kubeflow.training.constants import constants
from kubeflow.training.utils import utils
from kubeflow.storage_initializer.constants import (
VOLUME_PATH_DATASET,
VOLUME_PATH_MODEL,
)
logger = logging.getLogger(__name__)
status_logger = utils.StatusLogger(
header="{:<30.30} {:<20.20} {}".format("NAME", "STATE", "TIME"),
column_format="{:<30.30} {:<20.20} {}",
)
class TrainingClient(object):
def __init__(
self,
config_file: Optional[str] = None,
context: Optional[str] = None,
client_configuration: Optional[client.Configuration] = None,
namespace: str = utils.get_default_target_namespace(),
job_kind: str = constants.PYTORCHJOB_KIND,
):
"""TrainingClient constructor. Configure logging in your application
as follows to see detailed information from the TrainingClient APIs:
.. code-block:: python
import logging
logging.basicConfig()
log = logging.getLogger("kubeflow.training.api.training_client")
log.setLevel(logging.DEBUG)
Args:
config_file: Path to the kube-config file. Defaults to ~/.kube/config.
context: Set the active context. Defaults to current_context from the kube-config.
client_configuration: Client configuration for cluster authentication.
You have to provide valid configuration with Bearer token or
with username and password. You can find an example here:
https://github.com/kubernetes-client/python/blob/67f9c7a97081b4526470cad53576bc3b71fa6fcc/examples/remote_cluster.py#L31
namespace: Target Kubernetes namespace. By default it takes namespace
from `/var/run/secrets/kubernetes.io/serviceaccount/namespace` location
or set as `default`. Namespace can be overridden during method invocations.
job_kind: Target Training Job kind (e.g. `TFJob`, `PyTorchJob`, `MPIJob`).
Job kind can be overridden during method invocations.
The default Job kind is `PyTorchJob`.
Raises:
ValueError: Job kind is invalid.
"""
# If client configuration is not set, use kube-config to access Kubernetes APIs.
if client_configuration is None:
# Load kube-config or in-cluster config.
if config_file or not utils.is_running_in_k8s():
config.load_kube_config(config_file=config_file, context=context)
else:
config.load_incluster_config()
k8s_client = client.ApiClient(client_configuration)
self.custom_api = client.CustomObjectsApi(k8s_client)
self.core_api = client.CoreV1Api(k8s_client)
self.api_client = ApiClient()
self.namespace = namespace
if job_kind not in constants.JOB_PARAMETERS:
raise ValueError(
f"Job kind must be one of these: {list(constants.JOB_PARAMETERS.keys())}"
)
self.job_kind = job_kind
def train(
self,
name: str,
namespace: Optional[str] = None,
num_workers: int = 1,
num_procs_per_worker: int = 1,
storage_config: Dict[str, Optional[Union[str, List[str]]]] = {
"size": constants.PVC_DEFAULT_SIZE,
"storage_class": None,
"access_modes": constants.PVC_DEFAULT_ACCESS_MODES,
},
model_provider_parameters=None,
dataset_provider_parameters=None,
train_parameters=None,
resources_per_worker: Union[dict, client.V1ResourceRequirements, None] = None,
):
"""
Higher level train api
model_provider_parameters: It can be of type HuggingFaceModelParams
dataset_provider_parameters: It can be of type HfDatasetParams or S3DatasetParams
train_parameters: It can be of type HuggingFaceTrainParams
"""
try:
import peft
import transformers
except ImportError:
raise ImportError(
"Train API dependencies not installed. "
+ "Run: pip install -U 'kubeflow-training[huggingface]' "
)
from kubeflow.storage_initializer.s3 import S3DatasetParams
from kubeflow.storage_initializer.hugging_face import (
HuggingFaceModelParams,
HfDatasetParams,
)
if (
not name
or not model_provider_parameters
or not dataset_provider_parameters
or not train_parameters
):
raise ValueError("One of the required parameters is None")
namespace = namespace or self.namespace
# TODO (andreyvelich): PVC Creation should be part of Training Operator Controller.
# Ref issue: https://github.com/kubeflow/training-operator/issues/1971
try:
self.core_api.create_namespaced_persistent_volume_claim(
namespace=namespace,
body=utils.get_pvc_spec(
pvc_name=constants.STORAGE_INITIALIZER,
namespace=namespace,
storage_config=storage_config,
),
)
except Exception as e:
pvc_list = self.core_api.list_namespaced_persistent_volume_claim(namespace)
# Check if the PVC with the specified name exists
for pvc in pvc_list.items:
if pvc.metadata.name == constants.STORAGE_INITIALIZER:
print(
f"PVC '{constants.STORAGE_INITIALIZER}' already exists in namespace "
f"{namespace}."
)
break
else:
raise RuntimeError(f"failed to create PVC. Error: {e}")
if isinstance(model_provider_parameters, HuggingFaceModelParams):
mp = "hf"
else:
raise ValueError(
f"Invalid model provider parameters {model_provider_parameters}"
)
if isinstance(dataset_provider_parameters, S3DatasetParams):
dp = "s3"
elif isinstance(dataset_provider_parameters, HfDatasetParams):
dp = "hf"
else:
raise ValueError(
f"Invalid dataset provider parameters {dataset_provider_parameters}"
)
# create init container spec
init_container_spec = utils.get_container_spec(
name=constants.STORAGE_INITIALIZER,
base_image=constants.STORAGE_INITIALIZER_IMAGE,
args=[
"--model_provider",
mp,
"--model_provider_parameters",
json.dumps(model_provider_parameters.__dict__, cls=utils.SetEncoder),
"--dataset_provider",
dp,
"--dataset_provider_parameters",
json.dumps(dataset_provider_parameters.__dict__),
],
volume_mounts=[constants.STORAGE_INITIALIZER_VOLUME_MOUNT],
)
# create app container spec
container_spec = utils.get_container_spec(
name=constants.JOB_PARAMETERS[constants.PYTORCHJOB_KIND]["container"],
base_image=constants.TRAINER_TRANSFORMER_IMAGE,
args=[
"--model_uri",
model_provider_parameters.model_uri,
"--transformer_type",
model_provider_parameters.transformer_type.__name__,
"--model_dir",
VOLUME_PATH_MODEL,
"--dataset_dir",
VOLUME_PATH_DATASET,
"--lora_config",
json.dumps(train_parameters.lora_config.__dict__, cls=utils.SetEncoder),
"--training_parameters",
json.dumps(train_parameters.training_parameters.to_dict()),
],
volume_mounts=[constants.STORAGE_INITIALIZER_VOLUME_MOUNT],
resources=resources_per_worker,
)
# create worker pod spec
worker_pod_template_spec = utils.get_pod_template_spec(
containers=[container_spec],
volumes=[constants.STORAGE_INITIALIZER_VOLUME],
)
# create master pod spec
master_pod_template_spec = utils.get_pod_template_spec(
containers=[container_spec],
init_containers=[init_container_spec],
volumes=[constants.STORAGE_INITIALIZER_VOLUME],
)
job = utils.get_pytorchjob_template(
name=name,
namespace=namespace,
master_pod_template_spec=master_pod_template_spec,
worker_pod_template_spec=worker_pod_template_spec,
num_workers=num_workers,
num_procs_per_worker=num_procs_per_worker,
)
self.create_job(job, namespace=namespace)
def create_job(
self,
job: Optional[constants.JOB_MODELS_TYPE] = None,
name: Optional[str] = None,
namespace: Optional[str] = None,
job_kind: Optional[str] = None,
base_image: Optional[str] = None,
train_func: Optional[Callable] = None,
parameters: Optional[Dict[str, Any]] = None,
num_workers: Optional[int] = None,
resources_per_worker: Union[dict, models.V1ResourceRequirements, None] = None,
num_chief_replicas: Optional[int] = None,
num_ps_replicas: Optional[int] = None,
packages_to_install: Optional[List[str]] = None,
pip_index_url: str = constants.DEFAULT_PIP_INDEX_URL,
):
"""Create the Training Job.
Job can be created using one of the following options:
- Define custom resource object in `job` parameter (e.g. TFJob or PyTorchJob).
- Define training function in `train_func` parameter and number of workers.
- Define Docker image in `base_image` parameter and number of workers.
Args:
job: Job object. Object must be one of these types: KubeflowOrgV1TFJob,
KubeflowOrgV1PyTorchJob, KubeflowOrgV1MXJob, etc.
name: Name for the Job. It must be set if `job` parameter is omitted.
namespace: Namespace for the Job. By default namespace is taken from
`TrainingClient` object.
job_kind: Kind for the Job (e.g. `TFJob` or `PyTorchJob`). It must be set if
`job` parameter is omitted. By default Job kind is taken from
`TrainingClient` object.
base_image: Image that Job uses to train the model on each training replica.
If `train_func` parameter is set, this image is used to execute the training
function. The `constants` module contains some base images, the default image
is `docker.io/pytorch/pytorch:1.12.1-cuda11.3-cudnn8-runtime`
train_func: Function that Job uses to train the model on each training replica.
This function must be Callable. Optionally, this function might have one dict
argument to define input parameters for the function. If `train_func` is
set, Base Image must support `bash` CLI to execute the training script.
parameters: Dict of input parameters that training function might receive.
num_workers: Number of Worker replicas for the Job.
resources_per_worker: A parameter that lets you specify how much
resources each Worker container should have. You can either specify a
kubernetes.client.V1ResourceRequirements object (documented here:
https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1ResourceRequirements.md)
or a dictionary that includes one or more of the following keys:
`cpu`, `memory`, or `gpu` (other keys will be ignored). Appropriate
values for these keys are documented here:
https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/.
For example:
```
{
"cpu": "1",
"memory": "2Gi",
"gpu": "1",
}
```
Please note, `gpu` specifies a resource request with a key of
`nvidia.com/gpu`, i.e. an NVIDIA GPU. If you need a different type
of GPU, pass in a V1ResourceRequirement instance instead, since it's
more flexible. This parameter is optional and defaults to None.
num_chief_replicas: Number of Chief replicas for the TFJob. Number
of Chief replicas can't be more than 1.
num_ps_replicas: Number of Parameter Server replicas for the TFJob.
packages_to_install: List of Python packages to install in addition
to the base image packages if `train_func` parameter is set.
These packages are installed before executing the objective function.
pip_index_url: The PyPI url from which to install Python packages.
Raises:
ValueError: Invalid input parameters.
TimeoutError: Timeout to create Job.
RuntimeError: Failed to create Job.
"""
# When Job is set, only namespace arg is allowed.
if job is not None:
for key, value in locals().items():
if (
key not in ["self", "job", "namespace", "pip_index_url"]
and value is not None
):
raise ValueError(
"If `job` is set only `namespace` argument is allowed. "
f"Argument `{key}` must be None."
)
namespace = namespace or self.namespace
job_kind = job_kind or self.job_kind
if job is not None:
job_kind = str(job.kind)
if job_kind not in constants.JOB_PARAMETERS:
raise ValueError(
f"Job kind must be one of these: {constants.JOB_PARAMETERS.keys()}"
)
# If Training function or base image is set, configure Job template.
if job is None and (train_func is not None or base_image is not None):
# Job name must be set to configure Job template.
if name is None:
raise ValueError(
"Job name must be set to configure Job from function or image"
)
# Assign the default base image.
# TODO (andreyvelich): Add base image for other Job kinds.
if base_image is None:
base_image = constants.JOB_PARAMETERS[job_kind]["base_image"]
# Get Training Container template.
container_spec = utils.get_container_spec(
name=constants.JOB_PARAMETERS[job_kind]["container"],
base_image=base_image,
train_func=train_func,
train_func_parameters=parameters,
packages_to_install=packages_to_install,
pip_index_url=pip_index_url,
resources=resources_per_worker,
)
# Get Pod template spec using the above container.
pod_template_spec = utils.get_pod_template_spec(
containers=[container_spec],
)
# Configure template for different Jobs.
# TODO (andreyvelich): Add support for other kinds (e.g. MPIJob).
if job_kind == constants.TFJOB_KIND:
job = utils.get_tfjob_template(
name=name,
namespace=namespace,
pod_template_spec=pod_template_spec,
num_workers=num_workers,
num_chief_replicas=num_chief_replicas,
num_ps_replicas=num_ps_replicas,
)
elif job_kind == constants.PYTORCHJOB_KIND and num_workers:
job = utils.get_pytorchjob_template(
name=name,
namespace=namespace,
worker_pod_template_spec=pod_template_spec,
num_workers=num_workers,
)
else:
raise ValueError(
f"Job kind {job_kind} can't be created using function or image. "
+ "Number of Workers must be set."
)
# Verify Job object type.
if not isinstance(
job,
getattr(models, constants.JOB_PARAMETERS[job_kind]["model"]),
):
raise ValueError(
f"Job must be one of these types: {constants.JOB_MODELS}, but Job is: {type(job)}"
)
# Create the Training Job.
try:
self.custom_api.create_namespaced_custom_object(
constants.GROUP,
constants.VERSION,
namespace,
constants.JOB_PARAMETERS[job_kind]["plural"],
job,
)
except multiprocessing.TimeoutError:
raise TimeoutError(
f"Timeout to create {job_kind}: {namespace}/{job.metadata.name}"
)
except Exception:
raise RuntimeError(
f"Failed to create {job_kind}: {namespace}/{job.metadata.name}"
)
logger.debug(f"{job_kind} {namespace}/{job.metadata.name} has been created")
def get_job(
self,
name: str,
namespace: Optional[str] = None,
job_kind: Optional[str] = None,
timeout: int = constants.DEFAULT_TIMEOUT,
) -> constants.JOB_MODELS_TYPE:
"""Get the Training Job.
Args:
name: Name for the Job.
namespace: Namespace for the Job. By default namespace is taken from
`TrainingClient` object.
job_kind: Kind for the Job (e.g. `TFJob` or `PyTorchJob`). By default Job kind
is taken from `TrainingClient` object.
timeout: Kubernetes API server timeout in seconds to execute the request.
Returns:
object: Job object. For example: KubeflowOrgV1PyTorchJob
Raises:
TimeoutError: Timeout to get Job.
RuntimeError: Failed to get Job.
"""
namespace = namespace or self.namespace
job_kind = job_kind or self.job_kind
if job_kind not in constants.JOB_PARAMETERS:
raise ValueError(
f"Job kind must be one of these: {constants.JOB_PARAMETERS.keys()}"
)
try:
thread = self.custom_api.get_namespaced_custom_object(
constants.GROUP,
constants.VERSION,
namespace,
constants.JOB_PARAMETERS[job_kind]["plural"],
name,
async_req=True,
)
response = utils.FakeResponse(thread.get(timeout))
job = self.api_client.deserialize(
response, constants.JOB_PARAMETERS[job_kind]["model"]
)
except multiprocessing.TimeoutError:
raise TimeoutError(f"Timeout to get {job_kind}: {namespace}/{name}")
except Exception:
raise RuntimeError(f"Failed to get {job_kind}: {namespace}/{name}")
return job
def list_jobs(
self,
namespace: Optional[str] = None,
job_kind: Optional[str] = None,
timeout: int = constants.DEFAULT_TIMEOUT,
) -> List[constants.JOB_MODELS_TYPE]:
"""List of all Training Jobs with specific kind in namespace.
Args:
namespace: Namespace to list the Jobs. By default namespace is taken from
`TrainingClient` object.
job_kind: Kind for the Job (e.g. `TFJob` or `PyTorchJob`). By default Job kind
is taken from `TrainingClient` object.
timeout: Kubernetes API server timeout in seconds to execute the request.
Returns:
list[object]: List of Job objects.
For example: list of KubeflowOrgV1PyTorchJob objects. It returns empty list
if Jobs can't be found.
Raises:
TimeoutError: Timeout to list Jobs
RuntimeError: Failed to list Jobs
"""
namespace = namespace or self.namespace
job_kind = job_kind or self.job_kind
if job_kind not in constants.JOB_PARAMETERS:
raise ValueError(
f"Job kind must be one of these: {constants.JOB_PARAMETERS.keys()}"
)
result = []
try:
thread = self.custom_api.list_namespaced_custom_object(
constants.GROUP,
constants.VERSION,
namespace,
constants.JOB_PARAMETERS[job_kind]["plural"],
async_req=True,
)
response = thread.get(timeout)
result = [
self.api_client.deserialize(
utils.FakeResponse(item),
constants.JOB_PARAMETERS[job_kind]["model"],
)
for item in response.get("items")
]
except multiprocessing.TimeoutError:
raise TimeoutError(f"Timeout to list {job_kind}s in namespace: {namespace}")
except Exception:
raise RuntimeError(f"Failed to list {job_kind}s in namespace: {namespace}")
return result
def get_job_conditions(
self,
name: Optional[str] = None,
namespace: Optional[str] = None,
job_kind: Optional[str] = None,
job: Optional[constants.JOB_MODELS_TYPE] = None,
timeout: int = constants.DEFAULT_TIMEOUT,
) -> List[models.V1JobCondition]:
"""Get the Training Job conditions. Training Job is in the condition when
`status=True` for the appropriate condition `type`. For example,
Training Job is Succeeded when `status=True` and `type=Succeeded`.
Args:
name: Name for the Job.
namespace: Namespace for the Job. By default namespace is taken from
`TrainingClient` object.
job_kind: Kind for the Job (e.g. `TFJob` or `PyTorchJob`). By default Job kind
is taken from `TrainingClient` object.
job: Job object can be set to get the conditions. Object must be one of
these types: KubeflowOrgV1TFJob, KubeflowOrgV1PyTorchJob, KubeflowOrgV1MXJob, etc.
If this parameter is omitted, it gets Job with the given name and kind.
timeout: Kubernetes API server timeout in seconds to execute the request.
Returns:
list[V1JobCondition]: List of Job conditions with
last transition time, last update time, message, reason, type, and
status. It returns empty list if Job does not have any
conditions yet.
Raises:
ValueError: Invalid input parameters.
TimeoutError: Timeout to get Job.
RuntimeError: Failed to get Job.
"""
namespace = namespace or self.namespace
job_kind = job_kind or self.job_kind
if job_kind not in constants.JOB_PARAMETERS:
raise ValueError(
f"Job kind must be one of these: {constants.JOB_PARAMETERS.keys()}"
)
if job is not None and not isinstance(
job, getattr(models, constants.JOB_PARAMETERS[job_kind]["model"])
):
raise ValueError(f"Job must be one of these types: {constants.JOB_MODELS}")
# If Job is not set, get the Training Job.
if job is None:
# Job name must be set when Job object is not set.
if name is None:
raise ValueError(
"Job name must be set to configure Job from function or image"
)
job = self.get_job(
name=name,
namespace=namespace,
job_kind=job_kind,
timeout=timeout,
)
if job.status and job.status.conditions and len(job.status.conditions) > 0:
return job.status.conditions
return []
def is_job_created(
self,
name: Optional[str] = None,
namespace: Optional[str] = None,
job_kind: Optional[str] = None,
job: Optional[constants.JOB_MODELS_TYPE] = None,
timeout: int = constants.DEFAULT_TIMEOUT,
) -> bool:
"""Check if Training Job is Created.
Args:
name: Name for the Job.
namespace: Namespace for the Job. By default namespace is taken from
`TrainingClient` object.
job_kind: Kind for the Job (e.g. `TFJob` or `PyTorchJob`). By default Job kind
is taken from `TrainingClient` object.
job: Job object can be set to get the conditions. Object must be one of
these types: KubeflowOrgV1TFJob, KubeflowOrgV1PyTorchJob, KubeflowOrgV1MXJob, etc.
If this parameter is omitted, it gets Job with the given name and kind.
timeout: Kubernetes API server timeout in seconds to execute the request.
Returns:
bool: True if Job is Created, else False.
Raises:
ValueError: Invalid input parameters.
TimeoutError: Timeout to get Job.
RuntimeError: Failed to get Job.
"""
return utils.has_condition(
self.get_job_conditions(name, namespace, job_kind, job, timeout),
constants.JOB_CONDITION_CREATED,
)
def is_job_running(
self,
name: Optional[str] = None,
namespace: Optional[str] = None,
job_kind: Optional[str] = None,
job: Optional[constants.JOB_MODELS_TYPE] = None,
timeout: int = constants.DEFAULT_TIMEOUT,
) -> bool:
"""Check if Training Job is Running.
Args:
name: Name for the Job.
namespace: Namespace for the Job. By default namespace is taken from
`TrainingClient` object.
job_kind: Kind for the Job (e.g. `TFJob` or `PyTorchJob`). By default Job kind
is taken from `TrainingClient` object.
job: Job object can be set to get the conditions. Object must be one of
these types: KubeflowOrgV1TFJob, KubeflowOrgV1PyTorchJob, KubeflowOrgV1MXJob, etc.
If this parameter is omitted, it gets Job with the given name and kind.
timeout: Kubernetes API server timeout in seconds to execute the request.
Returns:
bool: True if Job is Running, else False.
Raises:
ValueError: Invalid input parameters.
TimeoutError: Timeout to get Job.
RuntimeError: Failed to get Job.
"""
return utils.has_condition(
self.get_job_conditions(name, namespace, job_kind, job, timeout),
constants.JOB_CONDITION_RUNNING,
)
def is_job_restarting(
self,
name: Optional[str] = None,
namespace: Optional[str] = None,
job_kind: Optional[str] = None,
job: Optional[constants.JOB_MODELS_TYPE] = None,
timeout: int = constants.DEFAULT_TIMEOUT,
) -> bool:
"""Check if Training Job is Restarting.
Args:
name: Name for the Job.
namespace: Namespace for the Job. By default namespace is taken from
`TrainingClient` object.
job_kind: Kind for the Job (e.g. `TFJob` or `PyTorchJob`). By default Job kind
is taken from `TrainingClient` object.
job: Job object can be set to get the conditions. Object must be one of
these types: KubeflowOrgV1TFJob, KubeflowOrgV1PyTorchJob, KubeflowOrgV1MXJob, etc.
If this parameter is omitted, it gets Job with the given name and kind.
timeout: Kubernetes API server timeout in seconds to execute the request.
Returns:
bool: True if Job is Restarting, else False.
Raises:
ValueError: Invalid input parameters.
TimeoutError: Timeout to get Job.
RuntimeError: Failed to get Job.
"""
return utils.has_condition(
self.get_job_conditions(name, namespace, job_kind, job, timeout),
constants.JOB_CONDITION_RESTARTING,
)
def is_job_succeeded(
self,
name: Optional[str] = None,
namespace: Optional[str] = None,
job_kind: Optional[str] = None,
job: Optional[constants.JOB_MODELS_TYPE] = None,
timeout: int = constants.DEFAULT_TIMEOUT,
) -> bool:
"""Check if Training Job is Succeeded.
Args:
name: Name for the Job.
namespace: Namespace for the Job. By default namespace is taken from
`TrainingClient` object.
job_kind: Kind for the Job (e.g. `TFJob` or `PyTorchJob`). By default Job kind
is taken from `TrainingClient` object.
job: Job object can be set to get the conditions. Object must be one of
these types: KubeflowOrgV1TFJob, KubeflowOrgV1PyTorchJob, KubeflowOrgV1MXJob, etc.
If this parameter is omitted, it gets Job with the given name and kind.
timeout: Kubernetes API server timeout in seconds to execute the request.
Returns:
bool: True if Job is Succeeded, else False.
Raises:
ValueError: Invalid input parameters.
TimeoutError: Timeout to get Job.
RuntimeError: Failed to get Job.
"""
return utils.has_condition(
self.get_job_conditions(name, namespace, job_kind, job, timeout),
constants.JOB_CONDITION_SUCCEEDED,
)
def is_job_failed(
self,
name: Optional[str] = None,
namespace: Optional[str] = None,
job_kind: Optional[str] = None,
job: Optional[constants.JOB_MODELS_TYPE] = None,
timeout: int = constants.DEFAULT_TIMEOUT,
) -> bool:
"""Check if Training Job is Failed.
Args:
name: Name for the Job.
namespace: Namespace for the Job. By default namespace is taken from
`TrainingClient` object.
job_kind: Kind for the Job (e.g. `TFJob` or `PyTorchJob`). By default Job kind
is taken from `TrainingClient` object.
job: Job object can be set to get the conditions. Object must be one of
these types: KubeflowOrgV1TFJob, KubeflowOrgV1PyTorchJob, KubeflowOrgV1MXJob, etc.
If this parameter is omitted, it gets Job with the given name and kind.
timeout: Kubernetes API server timeout in seconds to execute the request.
Returns:
bool: True if Job is Failed, else False.
Raises:
ValueError: Invalid input parameters.
TimeoutError: Timeout to get Job.
RuntimeError: Failed to get Job.
"""
return utils.has_condition(
self.get_job_conditions(name, namespace, job_kind, job, timeout),
constants.JOB_CONDITION_FAILED,
)
def wait_for_job_conditions(
self,
name: str,
namespace: Optional[str] = None,
job_kind: Optional[str] = None,
expected_conditions: Set = {constants.JOB_CONDITION_SUCCEEDED},
wait_timeout: int = 600,
polling_interval: int = 15,
callback: Optional[Callable] = None,
timeout: int = constants.DEFAULT_TIMEOUT,
) -> constants.JOB_MODELS_TYPE:
"""Wait until Training Job reaches any of the specified conditions.
By default it waits for the Succeeded condition.
Args:
name: Name for the Job.
namespace: Namespace for the Job. By default namespace is taken from
`TrainingClient` object.
job_kind: Kind for the Job (e.g. `TFJob` or `PyTorchJob`). By default Job kind
is taken from `TrainingClient` object.
expected_conditions: Set of expected conditions. It must be subset of this:
`{"Created", "Running", "Restarting", "Succeeded", "Failed"}`
wait_timeout: How many seconds to wait until Job reaches one of
the expected conditions.
polling_interval: The polling interval in seconds to get Job status.
callback: Callback function that is invoked after Job
status is polled. This function takes a single argument which
is current Job object.
timeout: Kubernetes API server timeout in seconds to execute the request.
Returns:
object: Job object. For example: KubeflowOrgV1PyTorchJob
Raises:
ValueError: Invalid input parameters.
TimeoutError: Timeout to get Job.
RuntimeError: Failed to get Job or Job reaches unexpected Failed condition.
"""
namespace = namespace or self.namespace
job_kind = job_kind or self.job_kind
if not expected_conditions.issubset(constants.JOB_CONDITIONS):
raise ValueError(
f"Expected conditions: {expected_conditions} must be subset of \
{constants.JOB_CONDITIONS}"
)
for _ in range(round(wait_timeout / polling_interval)):
# We should get Job only once per cycle and check the statuses.
job = self.get_job(
name=name,
namespace=namespace,
job_kind=job_kind,
timeout=timeout,
)
# Get Job conditions.
conditions = self.get_job_conditions(job=job, timeout=timeout)
if len(conditions) > 0:
status_logger(
name,
conditions[-1].type,
conditions[-1].last_transition_time,
)
# Execute callback function is it is set.
if callback:
callback(job)
# Raise an exception if Job is Failed and Failed is not expected condition.
if (
constants.JOB_CONDITION_FAILED not in conditions
and utils.has_condition(conditions, constants.JOB_CONDITION_FAILED)
):
raise RuntimeError(
f"{job_kind} {namespace}/{name} is Failed. "
f"{job_kind} conditions: {job.status.conditions}"
)
# Return Job when it reaches expected condition.
for expected_condition in expected_conditions:
if utils.has_condition(conditions, expected_condition):
return job
time.sleep(polling_interval)
raise TimeoutError(
f"Timeout waiting for {job_kind}: {namespace}/{name} to reach expected conditions: \
{expected_conditions}"
)
def get_job_pods(
self,
name: str,
namespace: Optional[str] = None,
is_master: bool = False,
replica_type: Optional[str] = None,
replica_index: Optional[int] = None,
timeout: int = constants.DEFAULT_TIMEOUT,
) -> List[models.V1Pod]:
"""Get pods for the Training Job.
Args:
name: Name for the Job.
namespace: Namespace for the Job. By default namespace is taken from
`TrainingClient` object.
is_master: Whether to get pods only with the label
`training.kubeflow.org/job-role: master`.
replica_type: Type of the Job replica.
For TFJob one of `Chief`, `PS`, or `worker`.
For PyTorchJob one of `master` or `worker`.
For MXJob one of `scheduler`, `server`, or `worker`.
For XGBoostJob one of `master` or `worker`.
For MPIJob one of `launcher` or `worker`.
For PaddleJob one of `master` or `worker`.
replica_index: Index for the Job replica.
timeout: Kubernetes API server timeout in seconds to execute the request.
Returns:
list[V1Pod]: List of the Job pods.
Raises:
ValueError: Job replica type is invalid.
TimeoutError: Timeout to get Job pods.
RuntimeError: Failed to get Job pods.
"""
namespace = namespace or self.namespace
if (
replica_type is not None
and replica_type not in constants.TFJOB_REPLICA_TYPES
and replica_type not in constants.PYTORCHJOB_REPLICA_TYPES
and replica_type not in constants.MXJOB_REPLICA_TYPES
and replica_type not in constants.XGBOOSTJOB_REPLICA_TYPES
and replica_type not in constants.MPIJOB_REPLICA_TYPES
and replica_type not in constants.PADDLEJOB_REPLICA_TYPES
):
raise ValueError(
f"TFJob replica type must be one of {constants.TFJOB_REPLICA_TYPES}\n"
f"PyTorchJob replica type must be one of {constants.PYTORCHJOB_REPLICA_TYPES}\n"
f"MXJob replica type must be one of {constants.MXJOB_REPLICA_TYPES}\n"
f"XGBoostJob replica type must be one of {constants.XGBOOSTJOB_REPLICA_TYPES}\n"
f"MPIJob replica type must be one of {constants.MPIJOB_REPLICA_TYPES}\n"
f"PaddleJob replica type must be one of {constants.PADDLEJOB_REPLICA_TYPES}"
)
label_selector = f"{constants.JOB_NAME_LABEL}={name}"
# Add Job role label if that is required.
if is_master:
label_selector += f",{constants.JOB_ROLE_LABEL}={constants.JOB_ROLE_MASTER}"
# Add Replica type label if that is required.
if replica_type:
label_selector += (
f",{constants.REPLICA_TYPE_LABEL}={str.lower(replica_type)}"
)
# Add Replica index label if that is required.
if replica_index is not None:
label_selector += f",{constants.REPLICA_INDEX_LABEL}={replica_index}"
# Return list of Training Job pods.
try:
thread = self.core_api.list_namespaced_pod(
namespace,
label_selector=label_selector,
async_req=True,
)
return thread.get(timeout).items
except multiprocessing.TimeoutError:
raise TimeoutError(f"Timeout to list pods for Job: {namespace}/{name}")
except Exception:
raise RuntimeError(f"Failed to list pods for Job: {namespace}/{name}")
def get_job_pod_names(
self,
name: str,
namespace: Optional[str] = None,
is_master: bool = False,
replica_type: Optional[str] = None,
replica_index: Optional[int] = None,
timeout: int = constants.DEFAULT_TIMEOUT,
) -> List[str]:
"""Get pod names for the Training Job.
Args:
name: Name for the Job.
namespace: Namespace for the Job. By default namespace is taken from
`TrainingClient` object.
is_master: Whether to get pods only with the label
`training.kubeflow.org/job-role: master`.
replica_type: Type of the Job replica.
For TFJob one of `Chief`, `PS`, or `worker`.
For PyTorchJob one of `master` or `worker`.
For MXJob one of `scheduler`, `server`, or `worker`.
For XGBoostJob one of `master` or `worker`.
For MPIJob one of `launcher` or `worker`.
For PaddleJob one of `master` or `worker`.
replica_index: Index for the Job replica.
timeout: Kubernetes API server timeout in seconds to execute the request.
Returns:
list[str]: List of the Job pod names.
Raises:
ValueError: Job replica type is invalid.
TimeoutError: Timeout to get Job pods.
RuntimeError: Failed to get Job pods.
"""