Giter VIP home page Giter VIP logo

mosecorg / mosec Goto Github PK

View Code? Open in Web Editor NEW
708.0 12.0 48.0 890 KB

A high-performance ML model serving framework, offers dynamic batching and CPU/GPU pipelines to fully exploit your compute machine

Home Page: https://mosec.readthedocs.io/

License: Apache License 2.0

Makefile 0.94% Python 68.89% Rust 28.76% Dockerfile 1.42%
model-serving deep-learning machine-learning nerual-network mlops machine-learning-platform hacktoberfest gpu python pytorch

mosec's Introduction

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.

mosec's People

Contributors

cutecutecat avatar delonleo avatar dependabot[bot] avatar ferdinandzhong avatar gaocegege avatar kemingy avatar lkevinzc avatar n063h avatar secsilm avatar thinkcache avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mosec's Issues

[BUG] Invalid output when pyarrow plasma is used and ValidationError is raised

Describe the bug
When pyarrow plasma is used in a multi stage setting and when mosec.errors.ValidationError is raised, we get can invalid response . Example ~��6,�&B���Ӣ��

To Reproduce

  1. Using official example
from functools import partial

from pyarrow import plasma  # type: ignore

from mosec import Server, Worker
from mosec.errors import ValidationError
from mosec.plugins import PlasmaShmWrapper


class DataProducer(Worker):
    def forward(self, data: dict) -> bytes:
        try:
            data_bytes = b"a" * data["size"]
        except KeyError as err:
            raise ValidationError(err)
        return data_bytes


class DataConsumer(Worker):
    def forward(self, data: bytes) -> dict:
        return {"ipc test data length": len(data)}


if __name__ == "__main__":
    """
    We start a subprocess for the plasma server, and pass the path
    to the plasma client which serves as the shm wrapper.
    We also register the plasma server process as a daemon, so
    that when it exits the service is able to gracefully shutdown
    and restarted by the orchestrator.
    """
    # 200 Mb store, adjust the size according to your requirement
    with plasma.start_plasma_store(plasma_store_memory=200 * 1000 * 1000) as (
        shm_path,
        shm_process,
    ):
        server = Server(
            ipc_wrapper=partial(  # defer the wrapper init to worker processes
                PlasmaShmWrapper,
                shm_path=shm_path,
            )
        )
        server.register_daemon("plasma_server", shm_process)
        server.append_worker(DataProducer, num=2)
        server.append_worker(DataConsumer, num=2)
        server.run()
  1. Command to run
curl -X POST h000/inference -d '{"wrong_key": 2}'
  1. Response from curl
1���6��.��2���{��r
  1. Expected output
validation error: 'size'
  1. Log from stdout
2022-03-04T05:59:40.629248Z  INFO mosec::protocol: abnormal tasks ids=[4] code=ValidationError
2022-03-04T06:00:22.816739Z  INFO mosec::protocol: abnormal tasks ids=[7] code=ValidationError
2022-03-04T06:00:23.513732Z  INFO mosec::protocol: abnormal tasks ids=[8] code=ValidationError
  1. Additional note
  • Only applies when pyarrow plasma is used.

Desktop (please complete the following information):

  • OS: Ubuntu 20.04
  • Library Version: 0.3.0
  • Python Version: 3.8.12
  • Python Plasma Version: 7.0.0

chore: better README

The current README doesn't give users a very intuitive introduction to the feature of MOSEC.

Let's make it more user-friendly.

  • image to demonstrate the features
  • better tutorial example

[FEATURE]Benchmark for AI system

Our community lacks some benchmark for server-side end to end AI system. For examples, the face recognition system, smart tracfic system with tens of models, and ocr-system. A complete comparison for the throughout and Latency across different hardware platforms and also libraries is necessary. Usability might also be considered. This is both beneficial to hardware manufactures, and also Democratisation of AI.

make sure all the examples can run with the latest code

How about locally we do lint for all codes including those under examples, but we do not do that in CI? Local dev environment should have those third parties installed. Doing full lint for examples benefits code styles.
It's better to have a CI to make sure all the examples can run with the latest code.

Originally posted by @kemingy in #180 (comment)

[BUG] security vulnerabilities

cargo audit                                                                                                    
    Fetching advisory database from `https://github.com/RustSec/advisory-db.git`
      Loaded 395 security advisories (from /home/keming/.cargo/advisory-db)
    Updating crates.io index
    Scanning Cargo.lock for vulnerabilities (100 crate dependencies)
Crate:         chrono
Version:       0.4.19
Title:         Potential segfault in `localtime_r` invocations
Date:          2020-11-10
ID:            RUSTSEC-2020-0159
URL:           https://rustsec.org/advisories/RUSTSEC-2020-0159
Solution:      No safe upgrade is available!
Dependency tree:
chrono 0.4.19
└── tracing-subscriber 0.2.19
    └── mosec 0.3.1

Crate:         thread_local
Version:       1.1.3
Title:         Data race in `Iter` and `IterMut`
Date:          2022-01-23
ID:            RUSTSEC-2022-0006
URL:           https://rustsec.org/advisories/RUSTSEC-2022-0006
Solution:      Upgrade to >=1.1.4
Dependency tree:
thread_local 1.1.3
└── tracing-subscriber 0.2.19
    └── mosec 0.3.1

Crate:         tokio
Version:       1.9.0
Title:         Data race when sending and receiving after closing a `oneshot` channel
Date:          2021-11-16
ID:            RUSTSEC-2021-0124
URL:           https://rustsec.org/advisories/RUSTSEC-2021-0124
Solution:      Upgrade to >=1.8.4, <1.9.0 OR >=1.13.1
Dependency tree:
tokio 1.9.0
├── mosec 0.3.1
└── hyper 0.14.11
    └── mosec 0.3.1

error: 3 vulnerabilities found!

Will create a PR to upgrade the version.

[FIX] apply `pylint` to tests and examples

We have changed to pylint in #134. But only the code under mosec/ directory has been applied.

Tasks

No tasks being tracked yet.

[FEATURE] Support mini-batch request

Is your feature request related to a problem? Please describe.
Currently we are batching at the request level, ignoring the fact that a single request may already contain a mini-batch formed by the client.

Describe the solution you'd like
One option is to add a header specifying the batch size as an integer, then when we do the batching taking that into consideration.

[BUG] `GLIBC_2.29` not found in Ubuntu 18.04

Describe the bug
mosec will raise the following error in Ubuntu 18.04:

/data/anaconda3/envs/mosec-p38/lib/python3.8/site-packages/mosec/bin/mosec: /lib/x86_64-linux-gnu/libm.so.6: version `GLIBC_2.29' not found (required by /data/anaconda3/envs/mosec-p38/lib/python3.8/site-packages/mosec/bin/mosec)

To Reproduce
Just run the Sentiment Analysis example.

Desktop (please complete the following information):

  • OS: Ubuntu 18.04
  • Library Version: 0.2.1
  • Rust Version: unknown
  • Python Version: 3.8.12

Additional context
I tried to use mosec in Ubuntu 20.04 and it worked. So if Ubuntu 20.04 or above is required, I think it's better to put it on the document.

[FEATURE] add gRPC service support

Requirements:

  • rust part doesn't parse the content, will pass all the bytes to python workers
  • user can define their own protobuf file to serialize or de-serialize the data

[BUG]NameError: name 'plasma' is not defined

Describe the bug
NameError: name 'plasma' is not defined

To Reproduce
Steps to reproduce the behavior:

import base64
import json
import os

import cv2
import numpy as np
import yaml
from mosec import Worker, Server
from mosec.errors import ValidationError

from inference import Inference


def _get_model():
    if os.path.exists('config.yaml'):
        config = open('config.yaml', mode='r', encoding='utf-8')
        config = yaml.load(config, Loader=yaml.FullLoader)

        model = Inference(
            det_model_path=config['det_model_path'],
            rec_model_path=config['rec_model_path'],
            device=config['device'],
            dict_path=config['dict_path'],
            rec_std=0.5, rec_mean=0.5, threshold=0.7,
            angle_classes=config['angle_classes'],
            angle_classify_model_path=config['angle_model_path'],
            object_classes=None,
            object_classify_model_path=None
        )
        return model, config
    else:
        raise FileNotFoundError('must have a config.yaml file!')


class OCRInference(Worker):
    def __init__(self):
        super(OCRInference, self).__init__()
        self.model, self.config = _get_model()

    def forward(self, req: dict):
        try:
            image = req["image"]
            save_name = req['saveName']
            im = np.frombuffer(base64.b64decode(image), np.uint8)
            im = cv2.imdecode(im, 1)
            result = self.model.infer(img=im,
                                      img_save_name=save_name,
                                      cut_image_save_path=self.config['cut_image_save_path'],
                                      need_angle=self.config['need_angle'],
                                      need_object=self.config['need_object'])
            return json.dumps({'status': 1, 'result': result})

        except KeyError as err:
            raise ValidationError(f"cannot find key {err}")
        except Exception as err:
            raise ValidationError(f"cannot decode as image data: {err}")


if __name__ == "__main__":
    server = Server()

    server.append_worker(OCRInference, num=2, max_batch_size=16)
    server.run()

Desktop (please complete the following information):

  • OS: [e.g. Ubuntu 20.04]
  • Library Version: [e.g. 0.1.0]
  • Rust Version: [e.g. 1.55.0]
  • Python Version: [e.g. 3.8.5]

Additional context
Add any other context about the problem here.

[FEATURE] Async Inference

This can offer the client side the flexibility to do independent computation while waiting for the model inference result.

Maybe two API:

  1. /inference_async/put which returns an rid;
  2. /inference_async/get.

Python code should not be affected; need minor modification on Rust side.

Thanks for your great contribution :)

2021/12/09 Update: I sincerely apologize for abusing the github issue system and we’ll find more proper ways to communicate with contributors in the future.

Hi kemingy
We are so appreciative of your contribution to fixing pylint rules through the “Let’s become Taichi contributors within 10 minutes” program. Please send an email to [email protected] with your offline address. We would deliver a hoodie to you. : ) Looking forward to hearing from you!

非常感谢您参与第0次十分钟成为 Taichi contributors 活动,并在 pylint 命令修复中的宝贵贡献!
为表感谢,近期太极周边会向你赶来~请麻烦将收件信息发送至运营同学 [email protected]
欢迎持续关注 Taichi 社区哦~
Taichi 开源社区 敬上

[FEATURE] Quick and easy demo

  • Provide colab example, which should be much more efficient than users copy and run by themselves
  • Provide out-of-the-box sample yaml for cloud deployment (low priority)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.