-
Notifications
You must be signed in to change notification settings - Fork 4k
/
client.py
2792 lines (2255 loc) · 112 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Internal package providing a Python CRUD interface to MLflow experiments, runs, registered models,
and model versions. This is a lower level API than the :py:mod:`mlflow.tracking.fluent` module,
and is exposed in the :py:mod:`mlflow.tracking` module.
"""
import contextlib
import logging
import json
import os
import posixpath
import sys
import tempfile
import yaml
from typing import Any, Dict, Sequence, List, Optional, Union, TYPE_CHECKING
from mlflow.entities import Experiment, Run, RunInfo, Param, Metric, RunTag, FileInfo, ViewType
from mlflow.store.entities.paged_list import PagedList
from mlflow.entities.model_registry import RegisteredModel, ModelVersion
from mlflow.entities.model_registry.model_version_stages import ALL_STAGES
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import FEATURE_DISABLED
from mlflow.store.model_registry import SEARCH_REGISTERED_MODEL_MAX_RESULTS_DEFAULT
from mlflow.store.tracking import SEARCH_MAX_RESULTS_DEFAULT
from mlflow.tracking._model_registry.client import ModelRegistryClient
from mlflow.tracking._model_registry import utils as registry_utils
from mlflow.tracking._model_registry import DEFAULT_AWAIT_MAX_SLEEP_SECONDS
from mlflow.tracking._tracking_service import utils
from mlflow.tracking._tracking_service.client import TrackingServiceClient
from mlflow.tracking.artifact_utils import _upload_artifacts_to_databricks
from mlflow.tracking.registry import UnsupportedModelRegistryStoreURIException
from mlflow.utils.databricks_utils import (
is_databricks_default_tracking_uri,
is_in_databricks_job,
is_in_databricks_notebook,
get_workspace_info_from_dbutils,
get_workspace_info_from_databricks_secrets,
)
from mlflow.utils.logging_utils import eprint
from mlflow.utils.uri import is_databricks_uri, construct_run_url
if TYPE_CHECKING:
import matplotlib # pylint: disable=unused-import
import plotly # pylint: disable=unused-import
import numpy # pylint: disable=unused-import
import PIL # pylint: disable=unused-import
_logger = logging.getLogger(__name__)
class MlflowClient(object):
"""
Client of an MLflow Tracking Server that creates and manages experiments and runs, and of an
MLflow Registry Server that creates and manages registered models and model versions. It's a
thin wrapper around TrackingServiceClient and RegistryClient so there is a unified API but we
can keep the implementation of the tracking and registry clients independent from each other.
"""
def __init__(self, tracking_uri: Optional[str] = None, registry_uri: Optional[str] = None):
"""
:param tracking_uri: Address of local or remote tracking server. If not provided, defaults
to the service set by ``mlflow.tracking.set_tracking_uri``. See
`Where Runs Get Recorded <../tracking.html#where-runs-get-recorded>`_
for more info.
:param registry_uri: Address of local or remote model registry server. If not provided,
defaults to the service set by ``mlflow.tracking.set_registry_uri``. If
no such service was set, defaults to the tracking uri of the client.
"""
final_tracking_uri = utils._resolve_tracking_uri(tracking_uri)
self._registry_uri = registry_utils._resolve_registry_uri(registry_uri, tracking_uri)
self._tracking_client = TrackingServiceClient(final_tracking_uri)
# `MlflowClient` also references a `ModelRegistryClient` instance that is provided by the
# `MlflowClient._get_registry_client()` method. This `ModelRegistryClient` is not explicitly
# defined as an instance variable in the `MlflowClient` constructor; an instance variable
# is assigned lazily by `MlflowClient._get_registry_client()` and should not be referenced
# outside of the `MlflowClient._get_registry_client()` method
def _get_registry_client(self):
"""
Attempts to create a py:class:`ModelRegistryClient` if one does not already exist.
:raises: py:class:`mlflow.exceptions.MlflowException` if the py:class:`ModelRegistryClient`
cannot be created. This may occur, for example, when the registry URI refers
to an unsupported store type (e.g., the FileStore).
:return: A py:class:`ModelRegistryClient` instance
"""
# Attempt to fetch a `ModelRegistryClient` that is lazily instantiated and defined as
# an instance variable on this `MlflowClient` instance. Because the instance variable
# is undefined until the first invocation of _get_registry_client(), the `getattr()`
# function is used to safely fetch the variable (if it is defined) or a NoneType
# (if it is not defined)
registry_client_attr = "_registry_client_lazy"
registry_client = getattr(self, registry_client_attr, None)
if registry_client is None:
try:
registry_client = ModelRegistryClient(self._registry_uri)
# Define an instance variable on this `MlflowClient` instance to reference the
# `ModelRegistryClient` that was just constructed. `setattr()` is used to ensure
# that the variable name is consistent with the variable name specified in the
# preceding call to `getattr()`
setattr(self, registry_client_attr, registry_client)
except UnsupportedModelRegistryStoreURIException as exc:
raise MlflowException(
"Model Registry features are not supported by the store with URI:"
" '{uri}'. Stores with the following URI schemes are supported:"
" {schemes}.".format(uri=self._registry_uri, schemes=exc.supported_uri_schemes),
FEATURE_DISABLED,
)
return registry_client
# Tracking API
def get_run(self, run_id: str) -> Run:
"""
Fetch the run from backend store. The resulting :py:class:`Run <mlflow.entities.Run>`
contains a collection of run metadata -- :py:class:`RunInfo <mlflow.entities.RunInfo>`,
as well as a collection of run parameters, tags, and metrics --
:py:class:`RunData <mlflow.entities.RunData>`. In the case where multiple metrics with the
same key are logged for the run, the :py:class:`RunData <mlflow.entities.RunData>` contains
the most recently logged value at the largest step for each metric.
:param run_id: Unique identifier for the run.
:return: A single :py:class:`mlflow.entities.Run` object, if the run exists. Otherwise,
raises an exception.
.. code-block:: python
:caption: Example
import mlflow
from mlflow.tracking import MlflowClient
with mlflow.start_run() as run:
mlflow.log_param("p", 0)
# The run has finished since we have exited the with block
# Fetch the run
client = MlflowClient()
run = client.get_run(run.info.run_id)
print("run_id: {}".format(run.info.run_id))
print("params: {}".format(run.data.params))
print("status: {}".format(run.info.status))
.. code-block:: text
:caption: Output
run_id: e36b42c587a1413ead7c3b6764120618
params: {'p': '0'}
status: FINISHED
"""
return self._tracking_client.get_run(run_id)
def get_metric_history(self, run_id: str, key: str) -> List[Metric]:
"""
Return a list of metric objects corresponding to all values logged for a given metric.
:param run_id: Unique identifier for run
:param key: Metric name within the run
:return: A list of :py:class:`mlflow.entities.Metric` entities if logged, else empty list
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
def print_metric_info(history):
for m in history:
print("name: {}".format(m.key))
print("value: {}".format(m.value))
print("step: {}".format(m.step))
print("timestamp: {}".format(m.timestamp))
print("--")
# Create a run under the default experiment (whose id is "0"). Since this is low-level
# CRUD operation, the method will create a run. To end the run, you'll have
# to explicitly end it.
client = MlflowClient()
experiment_id = "0"
run = client.create_run(experiment_id)
print("run_id: {}".format(run.info.run_id))
print("--")
# Log couple of metrics, update their initial value, and fetch each
# logged metrics' history.
for k, v in [("m1", 1.5), ("m2", 2.5)]:
client.log_metric(run.info.run_id, k, v, step=0)
client.log_metric(run.info.run_id, k, v + 1, step=1)
print_metric_info(client.get_metric_history(run.info.run_id, k))
client.set_terminated(run.info.run_id)
.. code-block:: text
:caption: Output
run_id: c360d15714994c388b504fe09ea3c234
--
name: m1
value: 1.5
step: 0
timestamp: 1603423788607
--
name: m1
value: 2.5
step: 1
timestamp: 1603423788608
--
name: m2
value: 2.5
step: 0
timestamp: 1603423788609
--
name: m2
value: 3.5
step: 1
timestamp: 1603423788610
--
"""
return self._tracking_client.get_metric_history(run_id, key)
def create_run(
self,
experiment_id: str,
start_time: Optional[int] = None,
tags: Optional[Dict[str, Any]] = None,
) -> Run:
"""
Create a :py:class:`mlflow.entities.Run` object that can be associated with
metrics, parameters, artifacts, etc.
Unlike :py:func:`mlflow.projects.run`, creates objects but does not run code.
Unlike :py:func:`mlflow.start_run`, does not change the "active run" used by
:py:func:`mlflow.log_param`.
:param experiment_id: The string ID of the experiment to create a run in.
:param start_time: If not provided, use the current timestamp.
:param tags: A dictionary of key-value pairs that are converted into
:py:class:`mlflow.entities.RunTag` objects.
:return: :py:class:`mlflow.entities.Run` that was created.
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
# Create a run with a tag under the default experiment (whose id is '0').
tags = {"engineering": "ML Platform"}
client = MlflowClient()
experiment_id = "0"
run = client.create_run(experiment_id, tags=tags)
# Show newly created run metadata info
print("Run tags: {}".format(run.data.tags))
print("Experiment id: {}".format(run.info.experiment_id))
print("Run id: {}".format(run.info.run_id))
print("lifecycle_stage: {}".format(run.info.lifecycle_stage))
print("status: {}".format(run.info.status))
.. code-block:: text
:caption: Output
Run tags: {'engineering': 'ML Platform'}
Experiment id: 0
Run id: 65fb9e2198764354bab398105f2e70c1
lifecycle_stage: active
status: RUNNING
"""
return self._tracking_client.create_run(experiment_id, start_time, tags)
def list_run_infos(
self,
experiment_id: str,
run_view_type: int = ViewType.ACTIVE_ONLY,
max_results: int = SEARCH_MAX_RESULTS_DEFAULT,
order_by: Optional[List[str]] = None,
page_token: Optional[str] = None,
) -> PagedList[RunInfo]:
"""
Return run information for runs which belong to the experiment_id.
:param experiment_id: The experiment id which to search
:param run_view_type: ACTIVE_ONLY, DELETED_ONLY, or ALL runs
:param max_results: Maximum number of results desired.
:param order_by: List of order_by clauses. Currently supported values are
are ``metric.key``, ``parameter.key``, ``tag.key``, ``attribute.key``.
For example, ``order_by=["tag.release ASC", "metric.click_rate DESC"]``.
:return: A :py:class:`PagedList <mlflow.store.entities.PagedList>` of
:py:class:`RunInfo <mlflow.entities.RunInfo>` objects that satisfy the search
expressions. If the underlying tracking store supports pagination, the token for the
next page may be obtained via the ``token`` attribute of the returned object.
.. code-block:: python
:caption: Example
import mlflow
from mlflow.tracking import MlflowClient
from mlflow.entities import ViewType
def print_run_infos(run_infos):
for r in run_infos:
print("- run_id: {}, lifecycle_stage: {}".format(r.run_id, r.lifecycle_stage))
# Create two runs
with mlflow.start_run() as run1:
mlflow.log_metric("click_rate", 1.55)
with mlflow.start_run() as run2:
mlflow.log_metric("click_rate", 2.50)
# Delete the last run
client = MlflowClient()
client.delete_run(run2.info.run_id)
# Get all runs under the default experiment (whose id is 0)
print("Active runs:")
print_run_infos(mlflow.list_run_infos("0", run_view_type=ViewType.ACTIVE_ONLY))
print("Deleted runs:")
print_run_infos(mlflow.list_run_infos("0", run_view_type=ViewType.DELETED_ONLY))
print("All runs:")
print_run_infos(mlflow.list_run_infos("0", run_view_type=ViewType.ALL,
order_by=["metric.click_rate DESC"]))
.. code-block:: text
:caption: Output
Active runs:
- run_id: 47b11b33f9364ee2b148c41375a30a68, lifecycle_stage: active
Deleted runs:
- run_id: bc4803439bdd4a059103811267b6b2f4, lifecycle_stage: deleted
All runs:
- run_id: bc4803439bdd4a059103811267b6b2f4, lifecycle_stage: deleted
- run_id: 47b11b33f9364ee2b148c41375a30a68, lifecycle_stage: active
"""
return self._tracking_client.list_run_infos(
experiment_id, run_view_type, max_results, order_by, page_token
)
def list_experiments(
self,
view_type: int = ViewType.ACTIVE_ONLY,
max_results: Optional[int] = None,
page_token: Optional[str] = None,
) -> PagedList[Experiment]:
"""
:param view_type: Qualify requested type of experiments.
:param max_results: If passed, specifies the maximum number of experiments desired. If not
passed, all experiments will be returned for the File and SQL backends.
For the REST backend, the server will pick a maximum number of results
to return.
:param page_token: Token specifying the next page of results. It should be obtained from
a ``list_experiments`` call.
:return: A :py:class:`PagedList <mlflow.store.entities.PagedList>` of
:py:class:`Experiment <mlflow.entities.Experiment>` objects. The pagination token
for the next page can be obtained via the ``token`` attribute of the object.
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
from mlflow.entities import ViewType
def print_experiment_info(experiments):
for e in experiments:
print("- experiment_id: {}, name: {}, lifecycle_stage: {}"
.format(e.experiment_id, e.name, e.lifecycle_stage))
client = MlflowClient()
for name in ["Experiment 1", "Experiment 2"]:
exp_id = client.create_experiment(name)
# Delete the last experiment
client.delete_experiment(exp_id)
# Fetch experiments by view type
print("Active experiments:")
print_experiment_info(client.list_experiments(view_type=ViewType.ACTIVE_ONLY))
print("Deleted experiments:")
print_experiment_info(client.list_experiments(view_type=ViewType.DELETED_ONLY))
print("All experiments:")
print_experiment_info(client.list_experiments(view_type=ViewType.ALL))
.. code-block:: text
:caption: Output
Active experiments:
- experiment_id: 0, name: Default, lifecycle_stage: active
- experiment_id: 1, name: Experiment 1, lifecycle_stage: active
Deleted experiments:
- experiment_id: 2, name: Experiment 2, lifecycle_stage: deleted
All experiments:
- experiment_id: 0, name: Default, lifecycle_stage: active
- experiment_id: 1, name: Experiment 1, lifecycle_stage: active
- experiment_id: 2, name: Experiment 2, lifecycle_stage: deleted
"""
return self._tracking_client.list_experiments(
view_type=view_type, max_results=max_results, page_token=page_token
)
def get_experiment(self, experiment_id: str) -> Experiment:
"""
Retrieve an experiment by experiment_id from the backend store
:param experiment_id: The experiment ID returned from ``create_experiment``.
:return: :py:class:`mlflow.entities.Experiment`
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
client = MlflowClient()
exp_id = client.create_experiment("Experiment")
experiment = client.get_experiment(exp_id)
# Show experiment info
print("Name: {}".format(experiment.name))
print("Experiment ID: {}".format(experiment.experiment_id))
print("Artifact Location: {}".format(experiment.artifact_location))
print("Lifecycle_stage: {}".format(experiment.lifecycle_stage))
.. code-block:: text
:caption: Output
Name: Experiment
Experiment ID: 1
Artifact Location: file:///.../mlruns/1
Lifecycle_stage: active
"""
return self._tracking_client.get_experiment(experiment_id)
def get_experiment_by_name(self, name: str) -> Optional[Experiment]:
"""
Retrieve an experiment by experiment name from the backend store
:param name: The experiment name, which is case sensitive.
:return: An instance of :py:class:`mlflow.entities.Experiment`
if an experiment with the specified name exists, otherwise None.
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
# Case-sensitive name
client = MlflowClient()
experiment = client.get_experiment_by_name("Default")
# Show experiment info
print("Name: {}".format(experiment.name))
print("Experiment ID: {}".format(experiment.experiment_id))
print("Artifact Location: {}".format(experiment.artifact_location))
print("Lifecycle_stage: {}".format(experiment.lifecycle_stage))
.. code-block:: text
:caption: Output
Name: Default
Experiment ID: 0
Artifact Location: file:///.../mlruns/0
Lifecycle_stage: active
"""
return self._tracking_client.get_experiment_by_name(name)
def create_experiment(
self,
name: str,
artifact_location: Optional[str] = None,
tags: Optional[Dict[str, Any]] = None,
) -> str:
"""Create an experiment.
:param name: The experiment name. Must be unique.
:param artifact_location: The location to store run artifacts.
If not provided, the server picks an appropriate default.
:param tags: A dictionary of key-value pairs that are converted into
:py:class:`mlflow.entities.ExperimentTag` objects, set as
experiment tags upon experiment creation.
:return: String as an integer ID of the created experiment.
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
# Create an experiment with a name that is unique and case sensitive.
client = MlflowClient()
experiment_id = client.create_experiment("Social NLP Experiments")
client.set_experiment_tag(experiment_id, "nlp.framework", "Spark NLP")
# Fetch experiment metadata information
experiment = client.get_experiment(experiment_id)
print("Name: {}".format(experiment.name))
print("Experiment_id: {}".format(experiment.experiment_id))
print("Artifact Location: {}".format(experiment.artifact_location))
print("Tags: {}".format(experiment.tags))
print("Lifecycle_stage: {}".format(experiment.lifecycle_stage))
.. code-block:: text
:caption: Output
Name: Social NLP Experiments
Experiment_id: 1
Artifact Location: file:///.../mlruns/1
Tags: {'nlp.framework': 'Spark NLP'}
Lifecycle_stage: active
"""
return self._tracking_client.create_experiment(name, artifact_location, tags)
def delete_experiment(self, experiment_id: str) -> None:
"""
Delete an experiment from the backend store.
:param experiment_id: The experiment ID returned from ``create_experiment``.
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
# Create an experiment with a name that is unique and case sensitive
client = MlflowClient()
experiment_id = client.create_experiment("New Experiment")
client.delete_experiment(experiment_id)
# Examine the deleted experiment details.
experiment = client.get_experiment(experiment_id)
print("Name: {}".format(experiment.name))
print("Artifact Location: {}".format(experiment.artifact_location))
print("Lifecycle_stage: {}".format(experiment.lifecycle_stage))
.. code-block:: text
:caption: Output
Name: New Experiment
Artifact Location: file:///.../mlruns/1
Lifecycle_stage: deleted
"""
self._tracking_client.delete_experiment(experiment_id)
def restore_experiment(self, experiment_id: str) -> None:
"""
Restore a deleted experiment unless permanently deleted.
:param experiment_id: The experiment ID returned from ``create_experiment``.
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
def print_experiment_info(experiment):
print("Name: {}".format(experiment.name))
print("Experiment Id: {}".format(experiment.experiment_id))
print("Lifecycle_stage: {}".format(experiment.lifecycle_stage))
# Create and delete an experiment
client = MlflowClient()
experiment_id = client.create_experiment("New Experiment")
client.delete_experiment(experiment_id)
# Examine the deleted experiment details.
experiment = client.get_experiment(experiment_id)
print_experiment_info(experiment)
print("--")
# Restore the experiment and fetch its info
client.restore_experiment(experiment_id)
experiment = client.get_experiment(experiment_id)
print_experiment_info(experiment)
.. code-block:: text
:caption: Output
Name: New Experiment
Experiment Id: 1
Lifecycle_stage: deleted
--
Name: New Experiment
Experiment Id: 1
Lifecycle_stage: active
"""
self._tracking_client.restore_experiment(experiment_id)
def rename_experiment(self, experiment_id: str, new_name: str) -> None:
"""
Update an experiment's name. The new name must be unique.
:param experiment_id: The experiment ID returned from ``create_experiment``.
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
def print_experiment_info(experiment):
print("Name: {}".format(experiment.name))
print("Experiment_id: {}".format(experiment.experiment_id))
print("Lifecycle_stage: {}".format(experiment.lifecycle_stage))
# Create an experiment with a name that is unique and case sensitive
client = MlflowClient()
experiment_id = client.create_experiment("Social NLP Experiments")
# Fetch experiment metadata information
experiment = client.get_experiment(experiment_id)
print_experiment_info(experiment)
print("--")
# Rename and fetch experiment metadata information
client.rename_experiment(experiment_id, "Social Media NLP Experiments")
experiment = client.get_experiment(experiment_id)
print_experiment_info(experiment)
.. code-block:: text
:caption: Output
Name: Social NLP Experiments
Experiment_id: 1
Lifecycle_stage: active
--
Name: Social Media NLP Experiments
Experiment_id: 1
Lifecycle_stage: active
"""
self._tracking_client.rename_experiment(experiment_id, new_name)
def log_metric(
self,
run_id: str,
key: str,
value: float,
timestamp: Optional[int] = None,
step: Optional[int] = None,
) -> None:
"""
Log a metric against the run ID.
:param run_id: The run id to which the metric should be logged.
:param key: Metric name (string). This string may only contain alphanumerics, underscores
(_), dashes (-), periods (.), spaces ( ), and slashes (/).
All backend stores will support keys up to length 250, but some may
support larger keys.
:param value: Metric value (float). Note that some special values such
as +/- Infinity may be replaced by other values depending on the store. For
example, the SQLAlchemy store replaces +/- Inf with max / min float values.
All backend stores will support values up to length 5000, but some
may support larger values.
:param timestamp: Time when this metric was calculated. Defaults to the current system time.
:param step: Integer training step (iteration) at which was the metric calculated.
Defaults to 0.
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
def print_run_info(r):
print("run_id: {}".format(r.info.run_id))
print("metrics: {}".format(r.data.metrics))
print("status: {}".format(r.info.status))
# Create a run under the default experiment (whose id is '0').
# Since these are low-level CRUD operations, this method will create a run.
# To end the run, you'll have to explicitly end it.
client = MlflowClient()
experiment_id = "0"
run = client.create_run(experiment_id)
print_run_info(run)
print("--")
# Log the metric. Unlike mlflow.log_metric this method
# does not start a run if one does not exist. It will log
# the metric for the run id in the backend store.
client.log_metric(run.info.run_id, "m", 1.5)
client.set_terminated(run.info.run_id)
run = client.get_run(run.info.run_id)
print_run_info(run)
.. code-block:: text
:caption: Output
run_id: 95e79843cb2c463187043d9065185e24
metrics: {}
status: RUNNING
--
run_id: 95e79843cb2c463187043d9065185e24
metrics: {'m': 1.5}
status: FINISHED
"""
self._tracking_client.log_metric(run_id, key, value, timestamp, step)
def log_param(self, run_id: str, key: str, value: Any) -> None:
"""
Log a parameter against the run ID.
:param run_id: The run id to which the param should be logged.
:param key: Parameter name (string). This string may only contain alphanumerics, underscores
(_), dashes (-), periods (.), spaces ( ), and slashes (/).
All backend stores will support keys up to length 250, but some may
support larger keys.
:param value: Parameter value (string, but will be string-ified if not).
All backend stores will support values up to length 5000, but some
may support larger values.
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
def print_run_info(r):
print("run_id: {}".format(r.info.run_id))
print("params: {}".format(r.data.params))
print("status: {}".format(r.info.status))
# Create a run under the default experiment (whose id is '0').
# Since these are low-level CRUD operations, this method will create a run.
# To end the run, you'll have to explicitly end it.
client = MlflowClient()
experiment_id = "0"
run = client.create_run(experiment_id)
print_run_info(run)
print("--")
# Log the parameter. Unlike mlflow.log_param this method
# does not start a run if one does not exist. It will log
# the parameter in the backend store
client.log_param(run.info.run_id, "p", 1)
client.set_terminated(run.info.run_id)
run = client.get_run(run.info.run_id)
print_run_info(run)
.. code-block:: text
:caption: Output
run_id: e649e49c7b504be48ee3ae33c0e76c93
params: {}
status: RUNNING
--
run_id: e649e49c7b504be48ee3ae33c0e76c93
params: {'p': '1'}
status: FINISHED
"""
self._tracking_client.log_param(run_id, key, value)
def set_experiment_tag(self, experiment_id: str, key: str, value: Any) -> None:
"""
Set a tag on the experiment with the specified ID. Value is converted to a string.
:param experiment_id: String ID of the experiment.
:param key: Name of the tag.
:param value: Tag value (converted to a string).
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
# Create an experiment and set its tag
client = MlflowClient()
experiment_id = client.create_experiment("Social Media NLP Experiments")
client.set_experiment_tag(experiment_id, "nlp.framework", "Spark NLP")
# Fetch experiment metadata information
experiment = client.get_experiment(experiment_id)
print("Name: {}".format(experiment.name))
print("Tags: {}".format(experiment.tags))
.. code-block:: text
:caption: Output
Name: Social Media NLP Experiments
Tags: {'nlp.framework': 'Spark NLP'}
"""
self._tracking_client.set_experiment_tag(experiment_id, key, value)
def set_tag(self, run_id: str, key: str, value: Any) -> None:
"""
Set a tag on the run with the specified ID. Value is converted to a string.
:param run_id: String ID of the run.
:param key: Tag name (string). This string may only contain alphanumerics,
underscores (_), dashes (-), periods (.), spaces ( ), and slashes (/).
All backend stores will support keys up to length 250, but some may
support larger keys.
:param value: Tag value (string, but will be string-ified if not).
All backend stores will support values up to length 5000, but some
may support larger values.
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
def print_run_info(run):
print("run_id: {}".format(run.info.run_id))
print("Tags: {}".format(run.data.tags))
# Create a run under the default experiment (whose id is '0').
client = MlflowClient()
experiment_id = "0"
run = client.create_run(experiment_id)
print_run_info(run)
print("--")
# Set a tag and fetch updated run info
client.set_tag(run.info.run_id, "nlp.framework", "Spark NLP")
run = client.get_run(run.info.run_id)
print_run_info(run)
.. code-block:: text
:caption: Output
run_id: 4f226eb5758145e9b28f78514b59a03b
Tags: {}
--
run_id: 4f226eb5758145e9b28f78514b59a03b
Tags: {'nlp.framework': 'Spark NLP'}
"""
self._tracking_client.set_tag(run_id, key, value)
def delete_tag(self, run_id: str, key: str) -> None:
"""
Delete a tag from a run. This is irreversible.
:param run_id: String ID of the run
:param key: Name of the tag
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
def print_run_info(run):
print("run_id: {}".format(run.info.run_id))
print("Tags: {}".format(run.data.tags))
# Create a run under the default experiment (whose id is '0').
client = MlflowClient()
tags = {"t1": 1, "t2": 2}
experiment_id = "0"
run = client.create_run(experiment_id, tags=tags)
print_run_info(run)
print("--")
# Delete tag and fetch updated info
client.delete_tag(run.info.run_id, "t1")
run = client.get_run(run.info.run_id)
print_run_info(run)
.. code-block:: text
:caption: Output
run_id: b7077267a59a45d78cd9be0de4bc41f5
Tags: {'t2': '2', 't1': '1'}
--
run_id: b7077267a59a45d78cd9be0de4bc41f5
Tags: {'t2': '2'}
"""
self._tracking_client.delete_tag(run_id, key)
def log_batch(
self,
run_id: str,
metrics: Sequence[Metric] = (),
params: Sequence[Param] = (),
tags: Sequence[RunTag] = (),
) -> None:
"""
Log multiple metrics, params, and/or tags.
:param run_id: String ID of the run
:param metrics: If provided, List of Metric(key, value, timestamp) instances.
:param params: If provided, List of Param(key, value) instances.
:param tags: If provided, List of RunTag(key, value) instances.
Raises an MlflowException if any errors occur.
:return: None
.. code-block:: python
:caption: Example
import time
from mlflow.tracking import MlflowClient
from mlflow.entities import Metric, Param, RunTag
def print_run_info(r):
print("run_id: {}".format(r.info.run_id))
print("params: {}".format(r.data.params))
print("metrics: {}".format(r.data.metrics))
print("tags: {}".format(r.data.tags))
print("status: {}".format(r.info.status))
# Create MLflow entities and a run under the default experiment (whose id is '0').
timestamp = int(time.time() * 1000)
metrics = [Metric('m', 1.5, timestamp, 1)]
params = [Param("p", 'p')]
tags = [RunTag("t", "t")]
experiment_id = "0"
client = MlflowClient()
run = client.create_run(experiment_id)
# Log entities, terminate the run, and fetch run status
client.log_batch(run.info.run_id, metrics=metrics, params=params, tags=tags)
client.set_terminated(run.info.run_id)
run = client.get_run(run.info.run_id)
print_run_info(run)
.. code-block:: text
:caption: Output
run_id: ef0247fa3205410595acc0f30f620871
params: {'p': 'p'}
metrics: {'m': 1.5}
tags: {'t': 't'}
status: FINISHED
"""
self._tracking_client.log_batch(run_id, metrics, params, tags)
def log_artifact(self, run_id, local_path, artifact_path=None) -> None:
"""
Write a local file or directory to the remote ``artifact_uri``.
:param local_path: Path to the file or directory to write.
:param artifact_path: If provided, the directory in ``artifact_uri`` to write to.
.. code-block:: python
:caption: Example
from mlflow.tracking import MlflowClient
features = "rooms, zipcode, median_price, school_rating, transport"
with open("features.txt", 'w') as f:
f.write(features)
# Create a run under the default experiment (whose id is '0').
client = MlflowClient()
experiment_id = "0"
run = client.create_run(experiment_id)
# log and fetch the artifact
client.log_artifact(run.info.run_id, "features.txt")
artifacts = client.list_artifacts(run.info.run_id)
for artifact in artifacts:
print("artifact: {}".format(artifact.path))
print("is_dir: {}".format(artifact.is_dir))
client.set_terminated(run.info.run_id)
.. code-block:: text
:caption: Output
artifact: features.txt
is_dir: False
"""
self._tracking_client.log_artifact(run_id, local_path, artifact_path)
def log_artifacts(
self, run_id: str, local_dir: str, artifact_path: Optional[str] = None
) -> None:
"""
Write a directory of files to the remote ``artifact_uri``.
:param local_dir: Path to the directory of files to write.
:param artifact_path: If provided, the directory in ``artifact_uri`` to write to.
.. code-block:: python
:caption: Example
import os
import json
# Create some artifacts data to preserve
features = "rooms, zipcode, median_price, school_rating, transport"
data = {"state": "TX", "Available": 25, "Type": "Detached"}
# Create couple of artifact files under the local directory "data"
os.makedirs("data", exist_ok=True)
with open("data/data.json", 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
with open("data/features.txt", 'w') as f:
f.write(features)
# Create a run under the default experiment (whose id is '0'), and log
# all files in "data" to root artifact_uri/states
client = MlflowClient()
experiment_id = "0"
run = client.create_run(experiment_id)
client.log_artifacts(run.info.run_id, "data", artifact_path="states")
artifacts = client.list_artifacts(run.info.run_id)
for artifact in artifacts:
print("artifact: {}".format(artifact.path))
print("is_dir: {}".format(artifact.is_dir))
client.set_terminated(run.info.run_id)
.. code-block:: text
:caption: Output
artifact: states
is_dir: True
"""