forked from mlflow/mlflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_fluent.py
903 lines (756 loc) · 31.2 KB
/
test_fluent.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
from collections import defaultdict
from importlib import reload
from mlflow.store.tracking import SEARCH_MAX_RESULTS_DEFAULT
import os
import random
import uuid
import inspect
import time
import pytest
from unittest import mock
import mlflow
import mlflow.tracking.context.registry
import mlflow.tracking.fluent
from mlflow.entities import (
LifecycleStage,
Metric,
Param,
Run,
RunData,
RunInfo,
RunStatus,
RunTag,
SourceType,
ViewType,
)
from mlflow.exceptions import MlflowException
from mlflow.store.entities.paged_list import PagedList
from mlflow.store.tracking.dbmodels.models import SqlExperiment
from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore
from mlflow.tracking.client import MlflowClient
from mlflow.tracking.fluent import (
_EXPERIMENT_ID_ENV_VAR,
_EXPERIMENT_NAME_ENV_VAR,
_RUN_ID_ENV_VAR,
_get_experiment_id,
_get_experiment_id_from_env,
_paginate,
search_runs,
set_experiment,
start_run,
get_run,
)
from mlflow.utils import mlflow_tags
from mlflow.utils.file_utils import TempDir
from tests.tracking.integration_test_utils import _init_server
from tests.helper_functions import multi_context
class HelperEnv:
def __init__(self):
pass
@classmethod
def assert_values(cls, exp_id, name):
assert os.environ.get(_EXPERIMENT_NAME_ENV_VAR) == name
assert os.environ.get(_EXPERIMENT_ID_ENV_VAR) == exp_id
@classmethod
def set_values(cls, experiment_id=None, name=None):
if experiment_id:
os.environ[_EXPERIMENT_ID_ENV_VAR] = str(experiment_id)
elif os.environ.get(_EXPERIMENT_ID_ENV_VAR):
del os.environ[_EXPERIMENT_ID_ENV_VAR]
if name:
os.environ[_EXPERIMENT_NAME_ENV_VAR] = str(name)
elif os.environ.get(_EXPERIMENT_NAME_ENV_VAR):
del os.environ[_EXPERIMENT_NAME_ENV_VAR]
def create_run(
run_id="",
exp_id="",
uid="",
start=0,
end=0,
metrics=None,
params=None,
tags=None,
status=RunStatus.FINISHED,
a_uri=None,
):
return Run(
RunInfo(
run_uuid=run_id,
run_id=run_id,
experiment_id=exp_id,
user_id=uid,
status=status,
start_time=start,
end_time=end,
lifecycle_stage=LifecycleStage.ACTIVE,
artifact_uri=a_uri,
),
RunData(metrics=metrics, params=params, tags=tags),
)
@pytest.fixture(autouse=True)
def reset_experiment_id():
"""
This fixture resets the active experiment id *after* the execution of the test case in which
its included
"""
yield
HelperEnv.set_values()
mlflow.tracking.fluent._active_experiment_id = None
@pytest.fixture(autouse=True)
def reload_context_registry():
"""Reload the context registry module to clear caches."""
reload(mlflow.tracking.context.registry)
@pytest.fixture(params=["list", "pandas"])
def search_runs_output_format(request):
if "MLFLOW_SKINNY" in os.environ and request.param == "pandas":
pytest.skip("pandas output_format is not supported with skinny client")
return request.param
def test_all_fluent_apis_are_included_in_dunder_all():
def _is_function_or_class(obj):
return callable(obj) or inspect.isclass(obj)
apis = [
a
for a in dir(mlflow)
if _is_function_or_class(getattr(mlflow, a)) and not a.startswith("_")
]
assert set(apis).issubset(set(mlflow.__all__))
def test_get_experiment_id_from_env():
# When no env variables are set
HelperEnv.assert_values(None, None)
assert _get_experiment_id_from_env() is None
# set only ID
random_id = random.randint(1, 1e6)
HelperEnv.set_values(experiment_id=random_id)
HelperEnv.assert_values(str(random_id), None)
assert _get_experiment_id_from_env() == str(random_id)
# set only name
with TempDir(chdr=True):
name = "random experiment %d" % random.randint(1, 1e6)
exp_id = mlflow.create_experiment(name)
assert exp_id is not None
HelperEnv.set_values(name=name)
HelperEnv.assert_values(None, name)
assert _get_experiment_id_from_env() == exp_id
# set both: assert that name variable takes precedence
with TempDir(chdr=True):
name = "random experiment %d" % random.randint(1, 1e6)
exp_id = mlflow.create_experiment(name)
assert exp_id is not None
random_id = random.randint(1, 1e6)
HelperEnv.set_values(name=name, experiment_id=random_id)
HelperEnv.assert_values(str(random_id), name)
assert _get_experiment_id_from_env() == exp_id
def test_get_experiment_id_with_active_experiment_returns_active_experiment_id():
# Create a new experiment and set that as active experiment
with TempDir(chdr=True):
name = "Random experiment %d" % random.randint(1, 1e6)
exp_id = mlflow.create_experiment(name)
assert exp_id is not None
mlflow.set_experiment(name)
assert _get_experiment_id() == exp_id
def test_get_experiment_id_with_no_active_experiments_returns_zero():
assert _get_experiment_id() == "0"
def test_get_experiment_id_in_databricks_detects_notebook_id_by_default():
notebook_id = 768
with mock.patch(
"mlflow.tracking.fluent.is_in_databricks_notebook"
) as notebook_detection_mock, mock.patch(
"mlflow.tracking.fluent.get_notebook_id"
) as notebook_id_mock:
notebook_detection_mock.return_value = True
notebook_id_mock.return_value = notebook_id
assert _get_experiment_id() == notebook_id
def test_get_experiment_id_in_databricks_with_active_experiment_returns_active_experiment_id():
with TempDir(chdr=True):
exp_name = "random experiment %d" % random.randint(1, 1e6)
exp_id = mlflow.create_experiment(exp_name)
mlflow.set_experiment(exp_name)
notebook_id = str(int(exp_id) + 73)
with mock.patch(
"mlflow.tracking.fluent.is_in_databricks_notebook"
) as notebook_detection_mock, mock.patch(
"mlflow.tracking.fluent.get_notebook_id"
) as notebook_id_mock:
notebook_detection_mock.return_value = True
notebook_id_mock.return_value = notebook_id
assert _get_experiment_id() != notebook_id
assert _get_experiment_id() == exp_id
def test_get_experiment_id_in_databricks_with_experiment_defined_in_env_returns_env_experiment_id():
with TempDir(chdr=True):
exp_name = "random experiment %d" % random.randint(1, 1e6)
exp_id = mlflow.create_experiment(exp_name)
notebook_id = str(int(exp_id) + 73)
HelperEnv.set_values(experiment_id=exp_id)
with mock.patch(
"mlflow.tracking.fluent.is_in_databricks_notebook"
) as notebook_detection_mock, mock.patch(
"mlflow.tracking.fluent.get_notebook_id"
) as notebook_id_mock:
notebook_detection_mock.side_effect = lambda *args, **kwargs: True
notebook_id_mock.side_effect = lambda *args, **kwargs: notebook_id
assert _get_experiment_id() != notebook_id
assert _get_experiment_id() == exp_id
def test_get_experiment_by_id():
with TempDir(chdr=True):
name = "Random experiment %d" % random.randint(1, 1e6)
exp_id = mlflow.create_experiment(name)
experiment = mlflow.get_experiment(exp_id)
print(experiment)
assert experiment.experiment_id == exp_id
def test_get_experiment_by_name():
with TempDir(chdr=True):
name = "Random experiment %d" % random.randint(1, 1e6)
exp_id = mlflow.create_experiment(name)
experiment = mlflow.get_experiment_by_name(name)
assert experiment.experiment_id == exp_id
@pytest.mark.parametrize("view_type", [ViewType.ACTIVE_ONLY, ViewType.DELETED_ONLY, ViewType.ALL])
def test_list_experiments(view_type, tmpdir):
sqlite_uri = "sqlite:///" + os.path.join(tmpdir.strpath, "test.db")
store = SqlAlchemyStore(sqlite_uri, default_artifact_root=tmpdir.strpath)
num_experiments = SEARCH_MAX_RESULTS_DEFAULT + 1
if view_type == ViewType.DELETED_ONLY:
# Delete the default experiment
mlflow.tracking.MlflowClient(sqlite_uri).delete_experiment("0")
# This is a bit hacky but much faster than creating experiments one by one with
# `mlflow.create_experiment`
with store.ManagedSessionMaker() as session:
lifecycle_stages = LifecycleStage.view_type_to_stages(view_type)
experiments = [
SqlExperiment(
name=f"exp_{i + 1}",
lifecycle_stage=random.choice(lifecycle_stages),
artifact_location=tmpdir.strpath,
)
for i in range(num_experiments - 1)
]
session.add_all(experiments)
try:
url, process = _init_server(sqlite_uri, root_artifact_uri=tmpdir.strpath)
mlflow.set_tracking_uri(url)
# `max_results` is unspecified
assert len(mlflow.list_experiments(view_type)) == num_experiments
# `max_results` is larger than the number of experiments in the database
assert len(mlflow.list_experiments(view_type, num_experiments + 1)) == num_experiments
# `max_results` is equal to the number of experiments in the database
assert len(mlflow.list_experiments(view_type, num_experiments)) == num_experiments
# `max_results` is smaller than the number of experiments in the database
assert len(mlflow.list_experiments(view_type, num_experiments - 1)) == num_experiments - 1
finally:
process.terminate()
@pytest.fixture
def empty_active_run_stack():
with mock.patch("mlflow.tracking.fluent._active_run_stack", []):
yield
def is_from_run(active_run, run):
return active_run.info == run.info and active_run.data == run.data
def test_start_run_defaults(empty_active_run_stack): # pylint: disable=unused-argument
mock_experiment_id = mock.Mock()
experiment_id_patch = mock.patch(
"mlflow.tracking.fluent._get_experiment_id", return_value=mock_experiment_id
)
databricks_notebook_patch = mock.patch(
"mlflow.tracking.fluent.is_in_databricks_notebook", return_value=False
)
mock_user = mock.Mock()
user_patch = mock.patch(
"mlflow.tracking.context.default_context._get_user", return_value=mock_user
)
mock_source_name = mock.Mock()
source_name_patch = mock.patch(
"mlflow.tracking.context.default_context._get_source_name", return_value=mock_source_name
)
source_type_patch = mock.patch(
"mlflow.tracking.context.default_context._get_source_type", return_value=SourceType.NOTEBOOK
)
mock_source_version = mock.Mock()
source_version_patch = mock.patch(
"mlflow.tracking.context.git_context._get_source_version", return_value=mock_source_version
)
expected_tags = {
mlflow_tags.MLFLOW_USER: mock_user,
mlflow_tags.MLFLOW_SOURCE_NAME: mock_source_name,
mlflow_tags.MLFLOW_SOURCE_TYPE: SourceType.to_string(SourceType.NOTEBOOK),
mlflow_tags.MLFLOW_GIT_COMMIT: mock_source_version,
}
create_run_patch = mock.patch.object(MlflowClient, "create_run")
with multi_context(
experiment_id_patch,
databricks_notebook_patch,
user_patch,
source_name_patch,
source_type_patch,
source_version_patch,
create_run_patch,
):
active_run = start_run()
MlflowClient.create_run.assert_called_once_with(
experiment_id=mock_experiment_id, tags=expected_tags
)
assert is_from_run(active_run, MlflowClient.create_run.return_value)
def test_start_run_defaults_databricks_notebook(
empty_active_run_stack,
): # pylint: disable=unused-argument
mock_experiment_id = mock.Mock()
experiment_id_patch = mock.patch(
"mlflow.tracking.fluent._get_experiment_id", return_value=mock_experiment_id
)
databricks_notebook_patch = mock.patch(
"mlflow.utils.databricks_utils.is_in_databricks_notebook", return_value=True
)
mock_user = mock.Mock()
user_patch = mock.patch(
"mlflow.tracking.context.default_context._get_user", return_value=mock_user
)
mock_source_version = mock.Mock()
source_version_patch = mock.patch(
"mlflow.tracking.context.git_context._get_source_version", return_value=mock_source_version
)
mock_notebook_id = mock.Mock()
notebook_id_patch = mock.patch(
"mlflow.utils.databricks_utils.get_notebook_id", return_value=mock_notebook_id
)
mock_notebook_path = mock.Mock()
notebook_path_patch = mock.patch(
"mlflow.utils.databricks_utils.get_notebook_path", return_value=mock_notebook_path
)
mock_webapp_url = mock.Mock()
webapp_url_patch = mock.patch(
"mlflow.utils.databricks_utils.get_webapp_url", return_value=mock_webapp_url
)
workspace_info_patch = mock.patch(
"mlflow.utils.databricks_utils.get_workspace_info_from_dbutils",
return_value=("https://databricks.com", "123456"),
)
expected_tags = {
mlflow_tags.MLFLOW_USER: mock_user,
mlflow_tags.MLFLOW_SOURCE_NAME: mock_notebook_path,
mlflow_tags.MLFLOW_SOURCE_TYPE: SourceType.to_string(SourceType.NOTEBOOK),
mlflow_tags.MLFLOW_GIT_COMMIT: mock_source_version,
mlflow_tags.MLFLOW_DATABRICKS_NOTEBOOK_ID: mock_notebook_id,
mlflow_tags.MLFLOW_DATABRICKS_NOTEBOOK_PATH: mock_notebook_path,
mlflow_tags.MLFLOW_DATABRICKS_WEBAPP_URL: mock_webapp_url,
mlflow_tags.MLFLOW_DATABRICKS_WORKSPACE_URL: "https://databricks.com",
mlflow_tags.MLFLOW_DATABRICKS_WORKSPACE_ID: "123456",
}
create_run_patch = mock.patch.object(MlflowClient, "create_run")
with multi_context(
experiment_id_patch,
databricks_notebook_patch,
user_patch,
source_version_patch,
notebook_id_patch,
notebook_path_patch,
webapp_url_patch,
workspace_info_patch,
create_run_patch,
):
active_run = start_run()
MlflowClient.create_run.assert_called_once_with(
experiment_id=mock_experiment_id, tags=expected_tags
)
assert is_from_run(active_run, MlflowClient.create_run.return_value)
@pytest.mark.usefixtures(empty_active_run_stack.__name__)
def test_start_run_creates_new_run_with_user_specified_tags():
mock_experiment_id = mock.Mock()
experiment_id_patch = mock.patch(
"mlflow.tracking.fluent._get_experiment_id", return_value=mock_experiment_id
)
databricks_notebook_patch = mock.patch(
"mlflow.tracking.fluent.is_in_databricks_notebook", return_value=False
)
mock_user = mock.Mock()
user_patch = mock.patch(
"mlflow.tracking.context.default_context._get_user", return_value=mock_user
)
mock_source_name = mock.Mock()
source_name_patch = mock.patch(
"mlflow.tracking.context.default_context._get_source_name", return_value=mock_source_name
)
source_type_patch = mock.patch(
"mlflow.tracking.context.default_context._get_source_type", return_value=SourceType.NOTEBOOK
)
mock_source_version = mock.Mock()
source_version_patch = mock.patch(
"mlflow.tracking.context.git_context._get_source_version", return_value=mock_source_version
)
user_specified_tags = {
"ml_task": "regression",
"num_layers": 7,
mlflow_tags.MLFLOW_USER: "user_override",
}
expected_tags = {
mlflow_tags.MLFLOW_SOURCE_NAME: mock_source_name,
mlflow_tags.MLFLOW_SOURCE_TYPE: SourceType.to_string(SourceType.NOTEBOOK),
mlflow_tags.MLFLOW_GIT_COMMIT: mock_source_version,
mlflow_tags.MLFLOW_USER: "user_override",
"ml_task": "regression",
"num_layers": 7,
}
create_run_patch = mock.patch.object(MlflowClient, "create_run")
with multi_context(
experiment_id_patch,
databricks_notebook_patch,
user_patch,
source_name_patch,
source_type_patch,
source_version_patch,
create_run_patch,
):
active_run = start_run(tags=user_specified_tags)
MlflowClient.create_run.assert_called_once_with(
experiment_id=mock_experiment_id, tags=expected_tags
)
assert is_from_run(active_run, MlflowClient.create_run.return_value)
@pytest.mark.usefixtures(empty_active_run_stack.__name__)
def test_start_run_resumes_existing_run_and_sets_user_specified_tags():
tags_to_set = {
"A": "B",
"C": "D",
}
run_id = mlflow.start_run().info.run_id
mlflow.end_run()
restarted_run = mlflow.start_run(run_id, tags=tags_to_set)
assert tags_to_set.items() <= restarted_run.data.tags.items()
def test_start_run_with_parent():
parent_run = mock.Mock()
mock_experiment_id = mock.Mock()
mock_source_name = mock.Mock()
active_run_stack_patch = mock.patch("mlflow.tracking.fluent._active_run_stack", [parent_run])
databricks_notebook_patch = mock.patch(
"mlflow.tracking.fluent.is_in_databricks_notebook", return_value=False
)
mock_user = mock.Mock()
user_patch = mock.patch(
"mlflow.tracking.context.default_context._get_user", return_value=mock_user
)
source_name_patch = mock.patch(
"mlflow.tracking.context.default_context._get_source_name", return_value=mock_source_name
)
expected_tags = {
mlflow_tags.MLFLOW_USER: mock_user,
mlflow_tags.MLFLOW_SOURCE_NAME: mock_source_name,
mlflow_tags.MLFLOW_SOURCE_TYPE: SourceType.to_string(SourceType.LOCAL),
mlflow_tags.MLFLOW_PARENT_RUN_ID: parent_run.info.run_id,
}
create_run_patch = mock.patch.object(MlflowClient, "create_run")
with multi_context(
databricks_notebook_patch,
active_run_stack_patch,
create_run_patch,
user_patch,
source_name_patch,
):
active_run = start_run(experiment_id=mock_experiment_id, nested=True)
MlflowClient.create_run.assert_called_once_with(
experiment_id=mock_experiment_id, tags=expected_tags
)
assert is_from_run(active_run, MlflowClient.create_run.return_value)
def test_start_run_with_parent_non_nested():
with mock.patch("mlflow.tracking.fluent._active_run_stack", [mock.Mock()]):
with pytest.raises(Exception, match=r"Run with UUID .+ is already active"):
start_run()
def test_start_run_existing_run(empty_active_run_stack): # pylint: disable=unused-argument
mock_run = mock.Mock()
mock_run.info.lifecycle_stage = LifecycleStage.ACTIVE
run_id = uuid.uuid4().hex
mock_get_store = mock.patch("mlflow.tracking.fluent._get_store")
with mock_get_store, mock.patch.object(MlflowClient, "get_run", return_value=mock_run):
active_run = start_run(run_id)
assert is_from_run(active_run, mock_run)
MlflowClient.get_run.assert_called_with(run_id)
def test_start_run_existing_run_from_environment(
empty_active_run_stack,
): # pylint: disable=unused-argument
mock_run = mock.Mock()
mock_run.info.lifecycle_stage = LifecycleStage.ACTIVE
run_id = uuid.uuid4().hex
env_patch = mock.patch.dict("os.environ", {_RUN_ID_ENV_VAR: run_id})
mock_get_store = mock.patch("mlflow.tracking.fluent._get_store")
with env_patch, mock_get_store, mock.patch.object(
MlflowClient, "get_run", return_value=mock_run
):
active_run = start_run()
assert is_from_run(active_run, mock_run)
MlflowClient.get_run.assert_called_with(run_id)
def test_start_run_existing_run_from_environment_with_set_environment(
empty_active_run_stack,
): # pylint: disable=unused-argument
mock_run = mock.Mock()
mock_run.info.lifecycle_stage = LifecycleStage.ACTIVE
run_id = uuid.uuid4().hex
env_patch = mock.patch.dict("os.environ", {_RUN_ID_ENV_VAR: run_id})
with env_patch, mock.patch.object(MlflowClient, "get_run", return_value=mock_run):
with pytest.raises(
MlflowException, match="active run ID does not match environment run ID"
):
set_experiment("test-run")
start_run()
def test_start_run_existing_run_deleted(empty_active_run_stack): # pylint: disable=unused-argument
mock_run = mock.Mock()
mock_run.info.lifecycle_stage = LifecycleStage.DELETED
run_id = uuid.uuid4().hex
match = f"Cannot start run with ID {run_id} because it is in the deleted state"
with mock.patch.object(MlflowClient, "get_run", return_value=mock_run):
with pytest.raises(MlflowException, match=match):
start_run(run_id)
def test_start_existing_run_status(empty_active_run_stack): # pylint: disable=unused-argument
run_id = mlflow.start_run().info.run_id
mlflow.end_run()
assert MlflowClient().get_run(run_id).info.status == RunStatus.to_string(RunStatus.FINISHED)
restarted_run = mlflow.start_run(run_id)
assert restarted_run.info.status == RunStatus.to_string(RunStatus.RUNNING)
def test_start_existing_run_end_time(empty_active_run_stack): # pylint: disable=unused-argument
run_id = mlflow.start_run().info.run_id
mlflow.end_run()
run_obj_info = MlflowClient().get_run(run_id).info
old_end = run_obj_info.end_time
assert run_obj_info.status == RunStatus.to_string(RunStatus.FINISHED)
mlflow.start_run(run_id)
mlflow.end_run()
run_obj_info = MlflowClient().get_run(run_id).info
assert run_obj_info.end_time > old_end
def test_get_run():
run_id = uuid.uuid4().hex
mock_run = mock.Mock()
mock_run.info.user_id = "my_user_id"
with mock.patch.object(MlflowClient, "get_run", return_value=mock_run):
run = get_run(run_id)
assert run.info.user_id == "my_user_id"
def validate_search_runs(results, data, output_format):
if output_format == "list":
result_data = defaultdict(list)
for run in results:
result_data["status"].append(run.info.status)
result_data["artifact_uri"].append(run.info.artifact_uri)
result_data["experiment_id"].append(run.info.experiment_id)
result_data["run_id"].append(run.info.run_id)
result_data["start_time"].append(run.info.start_time)
result_data["end_time"].append(run.info.end_time)
assert result_data == data
elif output_format == "pandas":
import pandas as pd
expected_df = pd.DataFrame(data)
pd.testing.assert_frame_equal(results, expected_df, check_like=True, check_frame_type=False)
else:
raise Exception("Invalid output format %s" % output_format)
def get_search_runs_timestamp(output_format):
if output_format == "list":
return time.time()
elif output_format == "pandas":
import pandas as pd
return pd.to_datetime(0, utc=True)
else:
raise Exception("Invalid output format %s" % output_format)
def test_search_runs_attributes(search_runs_output_format):
start_times = [
get_search_runs_timestamp(search_runs_output_format),
get_search_runs_timestamp(search_runs_output_format),
]
end_times = [
get_search_runs_timestamp(search_runs_output_format),
get_search_runs_timestamp(search_runs_output_format),
]
runs = [
create_run(
status=RunStatus.FINISHED,
a_uri="dbfs:/test",
run_id="abc",
exp_id="123",
start=start_times[0],
end=end_times[0],
),
create_run(
status=RunStatus.SCHEDULED,
a_uri="dbfs:/test2",
run_id="def",
exp_id="321",
start=start_times[1],
end=end_times[1],
),
]
with mock.patch("mlflow.tracking.fluent._paginate", return_value=runs):
pdf = search_runs(output_format=search_runs_output_format)
data = {
"status": [RunStatus.FINISHED, RunStatus.SCHEDULED],
"artifact_uri": ["dbfs:/test", "dbfs:/test2"],
"run_id": ["abc", "def"],
"experiment_id": ["123", "321"],
"start_time": start_times,
"end_time": end_times,
}
validate_search_runs(pdf, data, search_runs_output_format)
@pytest.mark.skipif(
"MLFLOW_SKINNY" in os.environ,
reason="Skinny client does not support the np or pandas dependencies",
)
def test_search_runs_data():
import numpy as np
import pandas as pd
runs = [
create_run(
metrics=[Metric("mse", 0.2, 0, 0)],
params=[Param("param", "value")],
tags=[RunTag("tag", "value")],
start=1564675200000,
end=1564683035000,
),
create_run(
metrics=[Metric("mse", 0.6, 0, 0), Metric("loss", 1.2, 0, 5)],
params=[Param("param2", "val"), Param("k", "v")],
tags=[RunTag("tag2", "v2")],
start=1564765200000,
end=1564783200000,
),
]
with mock.patch("mlflow.tracking.fluent._paginate", return_value=runs):
pdf = search_runs()
data = {
"status": [RunStatus.FINISHED] * 2,
"artifact_uri": [None] * 2,
"run_id": [""] * 2,
"experiment_id": [""] * 2,
"metrics.mse": [0.2, 0.6],
"metrics.loss": [np.nan, 1.2],
"params.param": ["value", None],
"params.param2": [None, "val"],
"params.k": [None, "v"],
"tags.tag": ["value", None],
"tags.tag2": [None, "v2"],
"start_time": [
pd.to_datetime(1564675200000, unit="ms", utc=True),
pd.to_datetime(1564765200000, unit="ms", utc=True),
],
"end_time": [
pd.to_datetime(1564683035000, unit="ms", utc=True),
pd.to_datetime(1564783200000, unit="ms", utc=True),
],
}
validate_search_runs(pdf, data, "pandas")
def test_search_runs_no_arguments(search_runs_output_format):
"""
When no experiment ID is specified, it should try to get the implicit one.
"""
mock_experiment_id = mock.Mock()
experiment_id_patch = mock.patch(
"mlflow.tracking.fluent._get_experiment_id", return_value=mock_experiment_id
)
get_paginated_runs_patch = mock.patch("mlflow.tracking.fluent._paginate", return_value=[])
with experiment_id_patch, get_paginated_runs_patch:
search_runs(output_format=search_runs_output_format)
mlflow.tracking.fluent._paginate.assert_called_once()
mlflow.tracking.fluent._get_experiment_id.assert_called_once()
def test_paginate_lt_maxresults_onepage():
"""
Number of runs is less than max_results and fits on one page,
so we only need to fetch one page.
"""
runs = [create_run() for _ in range(5)]
tokenized_runs = PagedList(runs, "")
max_results = 50
max_per_page = 10
mocked_lambda = mock.Mock(return_value=tokenized_runs)
paginated_runs = _paginate(mocked_lambda, max_per_page, max_results)
mocked_lambda.assert_called_once()
assert len(paginated_runs) == 5
def test_paginate_lt_maxresults_multipage():
"""
Number of runs is less than max_results, but multiple pages are necessary to get all runs
"""
tokenized_runs = PagedList([create_run() for _ in range(10)], "token")
no_token_runs = PagedList([create_run()], "")
max_results = 50
max_per_page = 10
mocked_lambda = mock.Mock(side_effect=[tokenized_runs, tokenized_runs, no_token_runs])
TOTAL_RUNS = 21
paginated_runs = _paginate(mocked_lambda, max_per_page, max_results)
assert len(paginated_runs) == TOTAL_RUNS
def test_paginate_lt_maxresults_onepage_nonetoken():
"""
Number of runs is less than max_results and fits on one page.
The token passed back on the last page is None, not the emptystring
"""
runs = [create_run() for _ in range(5)]
tokenized_runs = PagedList(runs, None)
max_results = 50
max_per_page = 10
mocked_lambda = mock.Mock(return_value=tokenized_runs)
paginated_runs = _paginate(mocked_lambda, max_per_page, max_results)
mocked_lambda.assert_called_once()
assert len(paginated_runs) == 5
def test_paginate_eq_maxresults_blanktoken():
"""
Runs returned are equal to max_results which are equal to a full number of pages.
The server might send a token back, or they might not (depending on if they know if
more runs exist). In this example, no token is sent back.
Expected behavior is to NOT query for more pages.
"""
# runs returned equal to max_results, blank token
runs = [create_run() for _ in range(10)]
tokenized_runs = PagedList(runs, "")
no_token_runs = PagedList([], "")
max_results = 10
max_per_page = 10
mocked_lambda = mock.Mock(side_effect=[tokenized_runs, no_token_runs])
paginated_runs = _paginate(mocked_lambda, max_per_page, max_results)
mocked_lambda.assert_called_once()
assert len(paginated_runs) == 10
def test_paginate_eq_maxresults_token():
"""
Runs returned are equal to max_results which are equal to a full number of pages.
The server might send a token back, or they might not (depending on if they know if
more runs exist). In this example, a token IS sent back.
Expected behavior is to NOT query for more pages.
"""
runs = [create_run() for _ in range(10)]
tokenized_runs = PagedList(runs, "abc")
blank_runs = PagedList([], "")
max_results = 10
max_per_page = 10
mocked_lambda = mock.Mock(side_effect=[tokenized_runs, blank_runs])
paginated_runs = _paginate(mocked_lambda, max_per_page, max_results)
mocked_lambda.assert_called_once()
assert len(paginated_runs) == 10
def test_paginate_gt_maxresults_multipage():
"""
Number of runs that fit search criteria is greater than max_results. Multiple pages expected.
Expected to only get max_results number of results back.
"""
# should ask for and return the correct number of max_results
full_page_runs = PagedList([create_run() for _ in range(8)], "abc")
partial_page = PagedList([create_run() for _ in range(4)], "def")
max_results = 20
max_per_page = 8
mocked_lambda = mock.Mock(side_effect=[full_page_runs, full_page_runs, partial_page])
paginated_runs = _paginate(mocked_lambda, max_per_page, max_results)
calls = [mock.call(8, None), mock.call(8, "abc"), mock.call(20 % 8, "abc")]
mocked_lambda.assert_has_calls(calls)
assert len(paginated_runs) == 20
def test_paginate_gt_maxresults_onepage():
"""
Number of runs that fit search criteria is greater than max_results. Only one page expected.
Expected to only get max_results number of results back.
"""
runs = [create_run() for _ in range(10)]
tokenized_runs = PagedList(runs, "abc")
max_results = 10
max_per_page = 20
mocked_lambda = mock.Mock(return_value=tokenized_runs)
paginated_runs = _paginate(mocked_lambda, max_per_page, max_results)
mocked_lambda.assert_called_once_with(max_results, None)
assert len(paginated_runs) == 10
def test_delete_tag():
"""
Confirm that fluent API delete tags actually works
:return:
"""
mlflow.set_tag("a", "b")
run = MlflowClient().get_run(mlflow.active_run().info.run_id)
assert "a" in run.data.tags
mlflow.delete_tag("a")
run = MlflowClient().get_run(mlflow.active_run().info.run_id)
assert "a" not in run.data.tags
with pytest.raises(MlflowException, match="No tag with name"):
mlflow.delete_tag("a")
with pytest.raises(MlflowException, match="No tag with name"):
mlflow.delete_tag("b")
mlflow.end_run()