-
Notifications
You must be signed in to change notification settings - Fork 239
/
serving.py
508 lines (432 loc) · 19.1 KB
/
serving.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
# 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 json
from typing import List, Union
import nuclio
import mlrun
from ..model import ObjectList
from ..secrets import SecretsStore
from ..serving.server import GraphServer, create_graph_server
from ..serving.states import (
RootFlowStep,
RouterStep,
StepKinds,
graph_root_setter,
new_model_endpoint,
new_remote_endpoint,
)
from ..utils import get_caller_globals, logger
from .function import NuclioSpec, RemoteRuntime
from .function_reference import FunctionReference
serving_subkind = "serving_v2"
def new_v2_model_server(
name,
model_class: str,
models: dict = None,
filename="",
protocol="",
image="",
endpoint="",
workers=8,
canary=None,
):
f = ServingRuntime()
if not image:
name, spec, code = nuclio.build_file(
filename, name=name, handler="handler", kind=serving_subkind
)
f.spec.base_spec = spec
f.metadata.name = name
f.spec.default_class = model_class
params = None
if protocol:
params = {"protocol": protocol}
if models:
for name, model_path in models.items():
f.add_model(name, model_path=model_path, parameters=params)
f.with_http(workers, host=endpoint, canary=canary)
if image:
f.from_image(image)
return f
class ServingSpec(NuclioSpec):
def __init__(
self,
command=None,
args=None,
image=None,
mode=None,
entry_points=None,
description=None,
replicas=None,
min_replicas=None,
max_replicas=None,
volumes=None,
volume_mounts=None,
env=None,
resources=None,
config=None,
base_spec=None,
no_cache=None,
source=None,
image_pull_policy=None,
function_kind=None,
service_account=None,
readiness_timeout=None,
models=None,
graph=None,
parameters=None,
default_class=None,
load_mode=None,
build=None,
function_refs=None,
graph_initializer=None,
error_stream=None,
track_models=None,
secret_sources=None,
default_content_type=None,
):
super().__init__(
command=command,
args=args,
image=image,
mode=mode,
entry_points=entry_points,
description=description,
replicas=replicas,
min_replicas=min_replicas,
max_replicas=max_replicas,
volumes=volumes,
volume_mounts=volume_mounts,
env=env,
resources=resources,
config=config,
base_spec=base_spec,
no_cache=no_cache,
source=source,
image_pull_policy=image_pull_policy,
function_kind=serving_subkind,
service_account=service_account,
readiness_timeout=readiness_timeout,
build=build,
)
self.models = models or {}
self._graph = None
self.graph: Union[RouterStep, RootFlowStep] = graph
self.parameters = parameters or {}
self.default_class = default_class
self.load_mode = load_mode
self._function_refs: ObjectList = None
self.function_refs = function_refs or []
self.graph_initializer = graph_initializer
self.error_stream = error_stream
self.track_models = track_models
self.secret_sources = secret_sources or []
self.default_content_type = default_content_type
@property
def graph(self) -> Union[RouterStep, RootFlowStep]:
"""states graph, holding the serving workflow/DAG topology"""
return self._graph
@graph.setter
def graph(self, graph):
graph_root_setter(self, graph)
@property
def function_refs(self) -> List[FunctionReference]:
"""function references, list of optional child function refs"""
return self._function_refs
@function_refs.setter
def function_refs(self, function_refs: List[FunctionReference]):
self._function_refs = ObjectList.from_list(FunctionReference, function_refs)
class ServingRuntime(RemoteRuntime):
"""MLRun Serving Runtime"""
kind = "serving"
@property
def spec(self) -> ServingSpec:
return self._spec
@spec.setter
def spec(self, spec):
self._spec = self._verify_dict(spec, "spec", ServingSpec)
def set_topology(
self, topology=None, class_name=None, engine=None, exist_ok=False, **class_args,
) -> Union[RootFlowStep, RouterStep]:
"""set the serving graph topology (router/flow) and root class or params
example::
graph = fn.set_topology("flow", engine="async")
graph.to("MyClass").to(name="to_json", handler="json.dumps").respond()
topology options are::
router - root router + multiple child route states/models
route is usually determined by the path (route key/name)
can specify special router class and router arguments
flow - workflow (DAG) with a chain of states
flow support "sync" and "async" engines, branches are not allowed in sync mode
when using async mode calling state.respond() will mark the state as the
one which generates the (REST) call response
:param topology: - graph topology, router or flow
:param class_name: - optional for router, router class name/path
:param engine: - optional for flow, sync or async engine (default to async)
:param exist_ok: - allow overriding existing topology
:param class_args: - optional, router/flow class init args
:return graph object (fn.spec.graph)
"""
topology = topology or StepKinds.router
if self.spec.graph and not exist_ok:
raise mlrun.errors.MLRunInvalidArgumentError(
"graph topology is already set, cannot be overwritten"
)
if topology == StepKinds.router:
self.spec.graph = RouterStep(class_name=class_name, class_args=class_args)
elif topology == StepKinds.flow:
self.spec.graph = RootFlowStep(engine=engine)
else:
raise mlrun.errors.MLRunInvalidArgumentError(
f"unsupported topology {topology}, use 'router' or 'flow'"
)
return self.spec.graph
def set_tracking(
self,
stream_path: str = None,
batch: int = None,
sample: int = None,
stream_args: dict = None,
):
"""set tracking stream parameters:
:param stream_path: path/url of the tracking stream e.g. v3io:///users/mike/mystream
you can use the "dummy://" path for test/simulation
:param batch: micro batch size (send micro batches of N records at a time)
:param sample: sample size (send only one of N records)
:param stream_args: stream initialization parameters, e.g. shards, retention_in_hours, ..
"""
self.spec.track_models = True
if stream_path:
self.spec.parameters["log_stream"] = stream_path
if batch:
self.spec.parameters["log_stream_batch"] = batch
if sample:
self.spec.parameters["log_stream_sample"] = sample
if stream_args:
self.spec.parameters["stream_args"] = stream_args
def add_model(
self,
key,
model_path=None,
class_name=None,
model_url=None,
handler=None,
**class_args,
):
"""add ml model and/or route to the function.
Example, create a function (from the notebook), add a model class, and deploy::
fn = code_to_function(kind='serving')
fn.add_model('boost', model_path, model_class='MyClass', my_arg=5)
fn.deploy()
only works with router topology, for nested topologies (model under router under flow)
need to add router to flow and use router.add_route()
:param key: model api key (or name:version), will determine the relative url/path
:param model_path: path to mlrun model artifact or model directory file/object path
:param class_name: V2 Model python class name
(can also module.submodule.class and it will be imported automatically)
:param model_url: url of a remote model serving endpoint (cannot be used with model_path)
:param handler: for advanced users!, override default class handler name (do_event)
:param class_args: extra kwargs to pass to the model serving class __init__
(can be read in the model using .get_param(key) method)
"""
graph = self.spec.graph
if not graph:
graph = self.set_topology()
if graph.kind != StepKinds.router:
raise ValueError("models can only be added under router state")
if not model_path and not model_url:
raise ValueError("model_path or model_url must be provided")
class_name = class_name or self.spec.default_class
if class_name and not isinstance(class_name, str):
raise ValueError(
"class name must be a string (name of module.submodule.name)"
)
if model_path and not class_name:
raise ValueError("model_path must be provided with class_name")
if model_path:
model_path = str(model_path)
if model_url:
state = new_remote_endpoint(model_url, **class_args)
else:
state = new_model_endpoint(class_name, model_path, handler, **class_args)
return graph.add_route(key, state)
def add_child_function(
self, name, url=None, image=None, requirements=None, kind=None
):
"""in a multi-function pipeline add child function
example::
fn.add_child_function('enrich', './enrich.ipynb', 'mlrun/mlrun')
:param name: child function name
:param url: function/code url, support .py, .ipynb, .yaml extensions
:param image: base docker image for the function
:param requirements: py package requirements file path OR list of packages
:param kind: mlrun function/runtime kind
:return function object
"""
function_reference = FunctionReference(
url, image, requirements=requirements, kind=kind or "serving"
)
self._spec.function_refs.update(function_reference, name)
func = function_reference.to_function(self.kind)
func.set_env("SERVING_CURRENT_FUNCTION", function_reference.name)
return func
def _add_ref_triggers(self):
"""add stream trigger to downstream child functions"""
for function_name, stream in self.spec.graph.get_queue_links().items():
if stream.path:
if function_name not in self._spec.function_refs.keys():
raise ValueError(f"function reference {function_name} not present")
group = stream.options.get("group", "serving")
child_function = self._spec.function_refs[function_name]
child_function.function_object.add_v3io_stream_trigger(
stream.path, group=group, shards=stream.shards
)
def _deploy_function_refs(self):
"""set metadata and deploy child functions"""
for function_ref in self._spec.function_refs.values():
logger.info(f"deploy child function {function_ref.name} ...")
function_object = function_ref.function_object
function_object.metadata.name = function_ref.fullname(self)
function_object.metadata.project = self.metadata.project
function_object.metadata.tag = self.metadata.tag
function_object.spec.graph = self.spec.graph
# todo: may want to copy parent volumes to child functions
function_object.apply(mlrun.v3io_cred())
function_ref.db_uri = function_object._function_uri()
function_object.verbose = self.verbose
function_object.spec.secret_sources = self.spec.secret_sources
function_object.deploy()
def remove_states(self, keys: list):
"""remove one, multiple, or all states/models from the spec (blank list for all)"""
if self.spec.graph:
self.spec.graph.clear_children(keys)
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, example::
task.with_secrets('file', 'file.txt')
task.with_secrets('inline', {'key': 'val'})
task.with_secrets('env', 'ENV1,ENV2')
task.with_secrets('vault', ['secret1', 'secret2'...])
# If using an empty secrets list [] then all accessible secrets will be available.
task.with_secrets('vault', [])
# To use with Azure key vault, a k8s secret must be created with the following keys:
# kubectl -n <namespace> create secret generic azure-key-vault-secret \\
# --from-literal=tenant_id=<service principal tenant ID> \\
# --from-literal=client_id=<service principal client ID> \\
# --from-literal=secret=<service principal secret key>
task.with_secrets('azure_vault', {
'name': 'my-vault-name',
'k8s_secret': 'azure-key-vault-secret',
# An empty secrets list may be passed ('secrets': []) to access all vault secrets.
'secrets': ['secret1', 'secret2'...]
})
:param kind: secret type (file, inline, env)
:param source: secret data or link (see example)
:returns: The Runtime (function) object
"""
if kind == "vault" and isinstance(source, list):
source = {"project": self.metadata.project, "secrets": source}
self.spec.secret_sources.append({"kind": kind, "source": source})
return self
def add_secrets_config_to_spec(self):
if self.spec.secret_sources:
self._secrets = SecretsStore.from_list(self.spec.secret_sources)
if self._secrets.has_vault_source():
self._add_vault_params_to_spec(project=self.metadata.project)
if self._secrets.has_azure_vault_source():
self._add_azure_vault_params_to_spec(
self._secrets.get_azure_vault_k8s_secret()
)
k8s_secrets = self._secrets.get_k8s_secrets()
if k8s_secrets:
self._add_project_k8s_secrets_to_spec(
k8s_secrets, project=self.metadata.project
)
def deploy(self, dashboard="", project="", tag="", verbose=False):
"""deploy model serving function to a local/remote cluster
:param dashboard: remote nuclio dashboard url (blank for local or auto detection)
:param project: optional, override function specified project name
:param tag: specify unique function tag (a different function service is created for every tag)
:param verbose: verbose logging
"""
load_mode = self.spec.load_mode
if load_mode and load_mode not in ["sync", "async"]:
raise ValueError(f"illegal model loading mode {load_mode}")
if not self.spec.graph:
raise ValueError("nothing to deploy, .spec.graph is none, use .add_model()")
if self.spec.graph.kind != StepKinds.router:
# initialize or create required streams/queues
self.spec.graph.check_and_process_graph()
self.spec.graph.init_queues()
# Handle secret processing before handling child functions, since secrets are transferred to them
if self.spec.secret_sources:
# Before passing to remote builder, secrets values must be retrieved (for example from ENV)
# and stored as inline secrets. Otherwise, they will not be available to the builder.
self._secrets = SecretsStore.from_list(self.spec.secret_sources)
self.spec.secret_sources = self._secrets.to_serial()
if self._spec.function_refs:
# deploy child functions
self._add_ref_triggers()
self._deploy_function_refs()
logger.info(f"deploy root function {self.metadata.name} ...")
return super().deploy(dashboard, project, tag, verbose=verbose)
def _get_runtime_env(self):
env = super()._get_runtime_env()
function_name_uri_map = {f.name: f.uri(self) for f in self.spec.function_refs}
serving_spec = {
"function_uri": self._function_uri(),
"version": "v2",
"parameters": self.spec.parameters,
"graph": self.spec.graph.to_dict() if self.spec.graph else {},
"load_mode": self.spec.load_mode,
"functions": function_name_uri_map,
"graph_initializer": self.spec.graph_initializer,
"error_stream": self.spec.error_stream,
"track_models": self.spec.track_models,
"default_content_type": self.spec.default_content_type,
}
if self.spec.secret_sources:
self._secrets = SecretsStore.from_list(self.spec.secret_sources)
serving_spec["secret_sources"] = self._secrets.to_serial()
env["SERVING_SPEC_ENV"] = json.dumps(serving_spec)
return env
def to_mock_server(
self, namespace=None, current_function="*", **kwargs
) -> GraphServer:
"""create mock server object for local testing/emulation
:param namespace: classes search namespace, use globals() for current notebook
:param log_level: log level (error | info | debug)
:param current_function: specify if you want to simulate a child function, * for all functions
"""
server = create_graph_server(
parameters=self.spec.parameters,
load_mode=self.spec.load_mode,
graph=self.spec.graph,
verbose=self.verbose,
current_function=current_function,
graph_initializer=self.spec.graph_initializer,
track_models=self.spec.track_models,
function_uri=self._function_uri(),
secret_sources=self.spec.secret_sources,
default_content_type=self.spec.default_content_type,
**kwargs,
)
server.init_states(
context=None,
namespace=namespace or get_caller_globals(),
logger=logger,
is_mock=True,
)
server.init_object(namespace or get_caller_globals())
return server