batched-fn

Library Listed Dormant

Middleware for serving deep learning models with batched prediction

Checked ยท Sources

Downloads
76
Dependents
0
Stars
22
Forks
2
Contributors
3
Commits
60
Latest release
0.2.5 ยท

About

From the project README ยท

Rust server plugin for deploying deep learning models with batched prediction.

Deep learning models are usually implemented to make efficient use of a GPU by batching inputs together in "mini-batches". However, applications serving these models often receive requests one-by-one. So using a conventional single or multi-threaded server approach will under-utilize the GPU and lead to latency that increases linearly with the volume of requests.

batched-fn is a drop-in solution for deep learning webservers that queues individual requests and provides them as a batch to your model. It can be added to any application with minimal refactoring simply by inserting the batched_fn macro into the function that runs requests through the model.

Features

  • ๐Ÿš€ Easy to use: drop the batched_fn! macro into existing code.
  • ๐Ÿ”ฅ Lightweight and fast: queue system implemented on top of the blazingly fast flume crate.
  • ๐Ÿ™Œ Easy to tune: simply adjust max_delay and max_batch_size.
  • ๐Ÿ›‘ Back pressure mechanism included: just set channel_cap and handle Error::Full by returning a 503 from your webserver.

Examples

Suppose you have a model API that look like this:

Read the full README
// `Batch` could be anything that implements the `batched_fn::Batch` trait.
type Batch<T> = Vec<T>;

#[derive(Debug)]
struct Input {
    // ...
}

#[derive(Debug)]
struct Output {
    // ...
}

struct Model {
    // ...
}

impl Model {
    fn predict(&self, batch: Batch<Input>) -> Batch<Output> {
        // ...
    }

    fn load() -> Self {
        // ...
    }
}

Without batched-fn a webserver route would need to call Model::predict on each individual input, resulting in a bottleneck from under-utilizing the GPU:

use once_cell::sync::Lazy;
static MODEL: Lazy<Model> = Lazy::new(Model::load);

fn predict_for_http_request(input: Input) -> Output {
    let mut batched_input = Batch::with_capacity(1);
    batched_input.push(input);
    MODEL.predict(batched_input).pop().unwrap()
}

But by dropping the batched_fn macro into your code you automatically get batched inference behind the scenes without changing the one-to-one relationship between inputs and outputs:

async fn predict_for_http_request(input: Input) -> Output {
    let batch_predict = batched_fn! {
        handler = |batch: Batch<Input>, model: &Model| -> Batch<Output> {
            model.predict(batch)
        };
        config = {
            max_batch_size: 16,
            max_delay: 50,
        };
        context = {
            model: Model::load(),
        };
    };
    batch_predict(input).await.unwrap()
}

โ—๏ธ Note that the predict_for_http_request function now has to be async.

Here we set the max_batch_size to 16 and max_delay to 50 milliseconds. This means the batched function will wait at most 50 milliseconds after receiving a single input to fill a batch of 16. If 15 more inputs are not received within 50 milliseconds then the partial batch will be ran as-is.

Tuning max batch size and max delay

The optimal batch size and delay will depend on the specifics of your use case, such as how big of a batch you can fit in memory (typically on the order of 8, 16, 32, or 64 for a deep learning model) and how long of a delay you can afford. In general you want to set max_batch_size as high as you can, assuming the total processing time for N examples is minimized with a batch size of N, and keep max_delay small relative to the time it takes for your handler function to process a batch.

Implementation details

When the batched_fn macro is invoked it spawns a new thread where the handler will be ran. Within that thread, every object specified in the context is initialized and then passed by reference to the handler each time it is run.

The object returned by the macro is just a closure that sends a single input and a callback through an asyncronous channel to the handler thread. When the handler finishes running a batch it invokes the callback corresponding to each input with the corresponding output, which triggers the closure to wake up and return the output.

Runs on
GPU support unknown
What shows it
  • no dependency or feature matches a backend row
Native code
None found
  • No native code found
Python bindings
No Python binding crate found
License
Apache-2.0

Compare with similar projects

Order: strongest tier first, then most downloads, then name, with unmeasured values last. A library counts downloads over 30 days. An app counts binary downloads per release. An app with none counts its crate downloads over 30 days. ML Rust runs this catalogue, so its closest project always gets a row.

batched-fn beside the projects that share a topic with it
ProjectDownloadsDependentsStarsLatest releaseRuns on (GPU)Native codeLicense
batched-fn This page Listed Dormant

Middleware for serving deep learning models with batched prediction

76 downloads over 30 days 0 22 0.2.5 GPU support unknown No native code found Apache-2.0
ort Featured

A safe Rust wrapper for ONNX Runtime 1.31 - Optimize and accelerate machine learning inference & training

3,902,768 downloads over 30 days 694 2,611 2.0.0-rc.15 CUDA, WebGPU, ROCm Binds native code: onnxruntime, ort-sys. Build uses a native toolchain: pkg-config (feature pkg-config) Apache-2.0 OR MIT
llmserve App Listed

TUI for serving local LLM models. Pick a model, pick a backend, serve it.

424 binary downloads per release Not applicable 417 0.0.7 GPU support unknown No native code found MIT
blazr App Listed

Inference server for LLMs, speech and embeddings: OpenAI-compatible routes with streaming, plus speech synthesis (TTS) and transcription (ASR). Serves Llama, Mistral, Qwen, Mamba2, MLA+MoE and hybrid models from SafeTensors, AWQ, GPTQ and GGUF.

8 binary downloads per release Not applicable 7 0.7.1 CUDA, WebGPU Binds native code: ring (feature distributed) Apache-2.0
rust-dl-webserver App Listed Dormant

๐Ÿฆ€ Example of serving deep learning models in Rust with batched prediction

Not measured Not applicable 34 Not measured Not measured Not measured None stated

600 KB WASM runtime for Cactus Compute's Needle AI tool-calling models, Needle 3, 2 and 1 from one build. Browser, Cloudflare Workers, Node.js, Python, C FFI and no_std. Token-exact with the JAX reference. No backend, no API key.

126 downloads over 30 days 0 107 0.3.1 GPU support unknown No native code found MIT
Why ListedNo archive, New or Featured rule places it, so it is Listed.

What it lacks for Featured

  • It has 0 active dependents and 0 new dependents in 365 days. Featured needs 11 active dependents or 9 new dependents in 365 days. The repository route reads 22 stars, 2 forks and 3 contributors. It needs 4,539 stars, 434 forks and 79 contributors together.
  • The project is dormant and not finished. Dormancy rule

What else the check found

  • The last activity is on 10 Mar 2024, 974 days ago. That reaches the 450 days the rules expect, so the project is dormant. Dormancy rule

Not measured: Latest release fails cargo check.

Exact rules: Listed, Featured library. The check on applied thresholds version 9.

Every rule outcome, as the check records it
  • expected-interval: version 0.2.5 base 450: E = 450 days
  • dormancy: last activity 2024-03-10, 974 days ago, E = 450: dormant
  • featured: not featured: active_users 0 < 11 and new_adopters 0 < 9 and repository route stars 22 (needs 4539), forks 2 (needs 434), contributors 3 (needs 79); dormant and not stable
  • listed: listed: no archive, new or featured rule applies

Measurements and sources

Each signal row shows the raw value, its source and the fetch date. The Sources list gathers every distinct source on this page. Movement needs more history.

Sources6 sources
Adoption0 active dependents, 0 new dependents in 365 days1 not measured
Adoption measurements
SignalValueSourceFetchedCounts
Active dependents0crates.io database dumpYes
New dependents (365 days)0crates.io database dumpYes
Peak active dependents0crates.io database dumpYes
Active dependents as a share of the peak1crates.io database dumpYes
Binary downloads per releaseNot measuredYes
MaintenanceLatest human commit: 2 years ago3 not measured
Maintenance measurements
SignalValueSourceFetchedCounts
Latest human commit2024-03-10GitHub repositoryYes
Latest release2024-03-10crates.io database dumpYes
First release2020-03-21crates.io database dumpYes
Latest version0.2.5crates.io database dumpYes
Days the oldest outside issue waits for a reply0GitHub repositoryYes
Maintainer replies over 365 days0GitHub repositoryYes
Repository archivedfalseGitHub repositoryYes
Repository gonefalseGitHub repositoryYes
Release commit or manifest in the repotruecrates.io packageYes
Published docstruecrates.io database dumpYes
Latest release fails cargo checkNot measuredYes
Build check dateNot measuredYes
Build check toolchainNot measuredYes
SecurityUnpatched vulnerabilities: none
Security measurements
SignalValueSourceFetchedCounts
Unpatched vulnerabilities past the grace windownoneRustSec advisory databaseYes
RustSec unmaintained advisorynoneRustSec advisory databaseYes
Deprecation noticenonecrates.io database dumpYes
Deprecated requirementnonecrates.io database dumpYes
Distribution17 releases, 76 downloads over 30 days5 not measured
Distribution measurements
SignalValueSourceFetchedCounts
Releases17crates.io database dumpYes
Downloads over 30 days76crates.io database dumpYes
Binary downloads over the last 3 releasesNot measuredYes
Homebrew installs on request over 365 daysNot measuredYes
Repology repository familiesNot measuredYes
Docker pull growth over 90 daysNot measuredYes
Docker pulls at the growth baselineNot measuredYes
Every version a prereleasefalsecrates.io database dumpYes
Every version 0.0.xfalsecrates.io database dumpYes
Every version yankedfalsecrates.io database dumpYes
Crate deleted from crates.iofalsecrates.io database dumpYes
Repository22 stars, 2 forks, 3 contributors, 60 commits. Stars alone never qualify a project.
Repository measurements
SignalValueSourceFetchedCounts
GitHub stars22GitHub repositoryYes โ€” one part of the repository route
GitHub forks2GitHub repositoryYes โ€” one part of the repository route
Contributors with a GitHub account3GitHub contributorsYes โ€” one part of the repository route
Commits on the default branch60GitHub repositoryNo
Repository's main crate left out of the entrynonecrates.io database dumpYes
Facts that never count
Facts that never count measurements
SignalValueSourceFetchedCounts
LicenseApache-2.0crates.io database dumpNo
Runs on, from listed crates and their direct dependenciesGPU support unknowncrates.io database dumpNo
What shows each backendno dependency or feature matches a backend rowcrates.io database dumpNo
Native code, from listed crates and their dependenciesNo native code foundcrates.io database dumpNo
Python bindings, from direct dependencies of listed cratesNo Python binding crate foundcrates.io database dumpNo
Crates that depend on a listed crate directly0crates.io database dumpNo

Corrections and review history

Report a correction

No correction applies to this entry.

Judgments

A judgment enters only through an approved issue and a merged pull request.

No judgment applies to this entry.