-
Notifications
You must be signed in to change notification settings - Fork 239
/
model.py
547 lines (468 loc) · 15.7 KB
/
model.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
# Copyright 2018 Iguazio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import inspect
import warnings
from copy import deepcopy
from os import environ
from .config import config
from .db import get_run_db
from .utils import dict_to_yaml, get_in, dict_to_json, get_artifact_target
class ModelObj:
_dict_fields = []
@staticmethod
def _verify_list(param, name):
if not isinstance(param, list):
raise ValueError(f"parameter {name} must be a list")
@staticmethod
def _verify_dict(param, name, new_type=None):
if (
param is not None
and not isinstance(param, dict)
and not hasattr(param, "to_dict")
):
raise ValueError(f"parameter {name} must be a dict or object")
if new_type and (isinstance(param, dict) or param is None):
return new_type.from_dict(param)
return param
def to_dict(self, fields=None, exclude=None):
struct = {}
fields = fields or self._dict_fields
if not fields:
fields = list(inspect.signature(self.__init__).parameters.keys())
for t in fields:
if not exclude or t not in exclude:
val = getattr(self, t, None)
if val is not None and not (isinstance(val, dict) and not val):
if hasattr(val, "to_dict"):
val = val.to_dict()
if val:
struct[t] = val
else:
struct[t] = val
return struct
@classmethod
def from_dict(cls, struct=None, fields=None):
struct = {} if struct is None else struct
fields = fields or cls._dict_fields
if not fields:
fields = list(inspect.signature(cls.__init__).parameters.keys())
new_obj = cls()
if struct:
for key, val in struct.items():
if key in fields:
setattr(new_obj, key, val)
return new_obj
def to_yaml(self):
return dict_to_yaml(self.to_dict())
def to_json(self):
return dict_to_json(self.to_dict())
def to_str(self):
return "{}".format(self.to_dict())
def __str__(self):
return str(self.to_dict())
def copy(self):
return deepcopy(self)
class BaseMetadata(ModelObj):
def __init__(
self,
name=None,
tag=None,
hash=None,
namespace=None,
project=None,
labels=None,
annotations=None,
categories=None,
updated=None,
):
self.name = name
self.tag = tag
self.hash = hash
self.namespace = namespace
self.project = project or config.default_project
self.labels = labels or {}
self.categories = categories or []
self.annotations = annotations or {}
self.updated = updated
class ImageBuilder(ModelObj):
"""An Image builder"""
def __init__(
self,
functionSourceCode=None,
source=None,
image=None,
base_image=None,
commands=None,
secret=None,
code_origin=None,
registry=None,
):
self.functionSourceCode = functionSourceCode #: functionSourceCode
self.codeEntryType = "" #: codeEntryType
self.source = source #: course
self.code_origin = code_origin #: code_origin
self.image = image #: image
self.base_image = base_image #: base_image
self.commands = commands or [] #: commands
self.secret = secret #: secret
self.registry = registry #: registry
self.build_pod = None
class RunMetadata(ModelObj):
"""Run metadata"""
def __init__(
self,
uid=None,
name=None,
project=None,
labels=None,
annotations=None,
iteration=None,
):
self.uid = uid
self._iteration = iteration
self.name = name
self.project = project
self.labels = labels or {}
self.annotations = annotations or {}
@property
def iteration(self):
return self._iteration or 0
@iteration.setter
def iteration(self, iteration):
self._iteration = iteration
class RunSpec(ModelObj):
"""Run specification"""
def __init__(
self,
parameters=None,
hyperparams=None,
param_file=None,
selector=None,
handler=None,
inputs=None,
outputs=None,
input_path=None,
output_path=None,
function=None,
secret_sources=None,
data_stores=None,
tuning_strategy=None,
verbose=None,
scrape_metrics=False,
):
self.parameters = parameters or {}
self.hyperparams = hyperparams or {}
self.param_file = param_file
self.tuning_strategy = tuning_strategy
self.selector = selector
self.handler = handler
self._inputs = inputs
self._outputs = outputs
self.input_path = input_path
self.output_path = output_path
self.function = function
self._secret_sources = secret_sources or []
self._data_stores = data_stores
self.verbose = verbose
self.scrape_metrics = scrape_metrics
def to_dict(self, fields=None, exclude=None):
struct = super().to_dict(fields, exclude=["handler"])
if self.handler and isinstance(self.handler, str):
struct["handler"] = self.handler
return struct
@property
def inputs(self):
return self._inputs
@inputs.setter
def inputs(self, inputs):
self._inputs = self._verify_dict(inputs, "inputs")
@property
def outputs(self):
return self._outputs
@outputs.setter
def outputs(self, outputs):
self._verify_list(outputs, "outputs")
self._outputs = outputs
@property
def secret_sources(self):
return self._secret_sources
@secret_sources.setter
def secret_sources(self, secret_sources):
self._verify_list(secret_sources, "secret_sources")
self._secret_sources = secret_sources
@property
def data_stores(self):
return self._data_stores
@data_stores.setter
def data_stores(self, data_stores):
self._verify_list(data_stores, "data_stores")
self._data_stores = data_stores
@property
def handler_name(self):
if self.handler:
if inspect.isfunction(self.handler):
return self.handler.__name__
else:
return str(self.handler)
return ""
class RunStatus(ModelObj):
"""Run status"""
def __init__(
self,
state=None,
error=None,
host=None,
commit=None,
status_text=None,
results=None,
artifacts=None,
start_time=None,
last_update=None,
iterations=None,
):
self.state = state or "created"
self.status_text = status_text
self.error = error
self.host = host
self.commit = commit
self.results = results
self.artifacts = artifacts
self.start_time = start_time
self.last_update = last_update
self.iterations = iterations
class RunTemplate(ModelObj):
"""Run template"""
def __init__(self, spec: RunSpec = None, metadata: RunMetadata = None):
self._spec = None
self._metadata = None
self.spec = spec
self.metadata = metadata
@property
def spec(self) -> RunSpec:
return self._spec
@spec.setter
def spec(self, spec):
self._spec = self._verify_dict(spec, "spec", RunSpec)
@property
def metadata(self) -> RunMetadata:
return self._metadata
@metadata.setter
def metadata(self, metadata):
self._metadata = self._verify_dict(metadata, "metadata", RunMetadata)
def with_params(self, **kwargs):
self.spec.parameters = kwargs
return self
def with_input(self, key, path):
if not self.spec.inputs:
self.spec.inputs = {}
self.spec.inputs[key] = path
return self
def with_hyper_params(self, hyperparams, selector=None, strategy=None):
self.spec.hyperparams = hyperparams
self.spec.selector = selector
self.spec.tuning_strategy = strategy
return self
def with_param_file(self, param_file, selector=None, strategy=None):
self.spec.param_file = param_file
self.spec.selector = selector
self.spec.tuning_strategy = strategy
return self
def with_secrets(self, kind, source):
"""register a secrets source (file, env or dict)
read secrets from a source provider to be used in workflows, e.g.
proj.with_secrets('file', 'file.txt')
proj.with_secrets('inline', {'key': 'val'})
proj.with_secrets('env', 'ENV1,ENV2')
:param kind: secret type (file, inline, env)
:param source: secret data or link (see example)
:returns: project object
"""
self.spec.secret_sources.append({"kind": kind, "source": source})
return self
def set_label(self, key, value):
self.metadata.labels[key] = str(value)
return self
def to_env(self):
environ["MLRUN_EXEC_CONFIG"] = self.to_json()
class RunObject(RunTemplate):
"""A run"""
def __init__(
self,
spec: RunSpec = None,
metadata: RunMetadata = None,
status: RunStatus = None,
):
super().__init__(spec, metadata)
self._status = None
self.status = status
@classmethod
def from_template(cls, template: RunTemplate):
return cls(template.spec, template.metadata)
@property
def status(self) -> RunStatus:
return self._status
@status.setter
def status(self, status):
self._status = self._verify_dict(status, "status", RunStatus)
def output(self, key):
if self.status.results and key in self.status.results:
return self.status.results.get(key)
artifact = self.artifact(key)
if artifact:
return get_artifact_target(artifact, self.metadata.project)
return None
@property
def outputs(self):
outputs = {}
if self.status.results:
outputs = {k: v for k, v in self.status.results.items()}
if self.status.artifacts:
for a in self.status.artifacts:
outputs[a["key"]] = get_artifact_target(a, self.metadata.project)
return outputs
def artifact(self, key):
if self.status.artifacts:
for a in self.status.artifacts:
if a["key"] == key:
return a
return None
def uid(self):
return self.metadata.uid
def state(self):
db = get_run_db().connect()
run = db.read_run(
uid=self.metadata.uid,
project=self.metadata.project,
iter=self.metadata.iteration,
)
if run:
return get_in(run, "status.state", "unknown")
def show(self):
db = get_run_db().connect()
db.list_runs(uid=self.metadata.uid, project=self.metadata.project).show()
def logs(self, watch=True, db=None):
if not db:
db = get_run_db().connect()
if not db:
print("DB is not configured, cannot show logs")
return None
if db.kind == "http":
state = db.watch_log(self.metadata.uid, self.metadata.project, watch=watch)
else:
state, text = db.get_log(self.metadata.uid, self.metadata.project)
if text:
print(text.decode())
if state:
print("final state: {}".format(state))
return state
# TODO: remove in 0.9.0
def NewTask(
name=None,
project=None,
handler=None,
params=None,
hyper_params=None,
param_file=None,
selector=None,
tuning_strategy=None,
inputs=None,
outputs=None,
in_path=None,
out_path=None,
artifact_path=None,
secrets=None,
base=None,
):
"""Creates a new task - see new_task
"""
warnings.warn(
"NewTask will be deprecated in 0.7.0, and will be removed in 0.9.0, use new_task instead",
# TODO: change to FutureWarning in 0.7.0
PendingDeprecationWarning,
)
return new_task(
name,
project,
handler,
params,
hyper_params,
param_file,
selector,
tuning_strategy,
inputs,
outputs,
in_path,
out_path,
artifact_path,
secrets,
base,
)
def new_task(
name=None,
project=None,
handler=None,
params=None,
hyper_params=None,
param_file=None,
selector=None,
tuning_strategy=None,
inputs=None,
outputs=None,
in_path=None,
out_path=None,
artifact_path=None,
secrets=None,
base=None,
):
"""Creates a new task
:param name: task name
:param project: task project
:param handler code entry-point/hanfler name
:param params: input parameters (dict)
:param hyper_params: dictionary of hyper parameters and list values, each
hyper param holds a list of values, the run will be
executed for every parameter combination (GridSearch)
:param param_file: a csv file with parameter combinations, first row hold
the parameter names, following rows hold param values
:param selector: selection criteria for hyper params e.g. "max.accuracy"
:param tuning_strategy: selection strategy for hyper params e.g. list, grid, random
:param inputs: dictionary of input objects + optional paths (if path is
omitted the path will be the in_path/key.
:param outputs: dictionary of input objects + optional paths (if path is
omitted the path will be the out_path/key.
:param in_path: default input path/url (prefix) for inputs
:param out_path: default output path/url (prefix) for artifacts
:param artifact_path: default artifact output path
:param secrets: extra secrets specs, will be injected into the runtime
e.g. ['file=<filename>', 'env=ENV_KEY1,ENV_KEY2']
:param base: task instance to use as a base instead of a fresh new task instance
"""
if base:
run = deepcopy(base)
else:
run = RunTemplate()
run.metadata.name = name or run.metadata.name
run.metadata.project = project or run.metadata.project
run.spec.handler = handler or run.spec.handler
run.spec.parameters = params or run.spec.parameters
run.spec.hyperparams = hyper_params or run.spec.hyperparams
run.spec.param_file = param_file or run.spec.param_file
run.spec.tuning_strategy = tuning_strategy or run.spec.tuning_strategy
run.spec.selector = selector or run.spec.selector
run.spec.inputs = inputs or run.spec.inputs
run.spec.outputs = outputs or run.spec.outputs or []
run.spec.input_path = in_path or run.spec.input_path
run.spec.output_path = artifact_path or out_path or run.spec.output_path
run.spec.secret_sources = secrets or run.spec.secret_sources or []
return run