forked from mlcommons/mlperf-automations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodule.py
6457 lines (5116 loc) · 244 KB
/
module.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
# This file is originally created for CM Script automations and is now
# modified to make it work for MLC automation.
# CM "script" automation helps users to encode their MLOps, DevOps and other knowledge
# as portable and reusable automation recipes with simple tags, native scripts
# and a unified CLI, Python API and JSON/YAML meta descriptions.
#
# This is a stable prototype of the MLC script automation being developed by Grigori Fursin and Arjun Suresh
#
#
import os
import logging
from mlc.main import Automation
import mlc.utils as utils
from utils import *
class ScriptAutomation(Automation):
"""
MLC "script" automation actions
(making native scripts more portable, deterministic, reusable and reproducible)
"""
############################################################
def __init__(self, action_object, automation_file):
super().__init__(action_object, "script", automation_file)
logging.basicConfig(level=logging.INFO)
self.os_info = {}
self.run_state = {}
self.run_state['deps'] = []
self.run_state['fake_deps'] = False
self.run_state['parent'] = None
self.run_state['version_info'] = []
self.run_state['cache'] = False
self.file_with_cached_state = 'mlc-cached-state.json'
self.tmp_file_env = 'tmp-env'
self.tmp_file_env_all = 'tmp-env-all'
self.tmp_file_run = 'tmp-run'
self.tmp_file_state = 'tmp-state.json'
self.tmp_file_run_state = 'tmp-run-state.json'
self.tmp_file_run_env = 'tmp-run-env.out'
self.tmp_file_ver = 'tmp-ver.out'
self.__version__ = "1.3.2"
self.local_env_keys = ['MLC_VERSION',
'MLC_VERSION_MIN',
'MLC_VERSION_MAX',
'MLC_VERSION_MAX_USABLE',
'MLC_DETECTED_VERSION',
'MLC_INPUT',
'MLC_OUTPUT',
'MLC_OUTBASENAME',
'MLC_OUTDIRNAME',
'MLC_NAME',
'MLC_EXTRA_CACHE_TAGS',
'MLC_TMP_*',
'MLC_GIT_*',
'MLC_RENEW_CACHE_ENTRY']
self.input_flags_converted_to_tmp_env = ['path']
self.input_flags_converted_to_env = ['input',
'output',
'outdirname',
'outbasename',
'name',
'extra_cache_tags',
'skip_compile',
'skip_run',
'accept_license',
'skip_system_deps',
'git_ssh',
'gh_token',
'hf_token']
############################################################
def run(self, i):
"""
Run MLC script
Args:
(MLC input dict):
(out) (str): if 'con', output to console
(artifact) (str): specify MLC script (MLC artifact) explicitly
(tags) (str): tags to find an MLC script (MLC artifact)
(env) (dict): global environment variables (can/will be updated by a given script and dependencies)
(const) (dict): constant environment variable (will be preserved and persistent for a given script and dependencies)
(state) (dict): global state dictionary (can/will be updated by a given script and dependencies)
(const_state) (dict): constant state (will be preserved and persistent for a given script and dependencies)
(add_deps) (dict): {"name": {"tag": "tag(s)"}, "name": {"version": "version_no"}, ...}
(add_deps_recursive) (dict): same as add_deps but is passed recursively onto dependencies as well
(version) (str): version to be added to env.MLC_VERSION to specialize this flow
(version_min) (str): min version to be added to env.MLC_VERSION_MIN to specialize this flow
(version_max) (str): max version to be added to env.MLC_VERSION_MAX to specialize this flow
(version_max_usable) (str): max USABLE version to be added to env.MLC_VERSION_MAX_USABLE
(path) (str): list of paths to be added to env.MLC_TMP_PATH to specialize this flow
(input) (str): converted to env.MLC_INPUT (local env)
(output) (str): converted to env.MLC_OUTPUT (local env)
(outbasename) (str): converted to env.MLC_OUTBASENAME (local env)
(outdirname) (str): converted to env.MLC_OUTDIRNAME (local env)
(extra_cache_tags) (str): converted to env.MLC_EXTRA_CACHE_TAGS and used to add to caching (local env)
(name) (str): taken from env.MLC_NAME and/or converted to env.MLC_NAME (local env)
Added to extra_cache_tags with "name-" prefix .
Useful for python virtual env (to create multiple entries)
(quiet) (bool): if True, set env.MLC_QUIET to "yes" and attempt to skip questions
(the developers have to support it in pre/post processing and scripts)
(skip_cache) (bool): if True, skip caching and run in current directory
(force_cache) (bool): if True, force caching if can_force_cache=true in script meta
(skip_remembered_selections) (bool): if True, skip remembered selections
(uses or sets env.MLC_TMP_SKIP_REMEMBERED_SELECTIONS to "yes")
(new) (bool): if True, skip search for cached and run again
(renew) (bool): if True, rewrite cache entry if exists
(dirty) (bool): if True, do not clean files
(save_env) (bool): if True, save env and state to tmp-env.sh/bat and tmp-state.json
(shell) (bool): if True, save env with cmd/bash and run it
(recursion) (bool): True if recursive call.
Useful when preparing the global bat file or Docker container
to save/run it in the end.
(recursion_spaces) (str, internal): adding ' ' during recursion for debugging
(remembered_selections) (list): remember selections of cached outputs
(print_env) (bool): if True, print aggregated env before each run of a native script
(fake_run) (bool): if True, will run the dependent scripts but will skip the main run script
(prepare) (bool): the same as fake_run
(fake_deps) (bool): if True, will fake run the dependent scripts
(run_state) (dict): Internal run state
(debug_script_tags) (str): if !='', run cmd/bash before executing a native command
inside a script specified by these tags
(debug_script) (bool): if True, debug current script (set debug_script_tags to the tags of a current script)
(debug_uid) (str): if True, set MLC_TMP_DEBUG_UID to this number to enable
remote python debugging of scripts and wrapped apps/tools
(detected_versions) (dict): All the used scripts and their detected_versions
(verbose) (bool): if True, prints all tech. info about script execution (False by default)
(v) (bool): the same as verbose
(time) (bool): if True, print script execution time (or if verbose == True)
(space) (bool): if True, print used disk space for this script (or if verbose == True)
(ignore_script_error) (bool): if True, ignore error code in native tools and scripts
and finish a given MLC script. Useful to test/debug partial installations
(json) (bool): if True, print output as JSON
(j) (bool): if True, print output as JSON
(pause) (bool): if True, pause at the end of the main script (Press Enter to continue)
(repro) (bool): if True, dump mlc-run-script-input.json, mlc-run_script_output.json,
mlc-run-script-state.json, mlc-run-script-info.json
to improve the reproducibility of results
(repro_prefix) (str): if !='', use it to record above files {repro-prefix)-input.json ...
(repro_dir) (str): if !='', use this directory to dump info (default = 'mlc-repro')
(dump_version_info) (bool): dump info about resolved versions of tools in dependencies
(print_deps) (bool): if True, will print the MLC run commands of the direct dependent scripts
(print_readme) (bool): if True, will print README with all MLC steps (deps) to run a given script
(script_call_prefix) (str): how to call script in logs and READMEs (mlc run script)
(skip_sys_utils) (bool): if True, set env['MLC_SKIP_SYS_UTILS']='yes'
to skip MLC sys installation
(skip_sudo) (bool): if True, set env['MLC_TMP_SKIP_SUDO']='yes'
to let scripts deal with that
(silent) (bool): if True, attempt to suppress all info if supported
(sets MLC_TMP_SILENT=yes)
(s) (bool): the same as 'silent'
...
Returns:
(MLC return dict):
* return (int): return code == 0 if no error and >0 if error
* (error) (str): error string if return>0
* (skipped) (bool): if true, this script was skipped
* new_env (dict): new environment (delta from a collective script)
* new_state (dict): new state (delta from a collective script)
* env (dict): global env (updated by this script - includes new_env)
* state (dict): global state (updated by this script - includes new_state)
"""
r = self._run(i)
return r
############################################################
def _run(self, i):
# from cmind import utils
import copy
import time
import shutil
# Check if save input/output to file
repro = i.get('repro', False)
repro_prefix = ''
if repro:
repro_prefix = i.get('repro_prefix', '')
if repro_prefix == '':
repro_prefix = 'mlc-run-script'
repro_dir = i.get('repro_dir', '')
if repro_dir == '':
repro_dir = os.path.join(os.getcwd(), 'mlc-repro')
if not os.path.isdir(repro_dir):
os.makedirs(repro_dir)
repro_prefix = os.path.join(repro_dir, repro_prefix)
if repro_prefix != '':
dump_repro_start(repro_prefix, i)
recursion = i.get('recursion', False)
# If first script run, check if can write to current directory
if not recursion and not i.get('skip_write_test', False):
if not can_write_to_current_directory():
return {
'return': 1, 'error': 'Current directory "{}" is not writable - please change it'.format(os.getcwd())}
'''
# Check if has default config
r = self.action_object.access({'action': 'load',
'automation': 'cfg,88dce9c160324c5d',
'artifact': 'default'})
if r['return'] == 0:
config = r['config']
script_input = config.get('script', {})
if len(script_input) > 0:
utils.merge_dicts({'dict1': i, 'dict2': script_input})
'''
recursion_int = int(i.get('recursion_int', 0)) + 1
start_time = time.time()
# Check extra input from environment variable MLC_SCRIPT_EXTRA_CMD
# Useful to set up default flags such as the name of virtual enviroment
extra_cli = os.environ.get('MLC_SCRIPT_EXTRA_CMD', '').strip()
if extra_cli != '':
from cmind import cli
r = cli.parse(extra_cli)
if r['return'] > 0:
return r
mlc_input = r['mlc_input']
utils.merge_dicts({'dict1': i,
'dict2': mlc_input,
'append_lists': True,
'append_unique': True})
# Check if has extra tags as a second artifact
# Example: cmr . "_python _tiny"
parsed_artifacts = i.get('parsed_artifacts', [])
if len(parsed_artifacts) > 0:
extra_tags = parsed_artifacts[0][0][0]
if ' ' in extra_tags or ',' in extra_tags:
# Add tags
x = i.get('tags', '')
if x != '':
x += ','
i['tags'] = x + extra_tags.replace(' ', ',')
# Recursion spaces needed to format log and print
recursion_spaces = i.get('recursion_spaces', '')
# Caching selections to avoid asking users again
remembered_selections = i.get('remembered_selections', [])
# Get current env and state before running this script and sub-scripts
env = i.get('env', {})
state = i.get('state', {})
const = i.get('const', {})
const_state = i.get('const_state', {})
# Save current env and state to detect new env and state after running
# a given script
saved_env = copy.deepcopy(env)
saved_state = copy.deepcopy(state)
for key in ["env", "state", "const", "const_state"]:
if i.get("local_" + key):
if not i.get(key, {}):
i[key] = {}
utils.merge_dicts({'dict1': i[key],
'dict2': i['local_' + key],
'append_lists': True,
'append_unique': True})
# print(f"Merged local {key}: {i[key]}")
# print(f"env = {env}")
add_deps = i.get('ad', {})
if not add_deps:
add_deps = i.get('add_deps', {})
else:
utils.merge_dicts({'dict1': add_deps, 'dict2': i.get(
'add_deps', {}), 'append_lists': True, 'append_unique': True})
add_deps_recursive = i.get('adr', {})
if not add_deps_recursive:
add_deps_recursive = i.get('add_deps_recursive', {})
else:
utils.merge_dicts({'dict1': add_deps_recursive, 'dict2': i.get(
'add_deps_recursive', {}), 'append_lists': True, 'append_unique': True})
save_env = i.get('save_env', False)
print_env = i.get('print_env', False)
show_time = i.get('time', False)
show_space = i.get('space', False)
if not recursion and show_space:
start_disk_stats = shutil.disk_usage("/")
extra_recursion_spaces = ' ' # if verbose else ''
skip_cache = i.get('skip_cache', False)
force_cache = i.get('force_cache', False)
fake_run = i.get('fake_run', False)
fake_run = i.get(
'fake_run',
False) if 'fake_run' in i else i.get(
'prepare',
False)
if fake_run:
env['MLC_TMP_FAKE_RUN'] = 'yes'
debug_uid = i.get('debug_uid', '')
if debug_uid != '':
r = _update_env(env, 'MLC_TMP_DEBUG_UID', debug_uid)
if r['return'] > 0:
return r
fake_deps = i.get('fake_deps', False)
if fake_deps:
env['MLC_TMP_FAKE_DEPS'] = 'yes'
if str(i.get('skip_sys_utils', '')).lower() in ['true', 'yes']:
env['MLC_SKIP_SYS_UTILS'] = 'yes'
if str(i.get('skip_sudo', '')).lower() in ['true', 'yes']:
env['MLC_TMP_SKIP_SUDO'] = 'yes'
run_state = i.get('run_state', self.run_state)
if not run_state.get('version_info', []):
run_state['version_info'] = []
if run_state.get('parent', '') == '':
run_state['parent'] = None
if fake_deps:
run_state['fake_deps'] = True
# Check verbose and silent
verbose = False
silent = True if str(i.get('silent', '')).lower() in [
'true', 'yes', 'on'] else False
if not silent:
silent = True if str(i.get('s', '')).lower() in [
'true', 'yes', 'on'] else False
if silent:
if 'verbose' in i:
del (i['verbose'])
if 'v' in i:
del (i['v'])
env['MLC_TMP_SILENT'] = 'yes'
run_state['tmp_silent'] = True
if 'verbose' in i:
verbose = i['verbose']
elif 'v' in i:
verbose = i['v']
if verbose:
env['MLC_VERBOSE'] = 'yes'
run_state['tmp_verbose'] = True
logging.getLogger().setLevel(logging.DEBUG)
print_deps = i.get('print_deps', False)
print_versions = i.get('print_versions', False)
print_readme = i.get('print_readme', False)
dump_version_info = i.get('dump_version_info', False)
new_cache_entry = i.get('new', False)
renew = i.get('renew', False)
cmd = i.get('cmd', '')
# Capturing the input command if it is coming from an access function
if not cmd and 'cmd' in i.get('input', ''):
i['cmd'] = i['input']['cmd']
cmd = i['cmd']
debug_script_tags = i.get('debug_script_tags', '')
detected_versions = i.get('detected_versions', {})
ignore_script_error = i.get('ignore_script_error', False)
# Detect current path and record in env for further use in native
# scripts
current_path = os.path.abspath(os.getcwd())
r = _update_env(env, 'MLC_TMP_CURRENT_PATH', current_path)
if r['return'] > 0:
return r
# Check if quiet mode
quiet = i.get(
'quiet',
False) if 'quiet' in i else (
env.get(
'MLC_QUIET',
'').lower() == 'yes')
if quiet:
env['MLC_QUIET'] = 'yes'
skip_remembered_selections = i.get('skip_remembered_selections', False) if 'skip_remembered_selections' in i \
else (env.get('MLC_SKIP_REMEMBERED_SELECTIONS', '').lower() == 'yes')
if skip_remembered_selections:
env['MLC_SKIP_REMEMBERED_SELECTIONS'] = 'yes'
# Prepare debug info
parsed_script = i.get('parsed_artifact')
parsed_script_alias = parsed_script[0][0] if parsed_script is not None else ''
# Get and cache minimal host OS info to be able to run scripts and
# manage OS environment
if len(self.os_info) == 0:
r = get_host_os_info()
# r = self.access({'action': 'get_host_os_info',
# 'automation': 'utils,dc2743f8450541e3'})
if r['return'] > 0:
return r
self.os_info = r['info']
os_info = self.os_info
# Bat extension for this host OS
bat_ext = os_info['bat_ext']
# Add permanent env from OS (such as MLC_WINDOWS:"yes" on Windows)
env_from_os_info = os_info.get('env', {})
if len(env_from_os_info) > 0:
env.update(env_from_os_info)
# take some env from the user environment
keys = [
"GH_TOKEN",
"ftp_proxy",
"FTP_PROXY",
"http_proxy",
"HTTP_PROXY",
"https_proxy",
"HTTPS_PROXY",
"no_proxy",
"NO_PROXY",
"socks_proxy",
"SOCKS_PROXY"]
for key in keys:
if os.environ.get(key, '') != '' and env.get(key, '') == '':
env[key] = os.environ[key]
r = self._update_env_from_input(env, i)
#######################################################################
# Check if we want to skip cache (either by skip_cache or by fake_run)
force_skip_cache = True if skip_cache else False
force_skip_cache = True if fake_run else force_skip_cache
#######################################################################
# Find MLC script(s) based on their tags and variations to get their meta and customize this workflow.
# We will need to decide how to select if more than 1 (such as "get compiler")
#
# Note: this local search function will separate tags and variations
#
# STEP 100 Input: Search sripts by i['tags'] (includes variations starting from _) and/or i['parsed_artifact']
# tags_string = i['tags']
tags_string = i.get('tags', '').strip()
# ii = utils.sub_input(i, self.action_object.cfg['artifact_keys'])
ii = {}
ii['tags'] = tags_string
ii['out'] = None
for key in ["automation", "parsed_automation",
"artifact", "parsed_artifact"]:
if i.get(key):
ii[key] = i[key]
# if cm run script without tags/artifact and with --help
if len(ii.get('parsed_artifact', [])) == 0 and ii.get(
'tags', '') == '' and i.get('help', False):
return utils.call_internal_module(
self, __file__, 'module_help', 'print_help', {'meta': {}, 'path': ''})
r = self.search(ii)
if r['return'] > 0:
return r
# Search function will return
list_of_found_scripts = r['list']
script_tags = r['script_tags']
script_tags_string = ','.join(script_tags)
variation_tags = r['variation_tags']
mlc_script_info = i.get('script_call_prefix', '').strip()
if mlc_script_info == '':
mlc_script_info = 'mlc run script'
if not mlc_script_info.endswith(' '):
mlc_script_info += ' '
x = '--tags='
y = ','
if parsed_script_alias != '':
mlc_script_info += parsed_script_alias
x = '--tags="'
if len(script_tags) > 0 or len(variation_tags) > 0:
mlc_script_info += x
if len(script_tags) > 0:
mlc_script_info += script_tags_string
if len(variation_tags) > 0:
if len(script_tags) > 0:
mlc_script_info += ','
x_variation_tags = ['_' + v for v in variation_tags]
mlc_script_info += y.join(x_variation_tags)
# if verbose:
# logging.info('')
if not run_state.get('tmp_silent', False):
logging.info(recursion_spaces + '* ' + mlc_script_info)
#######################################################################
# Report if scripts were not found or there is an ambiguity with UIDs
if not r['found_scripts']:
return {
'return': 1, 'error': f"""no scripts were found with tags: {tags_string} (when variations ignored)"""}
if len(list_of_found_scripts) == 0:
return {
'return': 16, 'error': f"""no scripts were found with tags: {tags_string} \n {r.get('warning', '')}"""}
# Sometimes there is an ambiguity when someone adds a script
# while duplicating a UID. In such case, we will return >1 script
# and will start searching in the cache ...
# We are detecing such cases here:
if len(list_of_found_scripts) > 1 and script_tags_string == '' and parsed_script_alias != '' and '?' not in parsed_script_alias and '*' not in parsed_script_alias:
x = 'Ambiguity in the following scripts have the same UID - please change that in meta.json or meta.yaml:\n'
for y in list_of_found_scripts:
x += ' * ' + y.path + '\n'
return {'return': 1, 'error': x}
# STEP 100 Output: list_of_found_scripts based on tags (with variations) and/or parsed_artifact
# script_tags [] - contains tags without variations (starting from _ such as _cuda)
# variation_tags [] - contains only variations tags (without _)
# string_tags_string [str] (joined script_tags)
#######################################################################
# Sort scripts for better determinism
list_of_found_scripts = sorted(list_of_found_scripts, key=lambda a: (a.meta.get('sort', 0),
a.path))
logging.debug(recursion_spaces +
' - Number of scripts found: {}'.format(len(list_of_found_scripts)))
# Check if script selection is remembered
if not skip_remembered_selections and len(list_of_found_scripts) > 1:
for selection in remembered_selections:
if selection['type'] == 'script' and set(
selection['tags'].split(',')) == set(script_tags_string.split(',')):
# Leave 1 entry in the found list
list_of_found_scripts = [selection['cached_script']]
logging.debug(
recursion_spaces +
' - Found remembered selection with tags: {}'.format(script_tags_string))
break
# STEP 200 Output: potentially pruned list_of_found_scripts if
# selection of multple scripts was remembered
# STEP 300: If more than one MLC script found (example: "get compiler"),
# first, check if selection was already remembered!
# second, check in cache to prune scripts
# STEP 300 input: lit_of_found_scripts
select_script = 0
# If 1 script found and script_tags == '', pick them from the meta
if script_tags_string == '' and len(list_of_found_scripts) == 1:
script_tags_string = ','.join(
list_of_found_scripts[0].meta.get('tags', []))
# Found 1 or more scripts. Scans cache tags to find at least 1 with
# cache==True
preload_cached_scripts = False
for script in list_of_found_scripts:
if script.meta.get('cache', False) == True or (
script.meta.get('can_force_cache', False) and force_cache):
preload_cached_scripts = True
break
# STEP 300 Output: preload_cached_scripts = True if at least one of the
# list_of_found_scripts must be cached
# STEP 400: If not force_skip_cache and at least one script can be cached, find (preload) related cache entries for found scripts
# STEP 400 input: script_tags and -tmp (to avoid unfinished scripts
# particularly when installation fails)
cache_list = []
if not force_skip_cache and preload_cached_scripts:
cache_tags_without_tmp_string = '-tmp'
if script_tags_string != '':
cache_tags_without_tmp_string += ',' + script_tags_string
if variation_tags:
cache_tags_without_tmp_string += ',_' + \
",_".join(variation_tags)
# variation_tags are prefixed with "_" but the MLC search function knows only tags and so we need to change "_-" to "-_" for excluding any variations
# This change can later be moved to a search function specific to
# cache
cache_tags_without_tmp_string = cache_tags_without_tmp_string.replace(
",_-", ",-_")
logging.debug(
recursion_spaces +
' - Searching for cached script outputs with the following tags: {}'.format(cache_tags_without_tmp_string))
search_cache = {'action': 'find',
'automation': self.meta['deps']['cache'],
'tags': cache_tags_without_tmp_string}
rc = self.action_object.access(search_cache)
if rc['return'] > 0:
return rc
cache_list = rc['list']
logging.debug(
recursion_spaces +
' - Number of cached script outputs found: {}'.format(
len(cache_list)))
# STEP 400 output: cache_list
# STEP 500: At this stage with have cache_list related to either 1 or more scripts (in case of get,compiler)
# If more than 1: Check if in cache and reuse it or ask user to select
# STEP 500 input: list_of_found_scripts
if len(list_of_found_scripts) > 0:
# If only tags are used, check if there are no cached scripts with tags - then we will reuse them
# The use case: mlc run script --tags=get,compiler
# MLC script will always ask to select gcc,llvm,etc even if any of
# them will be already cached
if len(cache_list) > 0:
new_list_of_found_scripts = []
for cache_entry in cache_list:
# Find associated script and add to the
# list_of_found_scripts
associated_script_artifact = cache_entry.meta['associated_script_artifact']
x = associated_script_artifact.find(',')
if x < 0:
return {'return': 1, 'error': 'MLC artifact format is wrong "{}" - no comma found'.format(
associated_script_artifact)}
associated_script_artifact_uid = associated_script_artifact[x + 1:]
cache_entry.meta['associated_script_artifact_uid'] = associated_script_artifact_uid
for script in list_of_found_scripts:
script_uid = script.meta['uid']
if associated_script_artifact_uid == script_uid:
if script not in new_list_of_found_scripts:
new_list_of_found_scripts.append(script)
# Avoid case when all scripts are pruned due to just 1
# variation used
if len(new_list_of_found_scripts) > 0:
list_of_found_scripts = new_list_of_found_scripts
# Select scripts
if len(list_of_found_scripts) > 1:
select_script = select_script_artifact(
list_of_found_scripts,
'script',
recursion_spaces,
False,
script_tags_string,
quiet,
verbose)
# Remember selection
if not skip_remembered_selections:
remembered_selections.append({'type': 'script',
'tags': script_tags_string,
'cached_script': list_of_found_scripts[select_script]})
else:
select_script = 0
# Prune cache list with the selected script
if len(list_of_found_scripts) > 0:
script_artifact_uid = list_of_found_scripts[select_script].meta['uid']
new_cache_list = []
for cache_entry in cache_list:
if cache_entry.meta['associated_script_artifact_uid'] == script_artifact_uid:
new_cache_list.append(cache_entry)
cache_list = new_cache_list
# Here a specific script is found and meta obtained
# Set some useful local variables
script_artifact = list_of_found_scripts[select_script]
# print(list_of_found_scripts)
meta = script_artifact.meta
# print(meta)
path = script_artifact.path
# Check min MLC version requirement
min_mlc_version = meta.get('min_mlc_version', '').strip()
if min_mlc_version != '':
try:
import importlib.metadata
current_mlc_version = importlib.metadata.version("mlc")
comparison = utils.compare_versions(
current_mlc_version, min_mlc_version)
if comparison < 0:
return {'return': 1, 'error': 'This script requires MLC version >= {} while current MLC version is {} - please update using "pip install mlcflow -U"'.format(
min_mlc_version, current_mlc_version)}
except Exception as e:
error = format(e)
# Check path to repo
script_repo_path = script_artifact.repo.path
script_repo_path_with_prefix = script_artifact.repo.path
if script_artifact.repo.meta.get('prefix', '') != '':
script_repo_path_with_prefix = os.path.join(
script_repo_path, script_artifact.repo.meta['prefix'])
env['MLC_TMP_CURRENT_SCRIPT_REPO_PATH'] = script_repo_path
env['MLC_TMP_CURRENT_SCRIPT_REPO_PATH_WITH_PREFIX'] = script_repo_path_with_prefix
# Check if has --help
if i.get('help', False):
return utils.call_internal_module(self, __file__, 'module_help', 'print_help', {
'meta': meta, 'path': path})
run_state['script_id'] = meta['alias'] + "," + meta['uid']
run_state['script_tags'] = script_tags
run_state['script_variation_tags'] = variation_tags
run_state['script_repo_alias'] = script_artifact.repo.meta.get(
'alias', '')
run_state['script_repo_git'] = script_artifact.repo.meta.get(
'git', False)
run_state['cache'] = meta.get('cache', False)
if not recursion:
run_state['script_entry_repo_to_report_errors'] = meta.get(
'repo_to_report_errors', '')
run_state['script_entry_repo_alias'] = script_artifact.repo.meta.get(
'alias', '')
run_state['script_entry_repo_git'] = script_artifact.repo.meta.get(
'git', False)
deps = meta.get('deps', [])
post_deps = meta.get('post_deps', [])
prehook_deps = meta.get('prehook_deps', [])
posthook_deps = meta.get('posthook_deps', [])
input_mapping = meta.get('input_mapping', {})
docker_settings = meta.get('docker')
docker_input_mapping = {}
if docker_settings:
docker_input_mapping = docker_settings.get(
'docker_input_mapping', {})
new_env_keys_from_meta = meta.get('new_env_keys', [])
new_state_keys_from_meta = meta.get('new_state_keys', [])
found_script_artifact = utils.assemble_object(
meta['alias'], meta['uid'])
found_script_tags = meta.get('tags', [])
if i.get('debug_script', False):
debug_script_tags = ','.join(found_script_tags)
logging.debug(recursion_spaces +
' - Found script::{} in {}'.format(found_script_artifact, path))
# STEP 500 output: script_artifact - unique selected script artifact
# (cache_list) pruned for the unique script if cache is used
# meta - script meta
# path - script path
# found_script_tags [] - all tags of the found script
# HERE WE HAVE ORIGINAL ENV
# STEP 600: Continue updating env
# Add default env from meta to new env if not empty
# (env NO OVERWRITE)
script_artifact_default_env = meta.get('default_env', {})
for key in script_artifact_default_env:
env.setdefault(key, script_artifact_default_env[key])
# Force env from meta['env'] as a CONST
# (env OVERWRITE)
script_artifact_env = meta.get('env', {})
# print(f"script meta env= {script_artifact_env}")
env.update(script_artifact_env)
# print(f"env = {env}")
script_artifact_state = meta.get('state', {})
utils.merge_dicts({'dict1': state,
'dict2': script_artifact_state,
'append_lists': True,
'append_unique': True})
# Store the default_version in run_state -> may be overridden by
# variations
default_version = meta.get(
'default_version',
'') # not used if version is given
run_state['default_version'] = default_version
# STEP 700: Overwrite env with keys from the script input (to allow user friendly CLI)
# IT HAS THE PRIORITY OVER meta['default_env'] and meta['env'] but not over the meta from versions/variations
# (env OVERWRITE - user enforces it from CLI)
# (it becomes const)
if input_mapping:
update_env_from_input_mapping(env, i, input_mapping)
update_env_from_input_mapping(const, i, input_mapping)
# This mapping is done in module_misc
# if docker_input_mapping:
# update_env_from_input_mapping(env, i, docker_input_mapping)
# update_env_from_input_mapping(const, i, docker_input_mapping)
# Update env/state with cost
env.update(const)
utils.merge_dicts({'dict1': state,
'dict2': const_state,
'append_lists': True,
'append_unique': True})
# STEP 800: Process variations and update env (overwrite from env and update form default_env)
# VARIATIONS HAS THE PRIORITY OVER
# MULTIPLE VARIATIONS (THAT CAN BE TURNED ON AT THE SAME TIME) SHOULD
# NOT HAVE CONFLICTING ENV
# VARIATIONS OVERWRITE current ENV but not input keys (they become
# const)
variations = script_artifact.meta.get('variations', {})
state['docker'] = meta.get('docker', {})
r = self._update_state_from_variations(
i,
meta,
variation_tags,
variations,
env,
state,
const,
const_state,
deps,
post_deps,
prehook_deps,
posthook_deps,
new_env_keys_from_meta,
new_state_keys_from_meta,
add_deps_recursive,
run_state,
recursion_spaces,
verbose)
if r['return'] > 0:
return r
warnings = meta.get('warnings', [])
if len(r.get('warnings', [])) > 0:
warnings += r['warnings']
variation_tags_string = r['variation_tags_string']
explicit_variation_tags = r['explicit_variation_tags']
# USE CASE:
# HERE we may have versions in script input and env['MLC_VERSION_*']
# STEP 900: Get version, min, max, usable from env (priority if passed from another script to force version),
# then script input, then script meta
# VERSIONS SHOULD NOT BE USED INSIDE VARIATIONS (in meta)!
# First, take version from input
version = i.get('version', '').strip()
version_min = i.get('version_min', '').strip()
version_max = i.get('version_max', '').strip()
version_max_usable = i.get('version_max_usable', '').strip()
# Second, take from env
if version == '':
version = env.get('MLC_VERSION', '')
if version_min == '':
version_min = env.get('MLC_VERSION_MIN', '')
if version_max == '':
version_max = env.get('MLC_VERSION_MAX', '')
if version_max_usable == '':
version_max_usable = env.get(
'MLC_VERSION_MAX_USABLE', '')
# Third, take from meta
if version == '':
version = meta.get('version', '')
if version_min == '':
version_min = meta.get('version_min', '')
if version_max == '':
version_max = meta.get('version_max', '')
if version_max_usable == '':
version_max_usable = meta.get(
'version_max_usable', '')
# Update env with resolved versions
notes = []
for version_index in [(version, 'MLC_VERSION', ' == {}'),
(version_min, 'MLC_VERSION_MIN', ' >= {}'),
(version_max, 'MLC_VERSION_MAX', ' <= {}'),
(version_max_usable, 'MLC_VERSION_MAX_USABLE', '({})')]:
version_value = version_index[0]
key = version_index[1]
note = version_index[2]
if version_value != '':
env[key] = version_value
notes.append(note.format(version_value))
# elif key in env:
# # If version_X is "", remove related key from ENV ...
# del(env[key])
if len(notes) > 0:
logging.debug(
recursion_spaces +
' - Requested version: ' +
' '.join(notes))
# STEP 900 output: version* set