12 releases

Uses new Rust 2021

0.3.6 Jun 18, 2022
0.3.5 May 7, 2022
0.3.4 Mar 5, 2022
0.3.3 Feb 19, 2022
0.1.0 Sep 27, 2021

#28 in Machine learning

Download history 4/week @ 2022-03-09 50/week @ 2022-03-16 20/week @ 2022-03-23 1/week @ 2022-03-30 10/week @ 2022-04-06 70/week @ 2022-04-27 83/week @ 2022-05-04 169/week @ 2022-05-11 46/week @ 2022-05-18 44/week @ 2022-05-25 76/week @ 2022-06-01 23/week @ 2022-06-08 25/week @ 2022-06-15 4/week @ 2022-06-22

128 downloads per month


1.5K SLoC

Rust 840 SLoC // 0.1% comments Python 762 SLoC // 0.3% comments


discord invitation link PyPI version PyPi Downloads License Check status

Model Serving made Efficient in the Cloud.


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


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

> pip install -U mosec


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()
formatter = logging.Formatter(
    "%(asctime)s - %(process)d - %(levelname)s - %(filename)s:%(lineno)s - %(message)s"
sh = logging.StreamHandler()

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:
            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()
        CalculateExp, num=2
    )  # we spawn two processes for parallel computing

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 -d '{"x": 2}'
  "y": 7.38905609893065

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

or check the metrics:

> curl

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

> RUST_LOG=debug python server.py

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


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.


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!


~320K SLoC