-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathcompiler_test.py
5697 lines (4630 loc) · 218 KB
/
compiler_test.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 2020-2022 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 collections
import json
import os
import re
import subprocess
import tempfile
import textwrap
from typing import Any, Dict, List, NamedTuple, Optional
import unittest
from absl.testing import parameterized
from click import testing
from google.protobuf import json_format
import kfp
from kfp import components
from kfp import dsl
from kfp.cli import cli
from kfp.compiler import compiler
from kfp.compiler import compiler_utils
from kfp.dsl import Artifact
from kfp.dsl import ContainerSpec
from kfp.dsl import Dataset
from kfp.dsl import graph_component
from kfp.dsl import Input
from kfp.dsl import Model
from kfp.dsl import Output
from kfp.dsl import OutputPath
from kfp.dsl import pipeline_task
from kfp.dsl import PipelineTaskFinalStatus
from kfp.dsl import tasks_group
from kfp.dsl import yaml_component
from kfp.dsl.types import type_utils
from kfp.pipeline_spec import pipeline_spec_pb2
import yaml
VALID_PRODUCER_COMPONENT_SAMPLE = components.load_component_from_text("""
name: producer
inputs:
- {name: input_param, type: String}
outputs:
- {name: output_model, type: Model}
- {name: output_value, type: Integer}
implementation:
container:
image: gcr.io/my-project/my-image:tag
args:
- {inputValue: input_param}
- {outputPath: output_model}
- {outputPath: output_value}
""")
### components used throughout tests ###
@dsl.component
def flip_coin() -> str:
import random
return 'heads' if random.randint(0, 1) == 0 else 'tails'
@dsl.component
def print_and_return(text: str) -> str:
print(text)
return text
@dsl.component
def roll_three_sided_die() -> str:
import random
val = random.randint(0, 2)
if val == 0:
return 'heads'
elif val == 1:
return 'tails'
else:
return 'draw'
@dsl.component
def int_zero_through_three() -> int:
import random
return random.randint(0, 3)
@dsl.component
def print_op(message: str):
print(message)
@dsl.component
def producer_op() -> str:
return 'a'
@dsl.component
def dummy_op(msg: str = ''):
pass
@dsl.component
def hello_world(text: str) -> str:
"""Hello world component."""
return text
@dsl.component
def add(nums: List[int]) -> int:
return sum(nums)
@dsl.component
def comp():
pass
@dsl.component
def return_1() -> int:
return 1
@dsl.component
def args_generator_op() -> List[Dict[str, str]]:
return [{'A_a': '1', 'B_b': '2'}, {'A_a': '10', 'B_b': '20'}]
@dsl.component
def my_comp(string: str, model: bool) -> str:
return string
@dsl.component
def print_hello():
print('hello')
@dsl.component
def cleanup():
print('cleanup')
@dsl.component
def double(num: int) -> int:
return 2 * num
@dsl.component
def print_and_return_as_artifact(text: str, a: Output[Artifact]):
print(text)
with open(a.path, 'w') as f:
f.write(text)
@dsl.component
def print_and_return_with_output_key(text: str, output_key: OutputPath(str)):
print(text)
with open(output_key, 'w') as f:
f.write(text)
@dsl.component
def print_artifact(a: Input[Artifact]):
with open(a.path) as f:
print(f.read())
###########
class TestCompilePipeline(parameterized.TestCase):
def test_can_use_dsl_attribute_on_kfp(self):
@kfp.dsl.pipeline
def my_pipeline(string: str = 'string'):
op1 = print_and_return(text=string)
with tempfile.TemporaryDirectory() as tmpdir:
compiler.Compiler().compile(
pipeline_func=my_pipeline,
package_path=os.path.join(tmpdir, 'pipeline.yaml'))
def test_compile_simple_pipeline(self):
with tempfile.TemporaryDirectory() as tmpdir:
producer_op = components.load_component_from_text("""
name: producer
inputs:
- {name: input_param, type: String}
outputs:
- {name: output_model, type: Model}
- {name: output_value, type: Integer}
implementation:
container:
image: gcr.io/my-project/my-image:tag
args:
- {inputValue: input_param}
- {outputPath: output_model}
- {outputPath: output_value}
""")
consumer_op = components.load_component_from_text("""
name: consumer
inputs:
- {name: input_model, type: Model}
- {name: input_value, type: Integer}
implementation:
container:
image: gcr.io/my-project/my-image:tag
args:
- {inputPath: input_model}
- {inputValue: input_value}
""")
@dsl.pipeline(name='test-pipeline')
def simple_pipeline(pipeline_input: str = 'Hello KFP!'):
producer = producer_op(input_param=pipeline_input)
consumer = consumer_op(
input_model=producer.outputs['output_model'],
input_value=producer.outputs['output_value'])
target_file = os.path.join(tmpdir, 'result.yaml')
compiler.Compiler().compile(
pipeline_func=simple_pipeline, package_path=target_file)
self.assertTrue(os.path.exists(target_file))
with open(target_file, 'r') as f:
f.read()
def test_compile_pipeline_with_bool(self):
with tempfile.TemporaryDirectory() as tmpdir:
predict_op = components.load_component_from_text("""
name: predict
inputs:
- {name: generate_explanation, type: Boolean, default: False}
implementation:
container:
image: gcr.io/my-project/my-image:tag
args:
- {inputValue: generate_explanation}
""")
@dsl.pipeline(name='test-boolean-pipeline')
def simple_pipeline():
predict_op(generate_explanation=True)
target_json_file = os.path.join(tmpdir, 'result.yaml')
compiler.Compiler().compile(
pipeline_func=simple_pipeline, package_path=target_json_file)
self.assertTrue(os.path.exists(target_json_file))
with open(target_json_file, 'r') as f:
f.read()
def test_compile_pipeline_with_misused_inputvalue_should_raise_error(self):
upstream_op = components.load_component_from_text("""
name: upstream compoent
outputs:
- {name: model, type: Model}
implementation:
container:
image: dummy
args:
- {outputPath: model}
""")
downstream_op = components.load_component_from_text("""
name: compoent with misused placeholder
inputs:
- {name: model, type: Model}
implementation:
container:
image: dummy
args:
- {inputValue: model}
""")
with self.assertRaisesRegex(
TypeError,
' type "[email protected]" cannot be paired with InputValuePlaceholder.'
):
@dsl.pipeline(name='test-pipeline')
def my_pipeline():
downstream_op(model=upstream_op().output)
def test_compile_pipeline_with_misused_inputpath_should_raise_error(self):
component_op = components.load_component_from_text("""
name: compoent with misused placeholder
inputs:
- {name: text, type: String}
implementation:
container:
image: dummy
args:
- {inputPath: text}
""")
with self.assertRaisesRegex(
TypeError,
' type "String" cannot be paired with InputPathPlaceholder.'):
@dsl.pipeline(name='test-pipeline')
def my_pipeline(text: str):
component_op(text=text)
def test_compile_pipeline_with_missing_task_should_raise_error(self):
with self.assertRaisesRegex(ValueError,
'Task is missing from pipeline.'):
@dsl.pipeline(name='test-pipeline')
def my_pipeline(text: str):
pass
def test_compile_pipeline_with_misused_inputuri_should_raise_error(self):
component_op = components.load_component_from_text("""
name: compoent with misused placeholder
inputs:
- {name: value, type: Float}
implementation:
container:
image: dummy
args:
- {inputUri: value}
""")
with self.assertRaisesRegex(
TypeError,
' type "Float" cannot be paired with InputUriPlaceholder.'):
@dsl.pipeline(name='test-pipeline')
def my_pipeline(value: float):
component_op(value=value)
def test_compile_pipeline_with_misused_outputuri_should_raise_error(self):
component_op = components.load_component_from_text("""
name: compoent with misused placeholder
outputs:
- {name: value, type: Integer}
implementation:
container:
image: dummy
args:
- {outputUri: value}
""")
with self.assertRaisesRegex(
TypeError,
' type "Integer" cannot be paired with OutputUriPlaceholder.'):
@dsl.pipeline(name='test-pipeline')
def my_pipeline():
component_op()
def test_compile_pipeline_with_invalid_name_should_raise_error(self):
@dsl.pipeline(name='')
def my_pipeline():
VALID_PRODUCER_COMPONENT_SAMPLE(input_param='input')
with tempfile.TemporaryDirectory() as tmpdir:
output_path = os.path.join(tmpdir, 'output.yaml')
compiler.Compiler().compile(
pipeline_func=my_pipeline, package_path=output_path)
def test_set_pipeline_root_through_pipeline_decorator(self):
@dsl.pipeline(name='test-pipeline', pipeline_root='gs://path')
def my_pipeline():
VALID_PRODUCER_COMPONENT_SAMPLE(input_param='input')
self.assertEqual(my_pipeline.pipeline_spec.default_pipeline_root,
'gs://path')
def test_set_display_name_through_pipeline_decorator(self):
@dsl.pipeline(display_name='my display name')
def my_pipeline():
VALID_PRODUCER_COMPONENT_SAMPLE(input_param='input')
self.assertEqual(my_pipeline.pipeline_spec.pipeline_info.display_name,
'my display name')
def test_set_name_and_display_name_through_pipeline_decorator(self):
@dsl.pipeline(
name='my-pipeline-name',
display_name='my display name',
)
def my_pipeline():
VALID_PRODUCER_COMPONENT_SAMPLE(input_param='input')
self.assertEqual(my_pipeline.pipeline_spec.pipeline_info.name,
'my-pipeline-name')
self.assertEqual(my_pipeline.pipeline_spec.pipeline_info.display_name,
'my display name')
def test_set_description_through_pipeline_decorator(self):
@dsl.pipeline(description='Prefer me.')
def my_pipeline():
"""Don't prefer me"""
VALID_PRODUCER_COMPONENT_SAMPLE(input_param='input')
self.assertEqual(my_pipeline.pipeline_spec.pipeline_info.description,
'Prefer me.')
def test_set_description_through_pipeline_docstring_short(self):
@dsl.pipeline
def my_pipeline():
"""Docstring-specified description."""
VALID_PRODUCER_COMPONENT_SAMPLE(input_param='input')
self.assertEqual(my_pipeline.pipeline_spec.pipeline_info.description,
'Docstring-specified description.')
def test_set_description_through_pipeline_docstring_long(self):
@dsl.pipeline
def my_pipeline():
"""Docstring-specified description.
More information about this pipeline."""
VALID_PRODUCER_COMPONENT_SAMPLE(input_param='input')
self.assertEqual(
my_pipeline.pipeline_spec.pipeline_info.description,
'Docstring-specified description.\nMore information about this pipeline.'
)
def test_passing_string_parameter_to_artifact_should_error(self):
component_op = components.load_component_from_text("""
name: component
inputs:
- {name: some_input, type: , description: an uptyped input}
implementation:
container:
image: dummy
args:
- {inputPath: some_input}
""")
with self.assertRaisesRegex(
type_utils.InconsistentTypeException,
"Incompatible argument passed to the input 'some_input' of "
"component 'component': Argument type 'STRING' is incompatible "
"with the input type '[email protected]'"):
@dsl.pipeline(name='test-pipeline', pipeline_root='gs://path')
def my_pipeline(input1: str):
component_op(some_input=input1)
def test_passing_missing_type_annotation_on_pipeline_input_should_error(
self):
with self.assertRaisesRegex(
TypeError, 'Missing type annotation for argument: input1'):
@dsl.pipeline(name='test-pipeline', pipeline_root='gs://path')
def my_pipeline(input1):
pass
def test_passing_generic_artifact_to_input_expecting_concrete_artifact(
self):
producer_op1 = components.load_component_from_text("""
name: producer compoent
outputs:
- {name: output, type: Artifact}
implementation:
container:
image: dummy
args:
- {outputPath: output}
""")
@dsl.component
def producer_op2(output: dsl.Output[dsl.Artifact]):
pass
consumer_op1 = components.load_component_from_text("""
name: consumer compoent
inputs:
- {name: input1, type: MyDataset}
implementation:
container:
image: dummy
args:
- {inputPath: input1}
""")
@dsl.component
def consumer_op2(input1: dsl.Input[dsl.Dataset]):
pass
@dsl.pipeline(name='test-pipeline')
def my_pipeline():
consumer_op1(input1=producer_op1().output)
consumer_op1(input1=producer_op2().output)
consumer_op2(input1=producer_op1().output)
consumer_op2(input1=producer_op2().output)
with tempfile.TemporaryDirectory() as tmpdir:
target_yaml_file = os.path.join(tmpdir, 'result.yaml')
compiler.Compiler().compile(
pipeline_func=my_pipeline, package_path=target_yaml_file)
self.assertTrue(os.path.exists(target_yaml_file))
def test_passing_concrete_artifact_to_input_expecting_generic_artifact(
self):
producer_op1 = components.load_component_from_text("""
name: producer compoent
outputs:
- {name: output, type: Dataset}
implementation:
container:
image: dummy
args:
- {outputPath: output}
""")
@dsl.component
def producer_op2(output: dsl.Output[dsl.Model]):
pass
consumer_op1 = components.load_component_from_text("""
name: consumer compoent
inputs:
- {name: input1, type: Artifact}
implementation:
container:
image: dummy
args:
- {inputPath: input1}
""")
@dsl.component
def consumer_op2(input1: dsl.Input[dsl.Artifact]):
pass
@dsl.pipeline(name='test-pipeline')
def my_pipeline():
consumer_op1(input1=producer_op1().output)
consumer_op1(input1=producer_op2().output)
consumer_op2(input1=producer_op1().output)
consumer_op2(input1=producer_op2().output)
with tempfile.TemporaryDirectory() as tmpdir:
target_yaml_file = os.path.join(tmpdir, 'result.yaml')
compiler.Compiler().compile(
pipeline_func=my_pipeline, package_path=target_yaml_file)
self.assertTrue(os.path.exists(target_yaml_file))
def test_passing_arbitrary_artifact_to_input_expecting_concrete_artifact(
self):
producer_op1 = components.load_component_from_text("""
name: producer compoent
outputs:
- {name: output, type: SomeArbitraryType}
implementation:
container:
image: dummy
args:
- {outputPath: output}
""")
@dsl.component
def consumer_op(input1: dsl.Input[dsl.Dataset]):
pass
@dsl.pipeline(name='test-pipeline')
def my_pipeline():
consumer_op(input1=producer_op1().output)
with tempfile.TemporaryDirectory() as tmpdir:
target_yaml_file = os.path.join(tmpdir, 'result.yaml')
compiler.Compiler().compile(
pipeline_func=my_pipeline, package_path=target_yaml_file)
self.assertTrue(os.path.exists(target_yaml_file))
def test_invalid_data_dependency_loop(self):
with self.assertRaisesRegex(
compiler_utils.InvalidTopologyException,
r'Illegal task dependency across DSL context managers\. A downstream task cannot depend on an upstream task within a dsl\.ParallelFor context unless the downstream is within that context too or the outputs are begin fanned-in to a list using dsl\.Collected\. Found task dummy-op which depends on upstream task producer-op within an uncommon dsl\.ParallelFor context\.'
):
@dsl.pipeline(name='test-pipeline')
def my_pipeline(val: bool):
with dsl.ParallelFor(['a, b']):
producer_task = producer_op()
dummy_op(msg=producer_task.output)
def test_invalid_data_dependency_condition(self):
with self.assertRaisesRegex(
compiler_utils.InvalidTopologyException,
r'Illegal task dependency across DSL context managers\. A downstream task cannot depend on an upstream task within a dsl\.Condition context unless the downstream is within that context too\. Found task dummy-op which depends on upstream task producer-op within an uncommon dsl\.Condition context\.'
):
@dsl.pipeline(name='test-pipeline')
def my_pipeline(val: bool):
with dsl.Condition(val == False):
producer_task = producer_op()
dummy_op(msg=producer_task.output)
def test_valid_data_dependency_condition(self):
@dsl.pipeline(name='test-pipeline')
def my_pipeline(val: bool):
with dsl.Condition(val == False):
producer_task = producer_op()
dummy_op(msg=producer_task.output)
with tempfile.TemporaryDirectory() as tmpdir:
package_path = os.path.join(tmpdir, 'pipeline.yaml')
compiler.Compiler().compile(
pipeline_func=my_pipeline, package_path=package_path)
def test_invalid_data_dependency_exit_handler(self):
with self.assertRaisesRegex(
compiler_utils.InvalidTopologyException,
r'Illegal task dependency across DSL context managers\. A downstream task cannot depend on an upstream task within a dsl\.ExitHandler context unless the downstream is within that context too\. Found task dummy-op which depends on upstream task producer-op-2 within an uncommon dsl\.ExitHandler context\.'
):
@dsl.pipeline(name='test-pipeline')
def my_pipeline(val: bool):
first_producer = producer_op()
with dsl.ExitHandler(first_producer):
producer_task = producer_op()
dummy_op(msg=producer_task.output)
def test_valid_data_dependency_exit_handler(self):
@dsl.pipeline(name='test-pipeline')
def my_pipeline(val: bool):
first_producer = producer_op()
with dsl.ExitHandler(first_producer):
producer_task = producer_op()
dummy_op(msg=producer_task.output)
with tempfile.TemporaryDirectory() as tmpdir:
package_path = os.path.join(tmpdir, 'pipeline.yaml')
compiler.Compiler().compile(
pipeline_func=my_pipeline, package_path=package_path)
def test_use_task_final_status_in_non_exit_op(self):
@dsl.component
def print_op(status: PipelineTaskFinalStatus):
return status
with self.assertRaisesRegex(
ValueError,
'PipelineTaskFinalStatus can only be used in an exit task.'):
@dsl.pipeline(name='test-pipeline')
def my_pipeline(text: bool):
print_op()
def test_use_task_final_status_in_non_exit_op_yaml(self):
print_op = components.load_component_from_text("""
name: Print Op
inputs:
- {name: message, type: PipelineTaskFinalStatus}
implementation:
container:
image: python:3.9
command:
- echo
- {inputValue: message}
""")
with self.assertRaisesRegex(
ValueError,
'PipelineTaskFinalStatus can only be used in an exit task.'):
@dsl.pipeline(name='test-pipeline')
def my_pipeline(text: bool):
print_op()
def test_task_final_status_parameter_type_is_used(self):
# previously compiled to STRUCT type, so checking that this is updated
@dsl.component
def exit_comp(status: dsl.PipelineTaskFinalStatus):
print(status)
@dsl.pipeline
def my_pipeline():
exit_task = exit_comp()
with dsl.ExitHandler(exit_task=exit_task):
print_and_return(text='hi')
self.assertEqual(
my_pipeline.pipeline_spec.components['comp-exit-comp']
.input_definitions.parameters['status'].parameter_type,
pipeline_spec_pb2.ParameterType.TASK_FINAL_STATUS)
def test_compile_parallel_for_with_valid_parallelism(self):
@dsl.component
def producer_op(item: str) -> str:
return item
@dsl.pipeline(name='test-parallel-for-with-parallelism')
def my_pipeline(text: bool):
with dsl.ParallelFor(items=['a', 'b'], parallelism=2) as item:
producer_task = producer_op(item=item)
with tempfile.TemporaryDirectory() as tempdir:
output_yaml = os.path.join(tempdir, 'result.yaml')
compiler.Compiler().compile(
pipeline_func=my_pipeline, package_path=output_yaml)
with open(output_yaml, 'r') as f:
pipeline_spec = yaml.safe_load(f)
self.assertEqual(
pipeline_spec['root']['dag']['tasks']['for-loop-2']
['iteratorPolicy']['parallelismLimit'], 2)
def test_compile_parallel_for_with_incompatible_input_type(self):
@dsl.component
def producer_op(item: str) -> str:
return item
@dsl.component
def list_dict_maker() -> List[Dict[str, int]]:
return [{'a': 1, 'b': 2}, {'a': 2, 'b': 3}, {'a': 3, 'b': 4}]
with self.assertRaisesRegex(
type_utils.InconsistentTypeException,
"Incompatible argument passed to the input 'item' of component 'producer-op': Argument type 'NUMBER_INTEGER' is incompatible with the input type 'STRING'"
):
@dsl.pipeline
def my_pipeline(text: bool):
with dsl.ParallelFor(items=list_dict_maker().output) as item:
producer_task = producer_op(item=item.a)
def test_compile_parallel_for_with_relaxed_type_checking(self):
@dsl.component
def producer_op(item: str) -> str:
return item
@dsl.component
def list_dict_maker() -> List[Dict]:
return [{'a': 1, 'b': 2}, {'a': 2, 'b': 3}, {'a': 3, 'b': 4}]
@dsl.pipeline
def my_pipeline(text: bool):
with dsl.ParallelFor(items=list_dict_maker().output) as item:
producer_task = producer_op(item=item.a)
def test_compile_parallel_for_with_invalid_parallelism(self):
@dsl.component
def producer_op(item: str) -> str:
return item
with self.assertRaisesRegex(ValueError,
'ParallelFor parallelism must be >= 0.'):
@dsl.pipeline(name='test-parallel-for-with-parallelism')
def my_pipeline(text: bool):
with dsl.ParallelFor(items=['a', 'b'], parallelism=-2) as item:
producer_task = producer_op(item=item)
def test_compile_parallel_for_with_zero_parallelism(self):
@dsl.component
def producer_op(item: str) -> str:
return item
@dsl.pipeline(name='test-parallel-for-with-parallelism')
def my_pipeline(text: bool):
with dsl.ParallelFor(items=['a', 'b'], parallelism=0) as item:
producer_task = producer_op(item=item)
with dsl.ParallelFor(items=['a', 'b']) as item:
producer_task = producer_op(item=item)
with tempfile.TemporaryDirectory() as tempdir:
output_yaml = os.path.join(tempdir, 'result.yaml')
compiler.Compiler().compile(
pipeline_func=my_pipeline, package_path=output_yaml)
with open(output_yaml, 'r') as f:
pipeline_spec = yaml.safe_load(f)
for_loop_2 = pipeline_spec['root']['dag']['tasks']['for-loop-2']
for_loop_4 = pipeline_spec['root']['dag']['tasks']['for-loop-4']
with self.assertRaises(KeyError):
for_loop_2['iteratorPolicy']
with self.assertRaises(KeyError):
for_loop_4['iteratorPolicy']
def test_cannot_compile_parallel_for_with_single_param(self):
with self.assertRaisesRegex(
ValueError,
r'Cannot iterate over a single parameter using `dsl\.ParallelFor`\. Expected a list of parameters as argument to `items`\.'
):
@dsl.pipeline
def my_pipeline():
single_param_task = print_and_return(text='string')
with dsl.ParallelFor(items=single_param_task.output) as item:
print_and_return(text=item)
def test_cannot_compile_parallel_for_with_single_artifact(self):
with self.assertRaisesRegex(
ValueError,
r'Cannot iterate over a single artifact using `dsl\.ParallelFor`\. Expected a list of artifacts as argument to `items`\.'
):
@dsl.pipeline
def my_pipeline():
single_artifact_task = print_and_return_as_artifact(
text='string')
with dsl.ParallelFor(items=single_artifact_task.output) as item:
print_artifact(a=item)
def test_pipeline_in_pipeline(self):
@dsl.pipeline(name='graph-component')
def graph_component(msg: str):
print_op(message=msg)
@dsl.pipeline(name='test-pipeline')
def my_pipeline():
graph_component(msg='hello')
with tempfile.TemporaryDirectory() as tmpdir:
output_yaml = os.path.join(tmpdir, 'result.yaml')
compiler.Compiler().compile(
pipeline_func=my_pipeline, package_path=output_yaml)
self.assertTrue(os.path.exists(output_yaml))
with open(output_yaml, 'r') as f:
pipeline_spec = yaml.safe_load(f)
self.assertEqual(2, len(pipeline_spec['components']))
self.assertTrue('comp-print-op' in pipeline_spec['components'])
self.assertTrue(
'comp-graph-component' in pipeline_spec['components'])
self.assertEqual(
1, len(pipeline_spec['deploymentSpec']['executors']))
self.assertTrue('exec-print-op' in
pipeline_spec['deploymentSpec']['executors'])
def test_pipeline_with_invalid_output(self):
with self.assertRaisesRegex(
ValueError, r'Pipeline or component output not defined: msg1'):
@dsl.pipeline
def my_pipeline() -> NamedTuple('Outputs', [
('msg', str),
]):
task = print_and_return(text='Hello')
output = collections.namedtuple('Outputs', ['msg1'])
return output(task.output)
def test_pipeline_with_missing_output(self):
with self.assertRaisesRegex(ValueError, 'Missing pipeline output: msg'):
@dsl.pipeline
def my_pipeline() -> NamedTuple('Outputs', [
('msg', str),
]):
task = print_and_return(text='Hello')
with self.assertRaisesRegex(ValueError,
'Missing pipeline output: model'):
@dsl.pipeline
def my_pipeline() -> NamedTuple('Outputs', [
('model', dsl.Model),
]):
task = print_and_return(text='Hello')
class TestCompilePipelineCaching(unittest.TestCase):
def test_compile_pipeline_with_caching_enabled(self):
"""Test pipeline compilation with caching enabled."""
@dsl.component
def my_component():
pass
@dsl.pipeline(name='tiny-pipeline')
def my_pipeline():
my_task = my_component()
my_task.set_caching_options(True)
with tempfile.TemporaryDirectory() as tempdir:
output_yaml = os.path.join(tempdir, 'pipeline.yaml')
compiler.Compiler().compile(
pipeline_func=my_pipeline, package_path=output_yaml)
with open(output_yaml, 'r') as f:
pipeline_spec = yaml.safe_load(f)
task_spec = pipeline_spec['root']['dag']['tasks']['my-component']
caching_options = task_spec['cachingOptions']
self.assertTrue(caching_options['enableCache'])
def test_compile_pipeline_with_caching_disabled(self):
"""Test pipeline compilation with caching disabled."""
@dsl.component
def my_component():
pass
@dsl.pipeline(name='tiny-pipeline')
def my_pipeline():
my_task = my_component()
my_task.set_caching_options(False)
with tempfile.TemporaryDirectory() as tempdir:
output_yaml = os.path.join(tempdir, 'pipeline.yaml')
compiler.Compiler().compile(
pipeline_func=my_pipeline, package_path=output_yaml)
with open(output_yaml, 'r') as f:
pipeline_spec = yaml.safe_load(f)
task_spec = pipeline_spec['root']['dag']['tasks']['my-component']
caching_options = task_spec.get('cachingOptions', {})
self.assertEqual(caching_options, {})
class V2NamespaceAliasTest(unittest.TestCase):
"""Test that imports of both modules and objects are aliased (e.g. all
import path variants work)."""
# Note: The DeprecationWarning is only raised on the first import where
# the kfp.v2 module is loaded. Due to the way we run tests in CI/CD, we cannot ensure that the kfp.v2 module will first be loaded in these tests,
# so we do not test for the DeprecationWarning here.
def test_import_namespace(self):
from kfp import v2
@v2.dsl.component
def hello_world(text: str) -> str:
"""Hello world component."""
return text
@v2.dsl.pipeline(
name='hello-world', description='A simple intro pipeline')
def pipeline_hello_world(text: str = 'hi there'):
"""Hello world pipeline."""
hello_world(text=text)
with tempfile.TemporaryDirectory() as tempdir:
# you can e.g. create a file here:
temp_filepath = os.path.join(tempdir, 'hello_world_pipeline.yaml')
v2.compiler.Compiler().compile(
pipeline_func=pipeline_hello_world, package_path=temp_filepath)
with open(temp_filepath, 'r') as f:
yaml.safe_load(f)
def test_import_modules(self):
from kfp.v2 import compiler
from kfp.v2 import dsl