Skip to main content

Model Serving made Efficient in the Cloud

Project description

MOSEC

discord invitation link PyPI version conda-forge Python Version PyPi monthly Downloads License Check status

Model Serving made Efficient in the Cloud.

Introduction

MOSEC

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 for Linux x86_64 or macOS x86_64/ARM64 with:

pip install -U mosec
# or install with conda
conda install conda-forge::mosec

To build from the source code, install Rust and run the following command:

make package

You will get a mosec wheel file in the dist folder.

Usage

We demonstrate how Mosec can help you easily host a pre-trained stable diffusion model as a service. You need to install diffusers and transformers as prerequisites:

pip install --upgrade diffusers[torch] transformers

Write the server

Click me for server codes with explanations.

Firstly, we 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 for clients to query a text prompt and obtain an image based on the stable-diffusion-v1-5 model in just 3 steps.

  1. Define your service as a class which inherits mosec.Worker. Here we also inherit MsgpackMixin to employ the msgpack serialization format(a).

  2. Inside the __init__ method, initialize your model and put it onto the corresponding device. Optionally you can assign self.example with some data to warm up(b) the model. Note that the data should be compatible with your handler's input format, which we detail next.

  3. Override the forward method to write your service handler(c), with the signature forward(self, data: Any | List[Any]) -> Any | List[Any]. Receiving/returning a single item or a tuple depends on whether dynamic batching(d) is configured.

class StableDiffusion(MsgpackMixin, Worker):
    def __init__(self):
        self.pipe = StableDiffusionPipeline.from_pretrained(
            "runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16
        )
        device = "cuda" if torch.cuda.is_available() else "cpu"
        self.pipe = self.pipe.to(device)
        self.example = ["useless example prompt"] * 4  # warmup (batch_size=4)

    def forward(self, data: List[str]) -> List[memoryview]:
        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())
        return images

[!NOTE]

(a) In this example we return an image in the binary format, which JSON does not support (unless encoded with base64 that makes the payload larger). Hence, msgpack suits our need better. If we do not inherit MsgpackMixin, JSON will be used by default. In other words, the protocol of the service request/response can be either msgpack, JSON, or any other format (check our mixins).

(b) Warm-up usually helps to allocate GPU memory in advance. If the warm-up example is specified, the service will only be ready after the example is forwarded through the handler. However, if no example is given, the first request's latency is expected to be longer. The example should be set as a single item or a tuple depending on what forward expects to receive. Moreover, in the case where you want to warm up with multiple different examples, you may set multi_examples (demo here).

(c) This example shows a single-stage service, where the StableDiffusion worker directly takes in client's prompt request and responds the image. Thus the forward can be considered as a complete service handler. However, we can also design a multi-stage service with workers doing different jobs (e.g., downloading images, model inference, post-processing) in a pipeline. In this case, the whole pipeline is considered as the service handler, with the first worker taking in the request and the last worker sending out the response. The data flow between workers is done by inter-process communication.

(d) Since dynamic batching is enabled in this example, the forward method will wishfully receive a list of string, e.g., ['a cute cat playing with a red ball', 'a man sitting in front of a computer', ...], aggregated from different clients for batch inference, improving the system throughput.

Finally, we append the worker to the server to construct a single-stage workflow (multiple stages can be pipelined to further boost the throughput, see this example), and specify the number of processes we want it to run in parallel (num=1), and the maximum batch size (max_batch_size=4, the maximum number of requests dynamic batching will accumulate before timeout; timeout is defined with the max_wait_time=10 in milliseconds, meaning the longest time Mosec waits until sending the batch to the Worker).

if __name__ == "__main__":
    server = Server()
    # 1) `num` specifies the number of processes that will be spawned to run in parallel.
    # 2) By configuring the `max_batch_size` with the value > 1, the input data in your
    # `forward` function will be a list (batch); otherwise, it's a single item.
    server.append_worker(StableDiffusion, num=1, max_batch_size=4, max_wait_time=10)
    server.run()

Run the server

Click me to see how to run and query the server.

The above snippets are merged in our example file. You may directly run at the project root level. We first have a look at the command line arguments (explanations here):

python examples/stable_diffusion/server.py --help

Then let's start the server with debug logs:

python examples/stable_diffusion/server.py --log-level debug --timeout 30000

Open http://127.0.0.1:8000/openapi/swagger/ in your browser to get the OpenAPI doc.

And in another terminal, test it:

python examples/stable_diffusion/client.py --prompt "a cute 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 service! 😉

Examples

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

Configuration

  • Dynamic batching
    • max_batch_size and max_wait_time (millisecond) are configured when you call append_worker.
    • Make sure inference with the max_batch_size value won't cause the out-of-memory in GPU.
    • Normally, max_wait_time should be less than the batch inference time.
    • If enabled, it will collect a batch either when the number of accumulated requests reaches max_batch_size or when max_wait_time has elapsed. The service will benefit from this feature when the traffic is high.
  • Check the arguments doc for other configurations.

Deployment

  • If you're looking for a GPU base image with mosec installed, you can check the official image mosecorg/mosec. For the complex use case, check out envd.
  • This service doesn't need Gunicorn or NGINX, but you can certainly use the ingress controller when necessary.
  • This service should be the PID 1 process in the container since it controls multiple processes. If you need to run multiple processes in one container, you will need a supervisor. You may choose Supervisor or Horust.
  • Remember to collect the metrics.
    • mosec_service_batch_size_bucket shows the batch size distribution.
    • mosec_service_batch_duration_second_bucket shows the duration of dynamic batching for each connection in each stage (starts from receiving the first task).
    • mosec_service_process_duration_second_bucket shows the duration of processing for each connection in each stage (including the IPC time but excluding the mosec_service_batch_duration_second_bucket).
    • mosec_service_remaining_task shows the number of currently processing tasks.
    • mosec_service_throughput shows the service throughput.
  • Stop the service with SIGINT (CTRL+C) or SIGTERM (kill {PID}) since it has the graceful shutdown logic.

Performance tuning

  • Find out the best max_batch_size and max_wait_time for your inference service. The metrics will show the histograms of the real batch size and batch duration. Those are the key information to adjust these two parameters.
  • Try to split the whole inference process into separate CPU and GPU stages (ref DistilBERT). Different stages will be run in a data pipeline, which will keep the GPU busy.
  • You can also adjust the number of workers in each stage. For example, if your pipeline consists of a CPU stage for preprocessing and a GPU stage for model inference, increasing the number of CPU-stage workers can help to produce more data to be batched for model inference at the GPU stage; increasing the GPU-stage workers can fully utilize the GPU memory and computation power. Both ways may contribute to higher GPU utilization, which consequently results in higher service throughput.
  • For multi-stage services, note that the data passing through different stages will be serialized/deserialized by the serialize_ipc/deserialize_ipc methods, so extremely large data might make the whole pipeline slow. The serialized data is passed to the next stage through rust by default, you could enable shared memory to potentially reduce the latency (ref RedisShmIPCMixin).
  • You should choose appropriate serialize/deserialize methods, which are used to decode the user request and encode the response. By default, both are using JSON. However, images and embeddings are not well supported by JSON. You can choose msgpack which is faster and binary compatible (ref Stable Diffusion).
  • Configure the threads for OpenBLAS or MKL. It might not be able to choose the most suitable CPUs used by the current Python process. You can configure it for each worker by using the env (ref custom GPU allocation).

Adopters

Here are some of the companies and individual users that are using Mosec:

Citation

If you find this software useful for your research, please consider citing

@software{yang2021mosec,
  title = {{MOSEC: Model Serving made Efficient in the Cloud}},
  author = {Yang, Keming and Liu, Zichen and Cheng, Philip},
  url = {https://github.com/mosecorg/mosec},
  year = {2021}
}

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.

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.8.6.tar.gz (86.9 kB view details)

Uploaded Source

Built Distributions

mosec-0.8.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.6 MB view details)

Uploaded CPython 3.12 manylinux: glibc 2.17+ x86-64

mosec-0.8.6-cp312-cp312-macosx_11_0_arm64.whl (4.6 MB view details)

Uploaded CPython 3.12 macOS 11.0+ ARM64

mosec-0.8.6-cp312-cp312-macosx_10_9_x86_64.whl (4.5 MB view details)

Uploaded CPython 3.12 macOS 10.9+ x86-64

mosec-0.8.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.6 MB view details)

Uploaded CPython 3.11 manylinux: glibc 2.17+ x86-64

mosec-0.8.6-cp311-cp311-macosx_11_0_arm64.whl (4.6 MB view details)

Uploaded CPython 3.11 macOS 11.0+ ARM64

mosec-0.8.6-cp311-cp311-macosx_10_9_x86_64.whl (4.5 MB view details)

Uploaded CPython 3.11 macOS 10.9+ x86-64

mosec-0.8.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.6 MB view details)

Uploaded CPython 3.10 manylinux: glibc 2.17+ x86-64

mosec-0.8.6-cp310-cp310-macosx_11_0_arm64.whl (4.6 MB view details)

Uploaded CPython 3.10 macOS 11.0+ ARM64

mosec-0.8.6-cp310-cp310-macosx_10_9_x86_64.whl (4.5 MB view details)

Uploaded CPython 3.10 macOS 10.9+ x86-64

mosec-0.8.6-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.6 MB view details)

Uploaded CPython 3.9 manylinux: glibc 2.17+ x86-64

mosec-0.8.6-cp39-cp39-macosx_11_0_arm64.whl (4.6 MB view details)

Uploaded CPython 3.9 macOS 11.0+ ARM64

mosec-0.8.6-cp39-cp39-macosx_10_9_x86_64.whl (4.5 MB view details)

Uploaded CPython 3.9 macOS 10.9+ x86-64

mosec-0.8.6-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.6 MB view details)

Uploaded CPython 3.8 manylinux: glibc 2.17+ x86-64

mosec-0.8.6-cp38-cp38-macosx_11_0_arm64.whl (4.6 MB view details)

Uploaded CPython 3.8 macOS 11.0+ ARM64

mosec-0.8.6-cp38-cp38-macosx_10_9_x86_64.whl (4.5 MB view details)

Uploaded CPython 3.8 macOS 10.9+ x86-64

File details

Details for the file mosec-0.8.6.tar.gz.

File metadata

  • Download URL: mosec-0.8.6.tar.gz
  • Upload date:
  • Size: 86.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.0 CPython/3.9.19

File hashes

Hashes for mosec-0.8.6.tar.gz
Algorithm Hash digest
SHA256 ad610eec13789dd07839f3483e16f74048a4d6ed816e9a8fb4f7f3cc175605ff
MD5 b70d6426b561c3641a4b57a6cf3bb49c
BLAKE2b-256 6219180e3d3c5d03749da59b97041c1a1d3573d8ebf61d8a14ed6f7ff5d05636

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 f0079ff489b9209ab31d1318798bd9f46ea1c731a80ee595d5bff8322813a49f
MD5 591325389404b941e2582e8d5b3b27ef
BLAKE2b-256 420788c68b5c363e4927c4de5fc435f3c1a6d7ac2c4d76d26f447f5d1acbcf2b

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 150524dac309d687ea58dc7814d0ab3a0d06ad6aa85bf5fd43ba6e136ed1fb1f
MD5 4ff094361785ee9875f74d49d915dcba
BLAKE2b-256 69cb99e968da9edee14ad2839f8977645e3eeb2133458e0380c4604c4f4495ee

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp312-cp312-macosx_10_9_x86_64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp312-cp312-macosx_10_9_x86_64.whl
Algorithm Hash digest
SHA256 929d821e9d44f029382164683f284f9ab9d3146b22f0a6b848d70722b2a9b263
MD5 5cb1b899b13e510ce5fdacedee05084a
BLAKE2b-256 3b94f2acfb6b7dfb50986e3d5603012aa0ee19e16f25fd07c9d3353c5b4084cd

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 df2a36227fbf1f0d3f023faad796a7b934de24538c8c8f621e43d0325a66e892
MD5 8fc152d430c99b02908434fa3e415d74
BLAKE2b-256 e7cd90fb4019b859b02dd06d9ed04489372499f38f5e0620fe224e4b06c5d5ad

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp311-cp311-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp311-cp311-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 05599ff6b13fa65f1e7e60a5ec8537595fe0dbef6399a68efa951ec8416dc7a1
MD5 c458f82123b4fe8cb72f699c048e6390
BLAKE2b-256 a507af9f5394070cd86f5a5d9d321da75b7023051fb7867fd45545f3f4ab0f93

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp311-cp311-macosx_10_9_x86_64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp311-cp311-macosx_10_9_x86_64.whl
Algorithm Hash digest
SHA256 0aa838af7075935454afbffd03d80d651d98cbe0ca327469574ff6053b795b37
MD5 eeb9fb1509e96c8ba3fbc6c5bd6996da
BLAKE2b-256 5438462ed1172c109f66e519d34097aa1a4672849b9533c7e660d8ca79453a87

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 5c942e614d6aabfdd9675e7c32a366bb1e168cadaa91889c1ab3e14b541bba7b
MD5 0e65ad2d21336e2505d31b5ae2d060c8
BLAKE2b-256 a428fe77b3f1c73d78ce62fc91c9fffaa4c1c9effdb40a71fb83dd148fd3fa10

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp310-cp310-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp310-cp310-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 7d955813f16d36409b518cc67ac52047224bb544ad7e12420b496d8ba7645769
MD5 e59c8e9366c606e9b0d76d353f87d250
BLAKE2b-256 c4e4406dc22abbc7510d326c2bf7aaa7ea561313a4fda72a9cfe390b7d71056a

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp310-cp310-macosx_10_9_x86_64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp310-cp310-macosx_10_9_x86_64.whl
Algorithm Hash digest
SHA256 225939496ba76449821446de99d3571dabf890cd731f44b63d11f87ed7e1e44e
MD5 e97de1cae9a9aab40d2b490792405e8c
BLAKE2b-256 cfe0b98c04a65259ab6977b6f3db55887f3cbf62c1778c7dbe451d9c14c45628

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 400fecc3f61b1b9bf7572fa4db323538646f7f43c5620519d0f0a3453839130d
MD5 e2e166aac792495040922f2ad3febda3
BLAKE2b-256 a796a031a6bdff678b8c247e40f8874279bfd01ea224588407640d6faf09376e

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp39-cp39-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp39-cp39-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 bfd95e27d633c508a1bc874864b05e0052b4fe0845238dcf4890aa0bba2ec23e
MD5 9dbacd3059630d5b283e2aed8210b33a
BLAKE2b-256 e1903512482f114cd0bf3ef86e8fe59fa1b3da2e259a6ac3f6f63c8368ccc717

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp39-cp39-macosx_10_9_x86_64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp39-cp39-macosx_10_9_x86_64.whl
Algorithm Hash digest
SHA256 99c63dad4245b8a302e731e31a46d94d1ebd39c5091b93f0fc40f4b19374c3e9
MD5 758178eba947df797bf6e5e81a7a7196
BLAKE2b-256 c28a68fa359634a848e5098576e7eca70df354089050acf656c3e4f8b64846b1

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 b1cf4abb4de475b1c2e6138337c00f9af2812400d0021273a671b85d686bc4af
MD5 aca2f45430d9f83a1b2480eb5cbfb752
BLAKE2b-256 24b51233d2de0fa1b24577263d33d46f5825bd4ddfdf13a8bbc1527191585da8

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp38-cp38-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp38-cp38-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 0b24b6f408d830a1669003be9cb3783d3cad06ed6c8de1aaf53b627f7a010764
MD5 d7cf1b456792eb4833c0c6141d369ca1
BLAKE2b-256 09e8194843fa9110c07b8adb993c5a4566fa92fa1d8715b51ffb12050ddad610

See more details on using hashes here.

File details

Details for the file mosec-0.8.6-cp38-cp38-macosx_10_9_x86_64.whl.

File metadata

File hashes

Hashes for mosec-0.8.6-cp38-cp38-macosx_10_9_x86_64.whl
Algorithm Hash digest
SHA256 fd5a4a6acf4f9bc095d1e3bdfe58993b6c8045ea19673659441c6aad94caa33a
MD5 ce2000919237d430407ff03c8589a02c
BLAKE2b-256 89e66ce45cb185a4e7c7adc757d2f157364e08c26778e7e16e7f1a38a3805586

See more details on using hashes here.

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