PyMapReduce
A high-performance, asynchronous distributed computing framework for Python, powered by an ultra-fast Rust runtime. Easily scale Python functions, stateful AI/ML actors, and data processing pipelines across multi-core CPUs and distributed clusters with native async/await syntax.
Quickstart
import asyncio
import pymapreduce
# 1. Stateless distributed function
@pymapreduce.remote
def square(x: int) -> int:
return x * x
# 2. Stateful distributed actor with auto memory cleanup
@pymapreduce.remote(idle_timeout=60.0)
class Counter:
def __init__(self, start: int = 0):
self.value = start
def increment(self, amount: int = 1) -> int:
self.value += amount
return self.value
async def main():
# Start local cluster coordinator (HeadNode) and connect a local worker
driver = await pymapreduce.init("127.0.0.1:7777")
worker = await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)
# Run tasks in parallel and fetch lazy object references
refs = [await square.remote(i) for i in range(5)]
results = await asyncio.gather(*[ref.get() for ref in refs])
print("Parallel Squares:", results) # [0, 1, 4, 9, 16]
# Instantiate stateful actor on the cluster
counter = await Counter.remote(start=10)
res_ref = await counter.increment.remote(5)
print("Counter Value:", await res_ref.get()) # 15
# Clean up actor and worker
await pymapreduce.kill(counter)
await worker.disconnect(graceful=True)
if __name__ == "__main__":
asyncio.run(main())
Table of Contents
- PyMapReduce
1. Installation
From PyPI (Recommended)
pip install pymapreduce-core
Building from Source
git clone https://github.com/xuandong/MapReduce.git
cd MapReduce/pymapreduce
python3 -m venv .venv
source .venv/bin/activate
pip install maturin cloudpickle
maturin develop --release
2. User Guide
2.1. Distributed Tasks (Functions)
Decorate any Python function with @pymapreduce.remote to execute it asynchronously across worker CPU cores:
import asyncio
import pymapreduce
@pymapreduce.remote
def process_item(item_id: int, scale: float) -> float:
return item_id * scale
async def main():
driver = await pymapreduce.init()
await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)
# 1. Single execution
res_ref = await process_item.remote(10, 2.5)
print("Single Result:", await res_ref.get())
# 2. Parallel execution
refs = [await process_item.remote(i, 2.5) for i in range(10)]
results = await asyncio.gather(*[ref.get() for ref in refs])
print("Parallel Results:", results)
if __name__ == "__main__":
asyncio.run(main())
2.2. Distributed Actors (Stateful Classes)
Decorate a Python class with @pymapreduce.remote to create a Stateful Actor. The instance stays resident in worker memory, preserving state across successive RPC invocations:
import asyncio
import pymapreduce
@pymapreduce.remote
class MLModelServer:
def __init__(self, model_name: str):
self.model_name = model_name
self.call_count = 0
print(f"Loaded {self.model_name} into RAM")
def predict(self, features: list) -> dict:
self.call_count += 1
return {"prediction": sum(features) * 0.5, "model": self.model_name}
def get_stats(self) -> dict:
return {"total_calls": self.call_count}
async def main():
driver = await pymapreduce.init()
await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)
# 1. Instantiate actor on the cluster
model = await MLModelServer.remote(model_name="ResNet50")
# 2. Call methods sequentially in FIFO order
p1 = await (await model.predict.remote([1.0, 2.0, 3.0])).get()
p2 = await (await model.predict.remote([4.0, 5.0])).get()
stats = await (await model.get_stats.remote()).get()
print("Predictions:", p1, p2)
print("Stats:", stats)
# 3. Explicitly kill actor when done
await pymapreduce.kill(model)
if __name__ == "__main__":
asyncio.run(main())
2.3. Actor Memory Management & Lifecycle
To prevent memory leaks and protect workers from running out of RAM, PyMapReduce provides built-in lifecycle management:
- Idle Timeout (TTL): Automatically unloads the actor instance if no calls are received for a specified duration.
- Explicit Kill: Call
await pymapreduce.kill(actor)orawait actor.destroy.remote()to immediately free allocated resources. - Resource Hook: Define a
close()method in your class to perform custom cleanup (closing file handles, flushing DB connections) when the actor is destroyed.
@pymapreduce.remote(idle_timeout=60.0) # Auto-unload after 60s of inactivity
class HeavyService:
def __init__(self):
self.cache = {}
def query(self, key: str) -> str:
return self.cache.setdefault(key, f"val_{key}")
def close(self):
"""Called automatically when actor is destroyed."""
print("Releasing resources...")
2.4. Automatic Code Shipping (runtime_env)
When distributing code across physical servers, use runtime_env to automatically package and synchronize your local project folder (respecting .gitignore):
import asyncio
import pymapreduce
async def main():
# Automatically package & sync local project files to all cluster workers
driver = await pymapreduce.connect(
"192.168.1.10:7777",
runtime_env={
"working_dir": ".",
"excludes": ["*.log", "data/raw/*"]
}
)
if __name__ == "__main__":
asyncio.run(main())
2.5. Zero-Copy Shared Memory (ObjectRef)
When tasks return large NumPy arrays, Pandas DataFrames, or PyArrow tables, PyMapReduce writes them to shared memory (/dev/shm) and returns an ObjectRef. Passing this reference into subsequent tasks avoids network copies and serialization overhead:
import asyncio
import pymapreduce
import pandas as pd
import numpy as np
@pymapreduce.remote
def create_dataframe(rows: int) -> pd.DataFrame:
return pd.DataFrame(np.random.randn(rows, 10))
@pymapreduce.remote
def compute_summary(df: pd.DataFrame) -> dict:
return df.mean().to_dict()
async def main():
driver = await pymapreduce.init()
await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)
# 1. Returns an ObjectRef handle
df_ref = await create_dataframe.remote(rows=500_000)
# 2. Pass reference directly into next task (zero network copy if collocated)
summary_ref = await compute_summary.remote(df_ref)
summary = await summary_ref.get()
print("Summary:", summary)
# 3. Or fetch the value locally
local_df = await df_ref.get()
print("Fetched DataFrame shape:", local_df.shape)
if __name__ == "__main__":
asyncio.run(main())
2.6. Distributed Datasets
The Dataset API provides lazy, functional transformations for parallel data processing:
import asyncio
import pymapreduce
async def main():
driver = await pymapreduce.init()
await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)
# 1. Create dataset from items, CSV, or Pandas
ds = await pymapreduce.from_items(range(1, 100_001), num_partitions=8)
# 2. Lazy transformation pipeline
transformed = await (
await ds.map(lambda x: x * 2)
).filter(lambda x: x % 4 == 0)
# 3. Actions & Conversions
count = await transformed.count()
sample = await transformed.take(5)
df = await transformed.to_pandas()
print(f"Total: {count}, Sample: {sample}, DataFrame Rows: {len(df)}")
if __name__ == "__main__":
asyncio.run(main())
2.7. Job Timeouts & Task Cancellation
Prevent hung jobs by configuring execution timeouts:
import asyncio
import pymapreduce
async def main():
driver = await pymapreduce.init()
await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)
# Set maximum execution timeout of 30 seconds for this job
config = pymapreduce.JobConfig("AnalyticsJob", max_time=30)
# Submit job through driver
results = await driver.submit(config)
3. Cluster Deployment
3.1. Local Mode (Embedded)
Ideal for single-machine development and testing:
driver = await pymapreduce.init(
address="127.0.0.1:7777",
scheduler=pymapreduce.SchedulerStrategy.Adaptive
)
await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)
3.2. Multi-Server Production Cluster
Deploy across multiple physical servers using the mapreduce CLI:
# 1. Master Server (192.168.1.10): Start Head Node
mapreduce start --head --port 7777 --scheduler Adaptive
# 2. Worker Server 1 (192.168.1.20): Join cluster
mapreduce start --worker --head-addr 192.168.1.10:7777 --cpus 16
# 3. Worker Server 2 (192.168.1.21): Join cluster
mapreduce start --worker --head-addr 192.168.1.10:7777 --cpus 32
In your application:
driver = await pymapreduce.connect(
"192.168.1.10:7777",
runtime_env={"working_dir": "."}
)
3.3. Docker & Kubernetes Deployment
When deploying inside Docker containers, set init: true to ensure clean process reaping:
version: '3.8'
services:
headnode:
image: pymapreduce:latest
init: true
command: ["mapreduce", "start", "--head", "--port", "7777"]
ports:
- "7777:7777"
workernode:
image: pymapreduce:latest
init: true
command: ["mapreduce", "start", "--worker", "--head-addr", "headnode:7777"]
depends_on:
- headnode
4. Task Scheduling Strategies
Configure how tasks are scheduled across available workers:
| Strategy | Python Enum / CLI Flag | Description & Best Use Case |
|---|---|---|
| Adaptive (Default) |
SchedulerStrategy.Adaptive--scheduler Adaptive |
Evaluates real-time network bandwidth (EMA), CPU load, and data locality. Best for heterogeneous production clusters. |
| LocalityFirst | SchedulerStrategy.LocalityFirst--scheduler LocalityFirst |
Prioritizes dispatching tasks to the worker already holding required data in RAM to minimize network transfers. |
| LeastLoad | SchedulerStrategy.LeastLoad--scheduler LeastLoad |
Dispatches tasks to the worker with the fewest active tasks. Best for long-running compute jobs. |
| WeightedCapacity | SchedulerStrategy.WeightedCapacity--scheduler WeightedCapacity |
Weights assignment based on each worker's physical CPU cores and available RAM size. |
| RoundRobin | SchedulerStrategy.RoundRobin--scheduler RoundRobin |
Rotates tasks evenly across all available workers. Ideal for baseline benchmarking. |
5. Command Line Interface (CLI)
# Start cluster coordinator (HeadNode)
mapreduce start --head --port 7777 --scheduler Adaptive
# Connect a worker node with 8 CPUs and 300s idle timeout
mapreduce start --worker --head-addr 127.0.0.1:7777 --cpus 8 --idle-timeout 300
# Submit a standalone script with a 60-second watchdog timeout
mapreduce submit pipeline.py --head-addr 127.0.0.1:7777 --max-time 60
6. Python API Reference
Top-Level Functions
| Function | Parameters | Description |
|---|---|---|
pymapreduce.init(...) |
address=None, runtime_env=None, scheduler=None |
Starts an embedded cluster coordinator and returns a connected Driver. |
pymapreduce.connect(...) |
head_node, workers=None, runtime_env=None |
Connects to an existing remote cluster coordinator. |
pymapreduce.connect_worker(...) |
head_addr, cpus=None, idle_timeout=0 |
Launches a background worker connected to the cluster and returns a WorkerHandle. |
@pymapreduce.remote(...) |
cls_or_func=None, idle_timeout=None |
Decorator turning a function into a distributed task or a class into a stateful actor. |
pymapreduce.kill(...) |
actor_handle |
Asynchronously purges an actor instance from worker memory and cluster registry. |
pymapreduce.from_items(...) |
items, num_partitions=None |
Creates a distributed Dataset from in-memory sequences. |
pymapreduce.read_csv(...) |
path_or_glob, num_partitions=None |
Creates a distributed Dataset by chunking CSV files. |
pymapreduce.from_pandas(...) |
df, num_partitions=None |
Creates a distributed Dataset from a Pandas DataFrame. |
pymapreduce.from_numpy(...) |
arr, num_partitions=None |
Creates a distributed Dataset from a NumPy array. |
Core Classes & Methods
| Class | Method | Description |
|---|---|---|
ActorHandle |
<method>.remote(*args, **kwargs) |
Dispatches an RPC call to the actor's FIFO mailbox on the worker node. |
ActorHandle |
destroy.remote() / kill.remote() |
Destroys this actor instance and cleans up allocated memory. |
ObjectRef |
await ref.get() |
Fetches the object from in-memory ObjectStore. |
ObjectRef |
ref.pin() / ref.unpin() |
Pins object in hot memory to prevent LRU cache eviction. |
WorkerHandle |
await handle.disconnect(graceful=True) |
Gracefully drains in-flight tasks and disconnects the worker. |
JobConfig |
JobConfig(name, max_time=None) |
Specifies job parameters and watchdog execution timeout in seconds. |
Dataset |
await ds.map(fn) / filter(fn) / flat_map(fn) |
Applies transformations across distributed partitions. |
Dataset |
await ds.map_batches(fn, batch_format="pandas") |
Applies batch transformations using Pandas, PyArrow, or NumPy. |
Dataset |
await ds.count() / take(n) / collect() |
Executes the pipeline and returns results. |
Dataset |
await ds.to_pandas() / to_arrow() |
Collects distributed partitions into a single Pandas DataFrame or PyArrow Table. |
7. Configuration & Environment Variables
| Environment Variable | Default | Description |
|---|---|---|
PYMAPREDUCE_MAX_ACTORS_PER_WORKER |
32 |
Maximum number of concurrently active actors per worker process before LRU eviction triggers. |
PYMAPREDUCE_ACTOR_IDLE_TIMEOUT |
0 (disabled) |
Default idle timeout (in seconds) for actors that do not specify an explicit idle_timeout. |
PYMAPREDUCE_MEMORY_THRESHOLD_PERCENT |
85.0 |
Host RAM threshold percentage. If system memory exceeds this percentage, LRU eviction activates proactively to avoid OOM crashes. |
PYMAPREDUCE_MAX_ACTOR_META |
1024 |
Maximum number of actor metadata entries cached for virtual lazy re-creation. |
8. License
PyMapReduce is open-source software licensed under the MIT License.
Metadata
Release files for pymapreduce-core 0.1.14
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pymapreduce_core-0.1.14.tar.gz | 101.1 kB | Without provenance | Details for pymapreduce_core-0.1.14.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pymapreduce_core-0.1.14-cp38-abi3-manylinux_2_28_x86_64.whl | CPython 3.8 | abi3 | Linux glibc 2.28+ x86-64 | Details for pymapreduce_core-0.1.14-cp38-abi3-manylinux_2_28_x86_64.whl |
Total release size: 1.7 MB
Release files / pymapreduce_core-0.1.14.tar.gz
| Download URL | pymapreduce_core-0.1.14.tar.gz |
|---|---|
| Size | 101.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
13661ac764b7c96cb7e1cb7e3a7b0e45e8a52ecf162738eed5f6f84640ec5b7b
|
|
BLAKE2b-256 checksum How to use checksums |
198688c41ce3ee629e67b3abf17cdb1981c16bf3200aacda1a63dce1fc50d1ed
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.3
|
Release files / pymapreduce_core-0.1.14-cp38-abi3-manylinux_2_28_x86_64.whl
| Download URL | pymapreduce_core-0.1.14-cp38-abi3-manylinux_2_28_x86_64.whl |
|---|---|
| Size | 1.6 MB |
| Tags | CPython 3.8 Linux glibc 2.28+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
2f2702dea1bbcb0cfb35925ace52d1569e42beb4d7fc1879cee083e81aae276a
|
|
BLAKE2b-256 checksum How to use checksums |
39d068ccb9394c7991585721a55aa1422ba0b9380e0d95184b209cfaa1db9443
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.3
|
Security for pymapreduce-core 0.1.14
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.