Skip to main content

Model Serving made Efficient in the Cloud.

Project description

MOSEC

discord invitation link PyPI 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 performance 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.

import logging

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

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(
    "%(asctime)s - %(process)d - %(levelname)s - %(filename)s:%(lineno)s - %(message)s"
)
sh = logging.StreamHandler()
sh.setFormatter(formatter)
logger.addHandler(sh)

Then, we build an API to calculate the exponential with base e for a given number. To achieve that, we simply inherit the Worker class and override the forward method. Note that the input req is by default a JSON-decoded object, e.g., a dictionary here (wishfully it receives data like {"x": 1}). We also enclose the input parsing part with a try...except... block to reject invalid input (e.g., no key named "x" or field "x" cannot be converted to float).

import math


class CalculateExp(Worker):
    def forward(self, req: dict) -> dict:
        try:
            x = float(req["x"])
        except KeyError:
            raise ValidationError("cannot find key 'x'")
        except ValueError:
            raise ValidationError("cannot convert 'x' value to float")
        y = math.exp(x)  # f(x) = e ^ x
        logger.debug(f"e ^ {x} = {y}")
        return {"y": y}

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

if __name__ == "__main__":
    server = Server()
    server.append_worker(
        CalculateExp, num=2
    )  # we spawn two processes for parallel computing
    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 server.py --help

Then let's start the server...

> python server.py

and in another terminal, test it:

> curl -X POST http://127.0.0.1:8000/inference -d '{"x": 2}'
{
  "y": 7.38905609893065
}

> curl -X POST http://127.0.0.1:8000/inference -d '{"input": 2}' # wrong schema
validation error: cannot find key 'x'

or check the metrics:

> curl http://127.0.0.1:8000/metrics

For more debug logs, you can enable it by changing the Python & Rust log level:

logger.setLevel(logging.DEBUG)
> RUST_LOG=debug python server.py

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

Example

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

  • Multi-stage workflow
  • Batch processing worker
  • Shared memory IPC
  • Customized GPU allocation
  • PyTorch deep learning models:
    • sentiment analysis
    • image recognition

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.

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!

Project details


Download files

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

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

mosec_tiinfer-0.0.7-cp38-cp38-manylinux1_x86_64.whl (3.0 MB view details)

Uploaded CPython 3.8

mosec_tiinfer-0.0.7-cp37-cp37m-manylinux1_x86_64.whl (3.0 MB view details)

Uploaded CPython 3.7m

File details

Details for the file mosec_tiinfer-0.0.7-cp311-cp311-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for mosec_tiinfer-0.0.7-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 c3b609b26bc91e0be8302d14c034aadda42e2f2cd3af8ccae2a4397f20bdaa64
MD5 3ea500a4cea8d8b5d15e39a8a6878bba
BLAKE2b-256 56f3da26f4a461498856b06c85f02318833d4accfb92020bf3be896b0ff89377

See more details on using hashes here.

File details

Details for the file mosec_tiinfer-0.0.7-cp310-cp310-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for mosec_tiinfer-0.0.7-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 7f701a35fc8ec98a4e876af3108dbbf39a9f0a4c92e6390732b0c586226d8dc7
MD5 71c10577f0a1c97c02964de00449e1ae
BLAKE2b-256 97c670f755fb55daa34c6ce12ff99cebdbe2fdce0ced9a9782a7b0bd748a6c67

See more details on using hashes here.

File details

Details for the file mosec_tiinfer-0.0.7-cp39-cp39-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for mosec_tiinfer-0.0.7-cp39-cp39-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 55fca23768ffed349b2d173b38ff073904544b1b29d18e6e7b1e358335f08d39
MD5 b118e62c2ac50099896ecbc095982eeb
BLAKE2b-256 c1cc7ae89e45de23f2f6a46487603995426e94394bcdb0589174a3abd7e3999d

See more details on using hashes here.

File details

Details for the file mosec_tiinfer-0.0.7-cp38-cp38-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for mosec_tiinfer-0.0.7-cp38-cp38-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 4e8f61c3fe9bbd721e37f9f07780da05351a36dfae7542f527dcdec8b9954104
MD5 cab3054cf3ff11fd0eb02b1177d72b2a
BLAKE2b-256 34f72c7ba43d4974208643b25d9cc59f06dbd5c06603f1365b8cc3e73c096599

See more details on using hashes here.

File details

Details for the file mosec_tiinfer-0.0.7-cp37-cp37m-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for mosec_tiinfer-0.0.7-cp37-cp37m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 c744cc75ca07ae26c903eb9bee0b581766fced55e228582441291f8d4936c0b6
MD5 581636071253b22edbbc19f5528f2cd7
BLAKE2b-256 9ed22ec04601f472b232ef51db0b3bdb41cf0a76f1b89b50c6336cd2a9e96074

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