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
driver = await pymapreduce.init()
await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)
# Run tasks in parallel
futures = [square.remote(i) for i in range(5)]
results = await asyncio.gather(*futures)
print("Parallel Squares:", results) # [0, 1, 4, 9, 16]
# Instantiate and call actor
counter = await Counter.remote(start=10)
print("Counter:", await counter.increment.remote(5)) # 15
# Clean up actor
await pymapreduce.kill(counter)
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 = await process_item.remote(10, 2.5)
print("Single Result:", res)
# 2. Parallel execution
futures = [process_item.remote(i, 2.5) for i in range(10)]
results = await asyncio.gather(*futures)
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 loaded in worker memory, preserving state across method calls:
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 model.predict.remote([1.0, 2.0, 3.0])
p2 = await model.predict.remote([4.0, 5.0])
stats = await model.get_stats.remote()
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 Self-Protection
To prevent memory leaks from abandoned actors and protect workers from running out of RAM (OOM), PyMapReduce provides built-in memory protection:
- Idle Timeout (TTL): Automatically unload the actor instance if no calls are received for a specified duration.
- Global LRU Eviction: Evict the least recently used actor when the worker's actor limit is reached.
- Lazy Re-creation: If an evicted actor is called again, it transparently reconstructs itself.
- RAM Safety Watchdog: Proactively unloads idle actors and clears GPU VRAM cache when system RAM exceeds 85%.
@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):
"""Optional hook called when actor is unloaded or destroyed."""
print("Releasing resources...")
2.4. Automatic Code Shipping (runtime_env)
When distributing code across multiple physical servers, use runtime_env to automatically package and synchronize your project folder (respecting .gitignore):
import asyncio
import pymapreduce
async def main():
# Connect and automatically package & sync local project files to all 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 serialization)
summary = await compute_summary.remote(df_ref)
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 = pymapreduce.from_items(range(1, 100_001), num_partitions=8)
# Alternatively: ds = await pymapreduce.read_csv("data/*.csv", num_partitions=8)
# 2. Lazy transformation pipeline
transformed = (
ds.map(lambda x: x * 2)
.filter(lambda x: x % 4 == 0)
.persist(pymapreduce.StorageLevel.MEMORY_ONLY)
)
# 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 Execution Timeouts
Prevent hung jobs by configuring a watchdog execution timeout:
import asyncio
import pymapreduce
async def main():
driver = await pymapreduce.init()
await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)
# Set a maximum execution timeout of 30 seconds for this job
config = pymapreduce.JobConfig("AnalyticsJob", max_time=30)
# Submit job
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 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": "."}
)
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 production multi-node clusters. |
| LocalityFirst | SchedulerStrategy.LocalityFirst--scheduler LocalityFirst |
Prioritizes dispatching tasks to the worker already holding required data in RAM to minimize network transfer. |
| 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 RAM size. |
| RoundRobin | SchedulerStrategy.RoundRobin--scheduler RoundRobin |
Rotates tasks evenly across all available workers. Ideal for benchmark baselines. |
5. Command Line Interface (CLI)
# Start cluster coordinator (HeadNode)
mapreduce start --head --port 7777 --scheduler Adaptive
# Connect a worker node
mapreduce start --worker --head-addr 127.0.0.1:7777 --cpus 8
# Submit a standalone script with a 60-second 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 state. |
pymapreduce.from_items(...) |
items, num_partitions=None |
Creates a distributed Dataset from in-memory items. |
pymapreduce.read_csv(...) |
path_or_glob, num_partitions=None |
Creates a distributed Dataset by chunking a CSV file. |
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 |
map(fn) / filter(fn) / flat_map(fn) |
Applies transformations across distributed partitions. |
Dataset |
map_batches(fn, batch_format="pandas") |
Applies batch transformations using Pandas, PyArrow, or NumPy. |
Dataset |
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.13
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.13.tar.gz | 333.2 kB | Without provenance | Details for pymapreduce_core-0.1.13.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pymapreduce_core-0.1.13-cp38-abi3-manylinux_2_28_x86_64.whl | CPython 3.8 | abi3 | Linux glibc 2.28+ x86-64 | Details for pymapreduce_core-0.1.13-cp38-abi3-manylinux_2_28_x86_64.whl |
Total release size: 1.8 MB
Release files / pymapreduce_core-0.1.13.tar.gz
| Download URL | pymapreduce_core-0.1.13.tar.gz |
|---|---|
| Size | 333.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4fbfafc4a190e3c97aeb9d1ea01d625434d33cfa3572f812703e8d5ac71c8bba
|
|
BLAKE2b-256 checksum How to use checksums |
ab4b1067c7fa51fce9918b4ec56f54329f9bf22b7f4e7f390d111e14d1007ea5
|
| 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.13-cp38-abi3-manylinux_2_28_x86_64.whl
| Download URL | pymapreduce_core-0.1.13-cp38-abi3-manylinux_2_28_x86_64.whl |
|---|---|
| Size | 1.5 MB |
| Tags | CPython 3.8 Linux glibc 2.28+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
6fe58b1efc09da9c7a2285ec3f35765876b0b0037e65af4caaf16d79054e3825
|
|
BLAKE2b-256 checksum How to use checksums |
d57449818a2c04c860fa645b64a405b6b593f56cb0b515f8a7a57c84002c58c8
|
| 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.13
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.