sdk.md 17.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!--
SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0

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.
-->

# Dynamo SDK

## Introduction

22
Dynamo is a flexible and performant distributed inferencing solution for large-scale deployments. It is an ecosystem of tools, frameworks, and abstractions that makes the design, customization, and deployment of frontier-level models onto datacenter-scale infrastructure easy to reason about and optimized for your specific inferencing workloads. Dynamo's core is written in Rust and contains a set of well-defined Python bindings. See [Python Bindings](./python_bindings.md).
23

24
Dynamo SDK is a layer on top of the core. It is a Python framework that makes it easy to create inference graphs and deploy them locally and onto a target K8s cluster. The SDK was heavily inspired by [BentoML's](https://github.com/bentoml/BentoML) open source deployment patterns. The Dynamo CLI is a companion tool that allows you to spin up an inference pipeline locally, containerize it, and deploy it. You can find a toy hello-world example and instructions for deploying it [here](../examples/hello_world.md).
25
26
27
28
29
30
31
32
33
34

## Installation

The SDK can be installed using pip:

```bash
pip install ai-dynamo
```

## Core Concepts
35

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
As you read about each concept, it is helpful to have the [basic example](../examples/hello_world.md) up as well so you can refer back to it.

### Defining a Service

A Service is a core building block for a project. You can think of it as a logical unit of work. For example, you might have a service responsible for preprocessing and tokenizing and another service running the model worker itself. You define a service using the `@service` decorator on a class.

```python
@service(
    dynamo={
        "namespace": "dynamo",
    },
    resources={"gpu": 2, "cpu": "10", "memory": "20Gi"},
    workers=1,
)
```

Key configuration options:
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
1. `dynamo`: Dictionary that defines the Dynamo configuration and enables/disables it. When enabled, a dynamo worker is created under the hood which can register with the [Distributed Runtime](../architecture/architecture.md)
2. `resources`: Dictionary defining resource requirements. The GPUs field is used for local and remote deployment. The other fields are used to determine resources when deploying to K8s.
3. `workers`: Number of parallel instances of the service to spin up.

### Writing a Service

Let's walk through an example to understand how you write a dynamo service.

```python
import ServiceB

@service(dynamo={"namespace": "dynamo"}, resources={"gpu": 1})
class ServiceA:
    # Define service dependencies
    service_b = depends(ServiceB)

    def __init__(self, model_name="meta-llama/Llama-3.1-8B-Instruct"):
        self.model_name = model_name
        self.engine = None

    @async_on_start
    async def async_init(self):
        # Initialize resources that require async operations
        self.engine = await initialize_model_engine(self.model_name)
        print(f"ServiceA initialized with model: {self.model_name}")

80
81
    @on_shutdown
    def shutdown(self):
82
83
        # Clean up resources
        if self.engine:
84
85
            self.engine.shutdown()
        print("ServiceA engine shut down")
86
87
88
89
90
91
92
93
94
95
96
97

    @endpoint()
    async def generate(self, request: ChatCompletionRequest):
        # Call dependent service
        processed_request = await self.service_b.preprocess(request)

        # Use the engine to generate a response
        response = await self.engine.generate(processed_request)
        return response
```

#### Class-Based Architecture
98

99
Dynamo follows a class-based architecture similar to BentoML making it intuitive for users familiar with those frameworks. Each service is defined as a Python class, with the following components:
100

101
102
1. Class attributes for dependencies using `depends()`
2. An `__init__` method for standard initialization
103
3. Optional lifecycle hooks like `@async_on_start` and `@on_shutdown`
104
105
106
107
108
109
110
4. Endpoints defined with `@endpoint()`. Optionally, an endpoint can be given a name
   via `@endpoint("my_endpoint_name")`, but otherwise defaults to the name of the
   function being decorated if omitted.

This approach provides a clean separation of concerns and makes the service structure easy to understand.

#### Service Dependencies with `depends()`
111

112
The `depends()` function is a powerful feature that lets you create a dependency between services. When you use `depends(ServiceB)`, several things happen:
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
1. It ensures that `ServiceB` is deployed when `ServiceA` is deployed by adding it to an internal service dependency graph
2. It creates a client to the endpoints of `ServiceB` that is being served under the hood.
3. You are able to access `ServiceB` endpoints as if it were a local function!

```python
# What happens internally when you use depends(ServiceB)
service_b = await runtime.namespace("dynamo").component("ServiceB").endpoint("preprocess").client()

# But with Dynamo SDK, you simply write:
service_b = depends(ServiceB)

# And then call methods directly:
result = await service_b.preprocess(data)
```

```{note}
Through the SDK, we also provide you with a way to access the underlying bindings if you need. Sometimes you might want to write complicated logic that causes you to directly create a client to another Service without depending on it. To do so:
```

```python
import VllmWorker

# this runtime object gives you access to the underlying python bindings
runtime = dynamo_context["runtime"]
comp_ns, comp_name = VllmWorker.dynamo_address() # dynamo://{namespace}/{name}
print(f"[Processor] comp_ns: {comp_ns}, comp_name: {comp_name}")
self.worker_client = (
    await runtime.namespace(comp_ns)
    .component(comp_name)
    .endpoint("generate")
    .client()
)
```

This is used in some of our prebuilt examples and is a powerful way to leverage the benefits of the SDK while being able to access Dynamo's core primitives.

#### Lifecycle Hooks
151

152
Dynamo supports key lifecycle hooks to manage service initialization and cleanup.
153
154
155
156
157
158
159
160
161
162
163
164
165

##### `@async_on_start`

The `@async_on_start` hook is called when the service is started and is used to run an async process outside of the main `__init__` function.

```python
@async_on_start
async def async_init(self):
    # Perfect for operations that need to be awaited
    self.db = await connect_to_db()
    self.tokenizer = await load_tokenizer()
    self.engine = await initialize_engine(self.model)
```
166

167
This is especially useful for:
168

169
170
171
- Initializing external connections
- Setting up runtime resources that require async operations

172
#### `@on_shutdown`
173

174
The `@on_shutdown` hook is called when the service is shutdown handles cleanup.
175
176

```python
177
178
179
180
@on_shutdown
def shutdown(self):
    # gracefully Handle shutdown / cleanup
    logger.info("worker shutting down")
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
```

This ensures resources are properly released, preventing memory leaks and making sure external connections are properly closed. This is helpful to clean up vLLM engines that have been started outside of the main process.

### Configuring a Service

Dynamo SDK provides a flexible configuration system that allows you to define service parameters through multiple methods:

1. Directly in the `@service` decorator
2. Through YAML configuration files
3. Via command-line arguments
4. Using environment variables

These methods can be used together with clear precedence rules, giving you fine-grained control over service configuration across different environments.

#### Configuration via Service Decorator

The most basic method is to specify parameters directly in the service decorator:

```python
@service(
    dynamo={"namespace": "prod"},
    resources={"gpu": 2, "cpu": "4", "memory": "16Gi"},
    workers=2,
)
class MyService:
    def __init__(self, model_name="deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B", temperature=0.7):
        self.model_name = model_name
        self.temperature = temperature
```

This defines static configuration values in code. Note that the constructor parameters (`model_name` and `temperature`) are also configurable values that can be overridden.

#### Configuration via YAML

For more flexible configuration, especially across environments, you can use YAML files:

```yaml
# config.yaml
MyService:
  # Override service decorator settings
  ServiceArgs:
    workers: 4
    resources:
      gpu: 4

  # Service instance parameters
  model_name: "deepseek-ai/DeepSeek-R1-Distill-Llama-8B"
  temperature: 0.8
```

The YAML file has a hierarchical structure:
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
- Top level keys are service class names
- `ServiceArgs` contains parameters for the service decorator
- Other keys are passed as arguments to the service constructor
- Additional keys specific to the service can be accessed via the config system

#### Loading YAML Configuration

Use the CLI to load configuration from a YAML file:

```bash
dynamo serve service:MyService -f config.yaml
```

The configuration is parsed and stored in the `DYNAMO_SERVICE_CONFIG` environment variable, which is then passed to the service workers.

#### Configuration Precedence

When multiple configuration sources are used, they follow this precedence order (highest to lowest):

1. Command-line arguments
2. YAML configuration
3. Service decorator defaults
4. Constructor defaults

#### Accessing Configuration in Services

Inside a service, you can access configuration using the `ServiceConfig` class:

```python
from dynamo.sdk.lib.config import ServiceConfig

class MyService:
    def __init__(self):
        config = ServiceConfig.get_instance()

        # Get with default value
        self.model_name = config.get("MyService", {}).get("model_name", "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B")
        self.temperature = config.get("MyService", {}).get("temperature", 0.7)

        # Require a config value (raises error if missing)
        self.api_key = config.require("MyService", "api_key")

        # Get all config for this service
        all_my_config = config.get("MyService", {})
```

#### Parsing Configuration as CLI Arguments

For services that need to extract their configuration as command-line arguments (common when integrating and validating with external libraries), the SDK provides a helper method:

```python
from dynamo.sdk.lib.config import ServiceConfig

def setup_my_lib():
    config = ServiceConfig.get_instance()

    # Get all MyService config with prefix "lib_" as CLI args
    cli_args = config.as_args("MyService", prefix="lib_")
    # Returns: ["--option1", "value1", "--flag2", "--option3", "value3"]

    # Pass to an external library's argument parser
    lib_parser = MyLibArgumentParser()
    lib_args = lib_parser.parse_args(cli_args)
    return lib_args
```

This pattern is used in the example vLLM integration:

```python
def parse_vllm_args(service_name, prefix) -> AsyncEngineArgs:
    config = ServiceConfig.get_instance()
    vllm_args = config.as_args(service_name, prefix=prefix)
    parser = FlexibleArgumentParser()

    # Add custom arguments
    parser.add_argument("--router", type=str, choices=["random", "round-robin", "kv"], default="random")
    parser.add_argument("--remote-prefill", action="store_true")

    # Add VLLM's arguments
    parser = AsyncEngineArgs.add_cli_args(parser)

    # Parse both custom and VLLM arguments
    args = parser.parse_args(vllm_args)

    # Convert to engine arguments
    engine_args = AsyncEngineArgs.from_cli_args(args)

    # Add custom args to the engine args
    engine_args.router = args.router
    engine_args.remote_prefill = args.remote_prefill

    return engine_args
```

#### Overriding Service Decorator with ServiceArgs

The `ServiceArgs` section in YAML configuration allows you to override any parameter in the `@service` decorator:

```yaml
MyService:
  ServiceArgs:
    dynamo:
336
      namespace: "staging" # Override namespace
337
    resources:
338
339
      gpu: 4 # Use more GPUs
    workers: 8 # Scale up workers
340
341
342
```

This is particularly useful for:
343

344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
- Changing resource allocations between environments
- Modifying worker counts based on expected load
- Switching between namespaces for different deployments

Under the hood, the `DynamoService` class reads these arguments during initialization:

```python
def _get_service_args(self, service_name: str) -> Optional[dict]:
    """Get ServiceArgs from environment config if specified"""
    config_str = os.environ.get("DYNAMO_SERVICE_CONFIG")
    if config_str:
        config = json.loads(config_str)
        service_config = config.get(service_name, {})
        return service_config.get("ServiceArgs")
    return None
```
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
#### Complete Configuration Example

Here's a comprehensive example showing how all these pieces fit together:

1. First, define your service with basic defaults:

```python
@service(
    dynamo={"namespace": "default"},
    resources={"gpu": 1},
    workers=1,
)
class LLMService:
    def __init__(self, model_name="gpt-2", temperature=0.7, max_tokens=1024):
        self.model_name = model_name
        self.temperature = temperature
        self.max_tokens = max_tokens

        # Get additional configuration
        config = ServiceConfig.get_instance()
        service_config = config.get("LLMService", {})

        # Extract service-specific parameters
        self.cache_size = service_config.get("cache_size", 1000)
        self.use_kv_cache = service_config.get("use_kv_cache", True)
```

2. Create a YAML configuration for production:

```yaml
# prod_config.yaml
LLMService:
  ServiceArgs:
    dynamo:
      namespace: "prod"
    resources:
      gpu: 4
      memory: "64Gi"
    workers: 8

  # Constructor parameters
  model_name: "llama-3-70b-instruct"
  temperature: 0.8
  max_tokens: 2048

  # Service-specific parameters
  cache_size: 10000
  use_kv_cache: true
```

3. Deploy with mixed configuration:

```bash
dynamo serve service:LLMService -f prod_config.yaml --LLMService.temperature=0.9
```

The service receives the combined configuration with the command-line value taking precedence, resulting in effective configuration of:
418

419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
- `dynamo.namespace = "prod"`
- `resources.gpu = 4`
- `workers = 8`
- `model_name = "llama-3-70b-instruct"`
- `temperature = 0.9` (from CLI override)
- `max_tokens = 2048`
- `cache_size = 10000`
- `use_kv_cache = true`

#### Service Configuration Best Practices

1. **Use the Service Decorator for Defaults**: Put reasonable defaults in the service decorator
2. **Use Constructor Parameters for Runtime Options**: Parameters that might change between deployments
3. **Use YAML for Environment Configuration**: Separate configuration by environment (dev/staging/prod)
4. **Use CLI for Quick Testing**: Override specific values for experimentation
5. **Document Configuration Keys**: Make sure to document all available configuration options

Following these practices help create flexible and maintainable Dynamo services that can be easily configured for different environments and use cases.

### Deploying a Single Service
439
440

You can deploy a single service for local development even if you have a dependency graph defined using `depends()` using `dynamo serve --service-name <ClassName> <entrypoint> <configuration arguments>`. You can see an example of this in our multinode documentation [here](../examples/multinode.md).
441
442

### Composing Services into an Graph
443

444
There are two main ways to compose services in Dynamo:
445

446
1. Use `depends()` (Recommended)
447
448
   The depends() approach is the recommended way for production deployments:

449
450
451
452
453
- Automatically deploys all dependencies
- Creates a static inference graph at deployment time
- Provides type hints and better IDE support

2. Use `.link()` (Experimental)
454
   Our `.link()` syntax is an flexible and experimental way to compose various services. Linking allows you to compose checks at runtime and view behavior. Under the hood - we are editing the dependency graph between various services. This is useful for experimentation and development but we suggest writing a static graph for your final production deployment.
455
456

#### Understanding the `.link()` syntax
457

458
Lets take the example of a `Processor` component. This component can currently do 2 things:
459

460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
1. Process a request and send it to a `Router` to decide what worker to send it to.
2. Process a request and send it to a `Worker` directly.

Consider this snippet of the Processor:

```python
class Processor(ProcessMixIn):
    """
    vLLM pre and post processing
    """

    worker = depends(VllmWorker)
    router = depends(Router)

    # logic for processing a request based on router or worker
```

Think of all the depends statements as the maximal set of edges for the processor. At runtime, you may want to follow only a single path. By default, our processor spins up both the VllmWorker and Router as separate services (because `depends()` is defined for both). However, if you want to only spin up the Router, you can do this by linking the Router to the Processor that removes the `worker` dependency from the Processor.

```python
Processor.link(Router)
```

483
This removes the `worker` dependency from the Processor and only spin up the Router.