"launch/dynamo-run/README.md" did not exist on "c70de37fcb50559ecd051df140db38250077c245"
hello_world.py 4.26 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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.

16
import logging
17
import os
18

19
from fastapi.responses import StreamingResponse
20
21
from pydantic import BaseModel

22
from dynamo.runtime.logging import configure_dynamo_logging
23
from dynamo.sdk import DYNAMO_IMAGE, depends, dynamo_api, dynamo_endpoint, service
24
from dynamo.sdk.lib.config import ServiceConfig
25

26
27
logger = logging.getLogger(__name__)

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
"""
Pipeline Architecture:

Users/Clients (HTTP)


┌─────────────┐
│  Frontend   │  HTTP API endpoint (/generate)
└─────────────┘
      │ dynamo/runtime

┌─────────────┐
│   Middle    │
└─────────────┘
      │ dynamo/runtime

┌─────────────┐
│  Backend    │
└─────────────┘
"""


class RequestType(BaseModel):
    text: str


class ResponseType(BaseModel):
    text: str


@service(
    dynamo={
        "namespace": "inference",
    },
63
    image=DYNAMO_IMAGE,
64
65
66
)
class Backend:
    def __init__(self) -> None:
67
        logger.info("Starting backend")
68
69
70
        config = ServiceConfig.get_instance()
        self.message = config.get("Backend", {}).get("message", "back")
        logger.info(f"Backend config message: {self.message}")
71
72
73
74
75

    @dynamo_endpoint()
    async def generate(self, req: RequestType):
        """Generate tokens."""
        req_text = req.text
76
        logger.info(f"Backend received: {req_text}")
77
        text = f"{req_text}-{self.message}"
78
        for token in text.split():
79
            yield f"[process_id:{os.getpid()}] Backend: {token}"
80
81
82


@service(
83
    dynamo={"namespace": "inference"},
84
    image=DYNAMO_IMAGE,
85
86
87
88
89
)
class Middle:
    backend = depends(Backend)

    def __init__(self) -> None:
90
        logger.info("Starting middle")
91
92
93
        config = ServiceConfig.get_instance()
        self.message = config.get("Middle", {}).get("message", "mid")
        logger.info(f"Middle config message: {self.message}")
94
95
96
97
98

    @dynamo_endpoint()
    async def generate(self, req: RequestType):
        """Forward requests to backend."""
        req_text = req.text
99
        logger.info(f"Middle received: {req_text}")
100
        text = f"{req_text}-{self.message}"
101
102
        next_request = RequestType(text=text).model_dump_json()
        async for response in self.backend.generate(next_request):
103
            logger.info(f"Middle received response: {response}")
104
            yield f"[process_id:{os.getpid()}] Middle: {response}"
105
106


107
@service(
108
    dynamo={"namespace": "inference"},
109
    image=DYNAMO_IMAGE,
110
)
111
class Frontend:
112
113
    """A simple frontend HTTP API that forwards requests to the dynamo graph."""

114
115
116
    middle = depends(Middle)

    def __init__(self) -> None:
117
        # Configure logging
118
        configure_dynamo_logging(service_name="Frontend")
119

120
121
122
123
124
125
        logger.info("Starting frontend")
        config = ServiceConfig.get_instance()
        self.message = config.get("Frontend", {}).get("message", "front")
        self.port = config.get("Frontend", {}).get("port", 8000)
        logger.info(f"Frontend config message: {self.message}")
        logger.info(f"Frontend config port: {self.port}")
126

127
128
    # alternative syntax: @dynamo_endpoint(transports=[DynamoTransport.HTTP])
    @dynamo_api()
129
    async def generate(self, request: RequestType):
130
        """Stream results from the pipeline."""
131
132
133
134
        logger.info(f"Frontend received: {request.text}")

        async def content_generator():
            async for response in self.middle.generate(request.model_dump_json()):
135
                yield f"[process_id:{os.getpid()}] Frontend: {response}"
136
137

        return StreamingResponse(content_generator())