Repository navigation
Expand file tree
/
Copy pathdistributed_training.py
More file actions
4843 lines (4648 loc) · 161 KB
/
Copy pathdistributed_training.py
File metadata and controls
4843 lines (4648 loc) · 161 KB
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
"""Flyte Ray tasks for distributed AutoE2E training."""
from __future__ import annotations
import hashlib
import json
import math
import os
import re
import time
from datetime import timedelta
from pathlib import Path
from typing import Any, List, Mapping, NamedTuple, Optional
from urllib.parse import urlparse
from flytekit import (
PodTemplate,
Resources,
current_context,
task,
workflow,
)
from flytekit.types.directory import FlyteDirectory
from flytekit.types.file import FlyteFile
from flytekitplugins.ray import (
HeadNodeConfig,
RayJobConfig,
WorkerNodeConfig,
)
from kubernetes.client import (
V1Affinity,
V1Container,
V1EmptyDirVolumeSource,
V1EnvVar,
V1LabelSelector,
V1LabelSelectorRequirement,
V1PodAffinity,
V1PodAffinityTerm,
V1PodAntiAffinity,
V1PodSpec,
V1ResourceRequirements,
V1Toleration,
V1Volume,
V1VolumeMount,
)
from data_parsing.kit_scenes.source import (
KITSCENES_DATA_REVISION,
KITSCENES_REPO_ID,
KITSCENES_STANDARD_TEST_SCENE_COUNT,
KITSCENES_STANDARD_TEST_SCENE_UID_SHA256,
KITSCENES_STANDARD_VAL_SCENE_COUNT,
KITSCENES_STANDARD_VAL_SCENE_UID_SHA256,
sdk_split_scene_ids,
)
TRAINING_IMAGE = os.environ.get(
"AUTO_E2E_TRAINING_IMAGE",
"auto-e2e/training:latest",
)
RAY_STORAGE_PATH = os.environ.get(
"AUTO_E2E_RAY_STORAGE_PATH",
"s3://auto-e2e-platform-checkpoints/ray-train",
)
MLFLOW_URI = os.environ.get(
"MLFLOW_TRACKING_URI",
"http://mlflow.mlflow.svc.cluster.local:5000",
)
REACTIVE_MLFLOW_EXPERIMENT = "reactive-training"
REACTIVE_BEV_EVALUATION_MLFLOW_EXPERIMENT = (
"reactive-bev-evaluation"
)
REACTIVE_POLICY_EVALUATION_MLFLOW_EXPERIMENT = (
"reactive-policy-evaluation"
)
REACTIVE_BEV_REGISTERED_MODEL = "auto-e2e-bev-segmentation"
REACTIVE_POLICY_REGISTERED_MODEL = "auto-e2e-driving-policy"
RAY_TASK_ENVIRONMENT = {
"AWS_DEFAULT_REGION": "us-west-2",
"AUTO_E2E_RAY_STORAGE_PATH": RAY_STORAGE_PATH,
"MLFLOW_TRACKING_URI": MLFLOW_URI,
"RAY_TRAIN_V2_ENABLED": "1",
}
BEV_POS_WEIGHT_CAP = 64.0
BEV_CANARY_MIN_SELECTION_GAIN = 1e-3
BEV_CANARY_AP_LIFT_ABSOLUTE_REGRESSION_TOLERANCE = 1e-3
BEV_CANARY_RARE_AP_LIFT_RELATIVE_REGRESSION_TOLERANCE = 0.1
P5EN_SMOKE_MAX_RUNTIME = timedelta(minutes=30)
NUPLAN_EPOCH5_TRAJECTORY_ROUTE_CHECKPOINT_SHA256 = (
"ca8b43d7a777d6fd9195bb253d1452f3cd645f7aab3bd0e36b1f74ffb31df29b"
)
KITSCENES_OFFICIAL_TEST_SCENE_COUNT = (
KITSCENES_STANDARD_TEST_SCENE_COUNT
)
KITSCENES_OFFICIAL_TEST_SCENE_UID_SHA256 = (
KITSCENES_STANDARD_TEST_SCENE_UID_SHA256
)
KITSCENES_OFFICIAL_VAL_SCENE_COUNT = KITSCENES_STANDARD_VAL_SCENE_COUNT
KITSCENES_OFFICIAL_VAL_SCENE_UID_SHA256 = (
KITSCENES_STANDARD_VAL_SCENE_UID_SHA256
)
KITSCENES_OFFICIAL_VAL_SAMPLE_COUNT = 11_035
KITSCENES_OFFICIAL_TEST_SAMPLE_COUNT = 23_690
KITSCENES_OFFICIAL_VAL_DATASET_VERSION = "v3.5"
KITSCENES_OFFICIAL_TEST_DATASET_VERSION = "v3.5-test-camera-only-v1"
KITSCENES_PRIMARY_VAL_BATCH_SIZE = 5
KITSCENES_STATEFUL_CAMERA_FPN_BATCH_SIZE = 5
KITSCENES_STATEFUL_CAMERA_FPN_POLICY = (
"stateful_camera_fpn_5lane_v1"
)
KITSCENES_TRAJECTORY_INFERENCE_POLICY = (
"deterministic_gru_no_noise_v1"
)
KITSCENES_EVALUATION_PRECISION_POLICY = (
"cuda_bfloat16_autocast_v1"
)
KITSCENES_PRIMARY_VAL_ROUTE_USAGE_POLICY = (
"route_zero_reused_image_bev_no_grad_v2"
)
KITSCENES_CAMERA_ONLY_ROUTE_USAGE_POLICY = (
"not_applicable_camera_only_v1"
)
def _sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _kitscenes_route_usage_evaluation_policy(
*,
mapless_test: bool,
) -> dict[str, object]:
return {
"counterfactuals_enabled": not mapless_test,
"input_gradient_enabled": False,
"reuse_precomputed_image_bev": not mapless_test,
"route_swap_counterfactual_enabled": False,
"version": (
KITSCENES_CAMERA_ONLY_ROUTE_USAGE_POLICY
if mapless_test
else KITSCENES_PRIMARY_VAL_ROUTE_USAGE_POLICY
),
}
def _kitscenes_evaluation_precision_policy() -> dict[str, object]:
return {
"autocast_enabled": True,
"device_type": "cuda",
"dtype": "bfloat16",
"version": KITSCENES_EVALUATION_PRECISION_POLICY,
}
def _finite_numeric_metrics(
prefix: str,
values: Mapping[str, object],
) -> dict[str, float]:
return {
f"{prefix}/{name}": float(value)
for name, value in values.items()
if (
value is not None
and not isinstance(value, bool)
and isinstance(value, (int, float))
and math.isfinite(float(value))
)
}
def _validate_kitscenes_runtime_precision(
metrics: Mapping[str, object],
policy: Mapping[str, object],
) -> None:
expected = {
key: policy[key]
for key in ("autocast_enabled", "device_type", "dtype")
}
if metrics.get("inference_precision") != expected:
raise RuntimeError(
"KITScenes evaluator runtime precision differs from policy"
)
def _kitscenes_scene_identity(
scene_uids: list[str],
*,
source_split: str,
expected_partition_count: int,
) -> tuple[str, bool]:
if source_split == "test":
official_scene_count = KITSCENES_OFFICIAL_TEST_SCENE_COUNT
official_scene_uid_sha256 = (
KITSCENES_OFFICIAL_TEST_SCENE_UID_SHA256
)
elif source_split == "val":
official_scene_count = KITSCENES_OFFICIAL_VAL_SCENE_COUNT
official_scene_uid_sha256 = KITSCENES_OFFICIAL_VAL_SCENE_UID_SHA256
else:
raise ValueError("KITScenes scene identity requires val or test")
if (
isinstance(expected_partition_count, bool)
or not isinstance(expected_partition_count, int)
or expected_partition_count < 0
):
raise ValueError(
f"KITScenes {source_split} expected partition count must be "
"non-negative"
)
if len(scene_uids) != len(set(scene_uids)):
raise ValueError(
f"KITScenes {source_split} manifests contain duplicate scene "
"identities"
)
scene_uid_sha256 = hashlib.sha256(
"\n".join(sorted(scene_uids)).encode("utf-8")
).hexdigest()
if (
expected_partition_count
and len(scene_uids) != expected_partition_count
):
raise ValueError(
f"KITScenes {source_split} evaluation does not cover the expected "
f"{expected_partition_count} partitions"
)
is_official = (
len(scene_uids) == official_scene_count
and scene_uid_sha256 == official_scene_uid_sha256
and (
source_split == "test"
or expected_partition_count == official_scene_count
)
)
if (
expected_partition_count == official_scene_count
and not is_official
):
raise ValueError(
f"KITScenes {source_split} manifests do not cover the official "
"scene set"
)
return scene_uid_sha256, is_official
def _validate_kitscenes_official_val_sdk_split(
scene_uids: list[str],
*,
expected_partition_count: int,
) -> None:
if expected_partition_count != KITSCENES_OFFICIAL_VAL_SCENE_COUNT:
return
sdk_val_scene_uids = sorted(
f"kitscenes-{scene_id}"
for scene_id in sdk_split_scene_ids("val")
)
sdk_train_scene_uids = {
f"kitscenes-{scene_id}"
for scene_id in sdk_split_scene_ids("train")
}
sdk_val_sha256 = hashlib.sha256(
"\n".join(sdk_val_scene_uids).encode("utf-8")
).hexdigest()
if (
len(sdk_val_scene_uids) != KITSCENES_OFFICIAL_VAL_SCENE_COUNT
or sdk_val_sha256 != KITSCENES_OFFICIAL_VAL_SCENE_UID_SHA256
):
raise ValueError(
"pinned KITScenes SDK val split differs from the reviewed "
"official identity"
)
actual_scene_uids = sorted(scene_uids)
if actual_scene_uids != sdk_val_scene_uids:
raise ValueError(
"KITScenes official val manifests differ from the pinned SDK "
"val split"
)
overlap = sorted(set(actual_scene_uids) & sdk_train_scene_uids)
if overlap:
raise ValueError(
"KITScenes official val split overlaps the pinned SDK train "
f"split: {overlap[:5]}"
)
def _validate_kitscenes_official_sample_inventory(
*,
source_split: str,
expected_partition_count: int,
empty_partition_count: int,
manifest_sample_count: int,
inventory_sample_count: int | None,
) -> None:
if source_split == "test":
official_scene_count = KITSCENES_OFFICIAL_TEST_SCENE_COUNT
official_sample_count = KITSCENES_OFFICIAL_TEST_SAMPLE_COUNT
elif source_split == "val":
official_scene_count = KITSCENES_OFFICIAL_VAL_SCENE_COUNT
official_sample_count = KITSCENES_OFFICIAL_VAL_SAMPLE_COUNT
else:
raise ValueError("KITScenes sample inventory requires val or test")
if expected_partition_count != official_scene_count:
return
if (
empty_partition_count != 0
or manifest_sample_count != official_sample_count
or inventory_sample_count != official_sample_count
):
raise ValueError(
f"KITScenes official {source_split} sample inventory differs from "
f"{official_sample_count}"
)
def _validate_kitscenes_val_manifest_contract(
manifest: Mapping[str, Any],
) -> None:
expected_flags = {
"has_map": True,
"has_navigation": True,
"has_reactive_navigation": True,
"has_route_reconstruction": True,
"has_trajectory_xy": True,
}
mismatches = {
key: manifest.get(key)
for key, expected in expected_flags.items()
if manifest.get(key) is not expected
}
input_track = manifest.get("input_track")
if input_track not in {None, "camera_map_route"}:
mismatches["input_track"] = input_track
if mismatches:
raise ValueError(
"KITScenes val manifest violates the camera-map-route "
f"contract: {mismatches}"
)
def _resolve_nuplan_validation_sample_limit(
config: Mapping[str, Any],
requested_sample_limit: int,
) -> tuple[int, str]:
"""Resolve legacy checkpoint provenance from an explicit workflow input."""
if (
isinstance(requested_sample_limit, bool)
or not isinstance(requested_sample_limit, int)
or requested_sample_limit < 0
):
raise ValueError(
"nuPlan evaluation validation_sample_limit is invalid"
)
checkpoint_sample_limit = config.get("validation_sample_limit")
if checkpoint_sample_limit is None:
if requested_sample_limit <= 0:
raise ValueError(
"nuPlan checkpoint lacks validation_sample_limit provenance; "
"set the workflow input from the source training execution"
)
return requested_sample_limit, "workflow_input_legacy_checkpoint"
if (
isinstance(checkpoint_sample_limit, bool)
or not isinstance(checkpoint_sample_limit, int)
or checkpoint_sample_limit <= 0
):
raise ValueError(
"nuPlan checkpoint validation_sample_limit is invalid"
)
if (
requested_sample_limit > 0
and requested_sample_limit != checkpoint_sample_limit
):
raise ValueError(
"nuPlan evaluation validation_sample_limit differs from the "
"checkpoint"
)
return checkpoint_sample_limit, "checkpoint"
class RaySmokeOutput(NamedTuple):
report: FlyteFile
class ReactiveRayOutput(NamedTuple):
checkpoint: FlyteFile
metadata: FlyteFile
checkpoint_uri: str
checkpoint_sha256: str
class ReactiveDistributedProgramOutput(NamedTuple):
stage_a_checkpoint: FlyteFile
stage_a_metadata: FlyteFile
stage_a_checkpoint_uri: str
stage_a_checkpoint_sha256: str
stage_b_checkpoint: FlyteFile
stage_b_metadata: FlyteFile
stage_b_checkpoint_uri: str
stage_b_checkpoint_sha256: str
class ReactiveCanaryOutput(NamedTuple):
stage_a_checkpoint: FlyteFile
stage_b_checkpoint: FlyteFile
stage_a_metadata: FlyteFile
stage_b_metadata: FlyteFile
gate_report: FlyteFile
class ReactiveBEVCanaryOutput(NamedTuple):
checkpoint: FlyteFile
metadata: FlyteFile
checkpoint_uri: str
checkpoint_sha256: str
gate_report: FlyteFile
class ReactiveBEVEvaluationOutput(NamedTuple):
report: FlyteFile
report_sha256: str
checkpoint_sha256: str
checkpoint_epoch: int
class ReactiveKITScenesEvaluationOutput(NamedTuple):
report: FlyteFile
report_sha256: str
checkpoint_sha256: str
checkpoint_epoch: int
class ReactiveKITScenesEvaluationWorkflowOutput(NamedTuple):
report: FlyteFile
report_sha256: str
checkpoint_sha256: str
checkpoint_epoch: int
mlflow_run_id: str
registered_model_name: str
registered_model_version: str
class ReactiveBEVPublicationOutput(NamedTuple):
mlflow_run_id: str
registered_model_name: str
registered_model_version: str
class ReactivePolicyPublicationOutput(NamedTuple):
mlflow_run_id: str
registered_model_name: str
registered_model_version: str
class ReactiveBEVEvaluationWorkflowOutput(NamedTuple):
report: FlyteFile
report_sha256: str
checkpoint_sha256: str
checkpoint_epoch: int
mlflow_run_id: str
registered_model_name: str
registered_model_version: str
def _head_pod_template() -> PodTemplate:
return PodTemplate(
primary_container_name="ray-head",
labels={"auto-e2e.training/role": "ray-head"},
annotations={"karpenter.sh/do-not-disrupt": "true"},
pod_spec=V1PodSpec(
service_account_name="default",
containers=[
V1Container(
name="ray-head",
resources=V1ResourceRequirements(
requests={"cpu": "2", "memory": "16Gi"},
limits={"cpu": "2", "memory": "16Gi"},
),
volume_mounts=[
V1VolumeMount(
name="dshm",
mount_path="/dev/shm",
),
],
),
],
volumes=[
V1Volume(
name="dshm",
empty_dir=V1EmptyDirVolumeSource(
medium="Memory",
size_limit="8Gi",
),
),
],
),
)
def _bev_evaluation_pod_template() -> PodTemplate:
return PodTemplate(
primary_container_name="primary",
annotations={"karpenter.sh/do-not-disrupt": "true"},
pod_spec=V1PodSpec(
service_account_name="default",
node_selector={"workload-type": "gpu-validation"},
tolerations=[
V1Toleration(
key="nvidia.com/gpu",
operator="Exists",
effect="NoSchedule",
),
],
containers=[
V1Container(
name="primary",
volume_mounts=[
V1VolumeMount(
name="dshm",
mount_path="/dev/shm",
),
],
),
],
volumes=[
V1Volume(
name="dshm",
empty_dir=V1EmptyDirVolumeSource(
medium="Memory",
size_limit="16Gi",
),
),
],
),
)
def _worker_pod_template(
*,
workload_type: str,
cpu: str,
memory: str,
shm_size: str,
gpu_count: int,
ephemeral_storage: str | None = None,
require_distinct_hosts: bool = True,
protect_from_disruption: bool = True,
) -> PodTemplate:
worker_labels = {
"auto-e2e.training/role": "ray-gpu-worker",
"auto-e2e.training/workload-type": workload_type,
}
affinity = None
if require_distinct_hosts:
affinity = V1Affinity(
pod_affinity=V1PodAffinity(
required_during_scheduling_ignored_during_execution=[
V1PodAffinityTerm(
label_selector=V1LabelSelector(
match_expressions=[
V1LabelSelectorRequirement(
key=(
"auto-e2e.training/workload-type"
),
operator="In",
values=[workload_type],
),
],
),
topology_key="topology.kubernetes.io/zone",
),
],
),
pod_anti_affinity=V1PodAntiAffinity(
required_during_scheduling_ignored_during_execution=[
V1PodAffinityTerm(
label_selector=V1LabelSelector(
match_expressions=[
V1LabelSelectorRequirement(
key=(
"auto-e2e.training/workload-type"
),
operator="In",
values=[workload_type],
),
],
),
topology_key="kubernetes.io/hostname",
),
],
),
)
resources = {
"cpu": cpu,
"memory": memory,
"nvidia.com/gpu": str(gpu_count),
}
if ephemeral_storage is not None:
resources["ephemeral-storage"] = ephemeral_storage
return PodTemplate(
primary_container_name="ray-worker",
labels=worker_labels,
annotations=(
{"karpenter.sh/do-not-disrupt": "true"}
if protect_from_disruption
else {}
),
pod_spec=V1PodSpec(
service_account_name="default",
node_selector={"workload-type": workload_type},
tolerations=[
V1Toleration(
key="nvidia.com/gpu",
operator="Exists",
effect="NoSchedule",
),
],
affinity=affinity,
containers=[
V1Container(
name="ray-worker",
env=[
V1EnvVar(name="NCCL_DEBUG", value="INFO"),
V1EnvVar(
name="TORCH_DISTRIBUTED_DEBUG",
value="INFO",
),
],
resources=V1ResourceRequirements(
requests=dict(resources),
limits=dict(resources),
),
volume_mounts=[
V1VolumeMount(
name="dshm",
mount_path="/dev/shm",
),
],
),
],
volumes=[
V1Volume(
name="dshm",
empty_dir=V1EmptyDirVolumeSource(
medium="Memory",
size_limit=shm_size,
),
),
],
),
)
def _ray_job_config(
pod_replicas: int,
*,
worker_workload_type: str,
worker_cpu: str = "4",
worker_memory: str = "16Gi",
worker_shm_size: str = "8Gi",
gpus_per_pod: int = 1,
worker_ephemeral_storage: str | None = None,
require_distinct_hosts: bool = True,
protect_workers_from_disruption: bool = True,
) -> RayJobConfig:
return RayJobConfig(
head_node_config=HeadNodeConfig(
ray_start_params={
"dashboard-host": "0.0.0.0",
"num-cpus": "0",
},
pod_template=_head_pod_template(),
),
worker_node_config=[
WorkerNodeConfig(
group_name="gpu-workers",
replicas=pod_replicas,
min_replicas=pod_replicas,
max_replicas=pod_replicas,
ray_start_params={
"num-cpus": worker_cpu,
"num-gpus": str(gpus_per_pod),
},
pod_template=_worker_pod_template(
workload_type=worker_workload_type,
cpu=worker_cpu,
memory=worker_memory,
shm_size=worker_shm_size,
gpu_count=gpus_per_pod,
ephemeral_storage=worker_ephemeral_storage,
require_distinct_hosts=require_distinct_hosts,
protect_from_disruption=(
protect_workers_from_disruption
),
),
),
],
enable_autoscaling=False,
address="auto",
shutdown_after_job_finishes=True,
ttl_seconds_after_finished=300,
)
RAY_1 = _ray_job_config(
1,
worker_workload_type="gpu-validation",
worker_cpu="3",
worker_memory="24Gi",
worker_shm_size="4Gi",
worker_ephemeral_storage="100Gi",
)
RAY_2 = _ray_job_config(
2,
worker_workload_type="gpu-validation",
worker_cpu="3",
worker_memory="12Gi",
worker_shm_size="4Gi",
)
RAY_4 = _ray_job_config(
1,
worker_workload_type="p5en-capacity-block",
worker_cpu="48",
worker_memory="512Gi",
worker_shm_size="64Gi",
gpus_per_pod=4,
worker_ephemeral_storage="500Gi",
require_distinct_hosts=False,
)
RAY_REACTIVE_4 = _ray_job_config(
1,
worker_workload_type="p5en-capacity-block",
worker_cpu="48",
worker_memory="512Gi",
worker_shm_size="64Gi",
gpus_per_pod=4,
worker_ephemeral_storage="500Gi",
require_distinct_hosts=False,
)
RAY_8 = _ray_job_config(
1,
worker_workload_type="p5en-capacity-block",
worker_cpu="96",
worker_memory="1Ti",
worker_shm_size="128Gi",
gpus_per_pod=8,
worker_ephemeral_storage="500Gi",
require_distinct_hosts=False,
)
@task(
task_config=RAY_4,
container_image=TRAINING_IMAGE,
retries=1,
timeout=P5EN_SMOKE_MAX_RUNTIME,
labels={
"kueue.x-k8s.io/queue-name": "p5en-capacity-block",
"kueue.x-k8s.io/priority-class": "research-low",
},
environment=RAY_TASK_ENVIRONMENT,
)
def ray_ddp_smoke_4(
capacity_block_end_utc: str,
steps: int = 4,
) -> RaySmokeOutput:
from distributed_training.ray_smoke import run_smoke
context = current_context()
execution_name = (
context.execution_id.name
if context.execution_id is not None
else "local"
)
run_name = re.sub(
r"[^a-zA-Z0-9_-]",
"-",
f"{execution_name}-ray-ddp-smoke-4",
)
result = run_smoke(
num_workers=4,
steps=steps,
storage_path=RAY_STORAGE_PATH,
run_name=run_name,
capacity_block_end_utc=capacity_block_end_utc,
)
report_path = Path("/tmp/ray-ddp-smoke/report.json")
report_path.parent.mkdir(parents=True, exist_ok=True)
report_path.write_text(
json.dumps(result, indent=2, sort_keys=True) + "\n",
encoding="ascii",
)
return RaySmokeOutput(report=FlyteFile(str(report_path)))
def _flyte_remote_uri(value: FlyteDirectory | FlyteFile) -> str:
remote_source = str(getattr(value, "remote_source", "") or "")
uri = remote_source or str(value)
if not uri.startswith("s3://"):
raise ValueError(
"distributed Ray workers require immutable S3 inputs"
)
return uri.rstrip("/")
def _reactive_worker_cpus(num_workers: int) -> int:
"""Allocate the equal CPU share available to each Ray actor."""
return 3 if num_workers <= 2 else 12
def _reactive_run_name(
*,
execution_name: str,
stage: str,
num_workers: int,
) -> str:
return re.sub(
r"[^a-zA-Z0-9_-]",
"-",
f"{execution_name}-{stage}-ray-{num_workers}-full",
)
def _reactive_mlflow_config_sha256(
config: Mapping[str, Any],
) -> str:
payload = json.dumps(
dict(config),
allow_nan=False,
sort_keys=True,
separators=(",", ":"),
).encode("utf-8")
return hashlib.sha256(payload).hexdigest()
def _reactive_mlflow_params(
config: Mapping[str, Any],
*,
execution_name: str,
) -> dict[str, Any]:
return {
"ctx/flyte_execution_id": execution_name,
"data/stage": config["stage"],
"data/source_partition_count": len(config["source_uris"]),
"model/backbone": config["backbone"],
"model/freeze_bevformer": config["freeze_bevformer"],
"model/is_pretrained": config["is_pretrained"],
"train/bev_encoder_learning_rate": config[
"bev_encoder_learning_rate"
],
"train/bev_weight": config["bev_weight"],
"train/checkpoint_interval_steps": config[
"checkpoint_interval_steps"
],
"train/epochs": config["epochs"],
"train/gradient_accumulation_steps": config[
"gradient_accumulation_steps"
],
"train/learning_rate": config["learning_rate"],
"train/num_loader_workers": config["num_loader_workers"],
"train/per_rank_batch_size": config["per_rank_batch_size"],
"train/precision": config["precision"],
"train/route_weight": config["route_weight"],
"train/seed": config["training_seed"],
"train/training_scope": config["training_scope"],
"train/trajectory_weight": config["trajectory_weight"],
"train/validation_fraction": config["val_fraction"],
"train/validation_sample_limit": config[
"validation_sample_limit"
],
"train/weight_decay": config["weight_decay"],
"train/world_size": config["num_workers"],
}
def _reactive_mlflow_metrics(
metrics: Mapping[str, Any],
) -> dict[str, float]:
result = {}
for name, value in metrics.items():
if (
isinstance(value, bool)
or not isinstance(value, (int, float))
):
continue
numeric_value = float(value)
if math.isfinite(numeric_value):
result[str(name)] = numeric_value
return result
def _start_reactive_mlflow_run(
config: Mapping[str, Any],
*,
execution_name: str,
run_name: str,
):
import mlflow
from mlflow.tracking import MlflowClient
mlflow.set_tracking_uri(os.environ["MLFLOW_TRACKING_URI"])
experiment = mlflow.set_experiment(REACTIVE_MLFLOW_EXPERIMENT)
client = MlflowClient()
config_sha256 = _reactive_mlflow_config_sha256(config)
matches = client.search_runs(
experiment_ids=[experiment.experiment_id],
filter_string=f"tags.reactive_run_key = '{run_name}'",
max_results=2,
)
if len(matches) > 1:
raise RuntimeError(
f"multiple MLflow runs use Reactive key {run_name}"
)
if matches:
run = matches[0]
recorded_sha256 = run.data.tags.get(
"reactive_config_sha256"
)
if recorded_sha256 != config_sha256:
raise ValueError(
"Reactive MLflow run config differs from the Flyte retry"
)
run_id = run.info.run_id
client.set_tag(run_id, "task_status", "RUNNING")
client.set_tag(run_id, "flyte_retry_reused", "true")
return client, run_id
tags = {
"mlflow.runName": run_name,
"pipeline": REACTIVE_MLFLOW_EXPERIMENT,
"reactive_run_key": run_name,
"reactive_config_sha256": config_sha256,
"flyte_execution_id": execution_name,
"stage": str(config["stage"]),
"training_scope": str(config["training_scope"]),
"task_status": "RUNNING",
}
run = client.create_run(
experiment_id=experiment.experiment_id,
start_time=int(time.time() * 1000),
tags=tags,
)
run_id = run.info.run_id
for name, value in _reactive_mlflow_params(
config,
execution_name=execution_name,
).items():
client.log_param(run_id, name, value)
return client, run_id
def _log_reactive_mlflow_result(
client,
run_id: str,
result: Mapping[str, Any],
*,
metadata_path: Path,
) -> None:
_log_reactive_mlflow_history(
client,
run_id,
result["history"],
)
selected_metrics = result["metrics"]
final_metrics = result["final_metrics"]
tags = {
"checkpoint_sha256": str(
selected_metrics["checkpoint_sha256"]
),
"checkpoint_uri": str(result["checkpoint_file_uri"]),
"dataset_manifest_sha256": str(
selected_metrics["dataset_manifest_sha256"]
),
"final_checkpoint_sha256": str(
final_metrics["checkpoint_sha256"]
),
"selected_checkpoint_epoch": str(result["selected_epoch"]),
"task_status": "FINISHED",
}
for name, value in tags.items():
client.set_tag(run_id, name, value)
client.log_artifact(
run_id,
str(metadata_path),
artifact_path="training",
)
client.set_terminated(run_id, status="FINISHED")
def _log_reactive_mlflow_history(
client,
run_id: str,
history: list[Mapping[str, Any]],
) -> None:
from mlflow.entities import Metric
timestamp = int(time.time() * 1000)
for row in history: