Skip to main content

Model Serving made Efficient in the Cloud

Reason this release was yanked:

potential deadlock when too many disconnects

Project description

MOSEC

discord invitation link PyPI version Python Version PyPi Downloads License Check status

Model Serving made Efficient in the Cloud.

Introduction

Mosec is a high-performance and flexible model serving framework for building ML model-enabled backend and microservices. It bridges the gap between any machine learning models you just trained and the efficient online service API.

  • Highly performant: web layer and task coordination built with Rust 🦀, which offers blazing speed in addition to efficient CPU utilization powered by async I/O
  • Ease of use: user interface purely in Python 🐍, by which users can serve their models in an ML framework-agnostic manner using the same code as they do for offline testing
  • Dynamic batching: aggregate requests from different users for batched inference and distribute results back
  • Pipelined stages: spawn multiple processes for pipelined stages to handle CPU/GPU/IO mixed workloads
  • Cloud friendly: designed to run in the cloud, with the model warmup, graceful shutdown, and Prometheus monitoring metrics, easily managed by Kubernetes or any container orchestration systems
  • Do one thing well: focus on the online serving part, users can pay attention to the model optimization and business logic

Installation

Mosec requires Python 3.7 or above. Install the latest PyPI package with:

pip install -U mosec

Usage

Write the server

Import the libraries and set up a basic logger to better observe what happens.

from io import BytesIO
from typing import List

import torch  # type: ignore
from diffusers import StableDiffusionPipeline  # type: ignore

from mosec import Server, Worker, get_logger
from mosec.mixin import MsgpackMixin

logger = get_logger()

Then, we build an API to generate the images for a given prompt. To achieve that, we simply inherit the MsgpackMixin and Worker class, then override the forward method. Note that the input data is by default a JSON-decoded object, but MsgpackMixin will override it to use msgpack for the request and response data, e.g., wishfully it receives data like [b'a cut cat playing with a red ball']. Noted that the returned objects will also be encoded by the MsgpackMixin.

class StableDiffusion(MsgpackMixin, Worker):
    def __init__(self):
        """Init the model for inference."""
        self.pipe = StableDiffusionPipeline.from_pretrained(
            "runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16
        )
        self.pipe = self.pipe.to("cuda")

    def forward(self, data: List[str]) -> List[memoryview]:
        """Override the forward process."""
        logger.debug("generate images for %s", data)
        res = self.pipe(data)
        logger.debug("NSFW: %s", res[1])
        images = []
        for img in res[0]:
            dummy_file = BytesIO()
            img.save(dummy_file, format="JPEG")
            images.append(dummy_file.getbuffer())
        # need to return the same number of images in the same request order
        # `len(data) == len(images)`
        return images

Finally, we append the worker to the server to construct a single-stage workflow, and specify the number of processes we want it to run in parallel. Then run the server.

if __name__ == "__main__":
    server = Server()
    # by configuring the `max_batch_size` with the value >= 1, the input data in your `forward` function will be a batch
    # otherwise, it's a single item
    server.append_worker(StableDiffusion, num=1, max_batch_size=16)
    server.run()

Run the server

After merging the snippets above into a file named server.py, we can first have a look at the command line arguments:

python examples/stable_diffusion/server.py --help

Then let's start the server with debug logs:

python examples/stable_diffusion/server.py --debug

And in another terminal, test it:

python examples/stable_diffusion/client.py --prompt "a cut cat playing with a red ball" --output cat.jpg --port 8000

You will get an image named "cat.jpg" in the current directory.

You can check the metrics:

curl http://127.0.0.1:8000/metrics

That's it! You have just hosted your stable-diffusion model as a server! 😉

Examples

More ready-to-use examples can be found in the Example section. It includes:

Configuration

  • Dynamic batching
    • max_batch_size is configured when you append_worker (make sure inference with the max value won't cause the out-of-memory in GPU)
    • --wait (default=10ms) is configured through CLI arguments (this usually should <= one batch inference duration)
    • If enabled, it will collect a batch either when it reaches the max_batch_size or the wait time.
  • Check the arguments doc.

Deployment

  • This may require some shared memory, remember to set the --shm-size flag if you are using docker.
  • This service doesn't require Gunicorn or NGINX, but you can certainly use the ingress controller. BTW, it should be the PID 1 process in the container since it controls multiple processes.
  • Remember to collect the metrics.
    • mosec_service_batch_size_bucket shows the batch size distribution.
    • mosec_service_process_duration_second_bucket shows the duration for each stage (excluding the IPC time).
    • mosec_service_remaining_task shows the number of currently processing tasks
    • mosec_service_throughput shows the service throughput
  • Stop the service with SIGINT or SIGTERM since it has the graceful shutdown logic.

Contributing

We welcome any kind of contribution. Please give us feedback by raising issues or discussing on Discord. You could also directly contribute your code and pull request!

To start develop, you can use envd to create an isolated and clean Python & Rust environment. Check the envd-docs or build.envd for more information.

Qualitative Comparison*

Batcher Pipeline Parallel I/O Format(1) Framework(2) Backend Activity
TF Serving Limited(a) Heavily TF C++
Triton Limited Multiple C++
MMS Limited Heavily MX Java
BentoML Limited(b) Multiple Python
Streamer Customizable Agnostic Python
Flask(3) Customizable Agnostic Python
Mosec Customizable Agnostic Rust

*As accessed on 08 Oct 2021. By no means is this comparison showing that other frameworks are inferior, but rather it is used to illustrate the trade-off. The information is not guaranteed to be absolutely accurate. Please let us know if you find anything that may be incorrect.

(1): Data format of the service's request and response. "Limited" in the sense that the framework has pre-defined requirements on the format. (2): Supported machine learning frameworks. "Heavily" means the serving framework is designed towards a specific ML framework. Thus it is hard, if not impossible, to adapt to others. "Multiple" means the serving framework provides adaptation to several existing ML frameworks. "Agnostic" means the serving framework does not necessarily care about the ML framework. Hence it supports all ML frameworks (in Python). (3): Flask is a representative of general purpose web frameworks to host ML models.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mosec-0.5.1.tar.gz (56.2 kB view hashes)

Uploaded Source

Built Distributions

mosec-0.5.1-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.4 MB view hashes)

Uploaded PyPy manylinux: glibc 2.17+ x86-64

mosec-0.5.1-pp39-pypy39_pp73-macosx_10_9_x86_64.whl (1.4 MB view hashes)

Uploaded PyPy macOS 10.9+ x86-64

mosec-0.5.1-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.4 MB view hashes)

Uploaded PyPy manylinux: glibc 2.17+ x86-64

mosec-0.5.1-pp38-pypy38_pp73-macosx_10_9_x86_64.whl (1.4 MB view hashes)

Uploaded PyPy macOS 10.9+ x86-64

mosec-0.5.1-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.4 MB view hashes)

Uploaded PyPy manylinux: glibc 2.17+ x86-64

mosec-0.5.1-pp37-pypy37_pp73-macosx_10_9_x86_64.whl (1.4 MB view hashes)

Uploaded PyPy macOS 10.9+ x86-64

mosec-0.5.1-cp311-cp311-musllinux_1_1_x86_64.whl (2.5 MB view hashes)

Uploaded CPython 3.11 musllinux: musl 1.1+ x86-64

mosec-0.5.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.4 MB view hashes)

Uploaded CPython 3.11 manylinux: glibc 2.17+ x86-64

mosec-0.5.1-cp311-cp311-macosx_10_9_x86_64.whl (1.4 MB view hashes)

Uploaded CPython 3.11 macOS 10.9+ x86-64

mosec-0.5.1-cp310-cp310-musllinux_1_1_x86_64.whl (2.5 MB view hashes)

Uploaded CPython 3.10 musllinux: musl 1.1+ x86-64

mosec-0.5.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.4 MB view hashes)

Uploaded CPython 3.10 manylinux: glibc 2.17+ x86-64

mosec-0.5.1-cp310-cp310-macosx_10_9_x86_64.whl (1.4 MB view hashes)

Uploaded CPython 3.10 macOS 10.9+ x86-64

mosec-0.5.1-cp39-cp39-musllinux_1_1_x86_64.whl (2.5 MB view hashes)

Uploaded CPython 3.9 musllinux: musl 1.1+ x86-64

mosec-0.5.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.4 MB view hashes)

Uploaded CPython 3.9 manylinux: glibc 2.17+ x86-64

mosec-0.5.1-cp39-cp39-macosx_10_9_x86_64.whl (1.4 MB view hashes)

Uploaded CPython 3.9 macOS 10.9+ x86-64

mosec-0.5.1-cp38-cp38-musllinux_1_1_x86_64.whl (2.5 MB view hashes)

Uploaded CPython 3.8 musllinux: musl 1.1+ x86-64

mosec-0.5.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.4 MB view hashes)

Uploaded CPython 3.8 manylinux: glibc 2.17+ x86-64

mosec-0.5.1-cp38-cp38-macosx_10_9_x86_64.whl (1.4 MB view hashes)

Uploaded CPython 3.8 macOS 10.9+ x86-64

mosec-0.5.1-cp37-cp37m-musllinux_1_1_x86_64.whl (2.5 MB view hashes)

Uploaded CPython 3.7m musllinux: musl 1.1+ x86-64

mosec-0.5.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.4 MB view hashes)

Uploaded CPython 3.7m manylinux: glibc 2.17+ x86-64

mosec-0.5.1-cp37-cp37m-macosx_10_9_x86_64.whl (1.4 MB view hashes)

Uploaded CPython 3.7m macOS 10.9+ x86-64

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page