Skip to main content

🐍 PyMapReduce

PyPI version Python 3.8+ PyO3 AsyncIO

pymapreduce is the official Python SDK for the MapReduce Distributed Framework, a high-performance distributed computing engine written in Rust. Inspired by Ray, pymapreduce brings the speed, memory safety, and concurrency of Rust to Python developers through a clean, intuitive, and asynchronous API.


🚀 Key Capabilities

  • Ray-Like Developer Experience: Use @pymapreduce.remote to turn ordinary Python functions and classes into distributed tasks and stateful actors.
  • Stateful Actor Support: Maintain class instance state (e.g., ML weights, database connections, caching layers) in-memory across distributed method invocations.
  • Zero-Copy Tiered Object Store: Pass large datasets (ObjectRef) between tasks with automatic peer-to-peer fetching without routing bulky payloads through the driver.
  • True Multi-Core Parallelism (GIL-Free): Each worker runs in an isolated Python process via high-speed IPC (stdin/stdout binary framing), bypassing Python's Global Interpreter Lock (GIL).
  • Runtime Environment Synchronization: Automatically zip and push local module dependencies (runtime_env={"working_dir": "..."}) to remote worker nodes.
  • Embedded & Distributed Modes: Seamlessly transition from a local zero-setup embedded cluster to a multi-node production deployment.

📦 Installation & Build

Prerequisites

  1. Rust Toolchain (Cargo) (version 1.75+)
  2. Python 3.8+

Building from Source (Development Mode)

# 1. Create and activate a virtual environment
python3 -m venv .venv
source .venv/bin/activate

# 2. Install Maturin build tool
pip install maturin cloudpickle

# 3. Compile and install in editable development mode
maturin develop --release

Building Distribution Wheels

maturin build --release
pip install target/wheels/pymapreduce_automl-*.whl

💻 Usage Guide

1. Cluster Operation

Option A: Running with Python CLI (mapreduce)

# Start HeadNode (Central scheduler & GCS on port 7777)
mapreduce start --head --port 7777 --scheduler Adaptive

# Start WorkerNode on compute machines
mapreduce start --worker --head-addr 127.0.0.1:7777 --cpus 4

Option B: Embedded Single-Node Mode (Notebooks & Local Dev)

You can spawn a local cluster programmatically in your application with zero setup:

import asyncio
import pymapreduce

async def main():
    # Automatically starts local HeadNode
    driver = await pymapreduce.DriverWrapper.init()

    # Launch background worker with 4 cores
    asyncio.ensure_future(pymapreduce.start_worker("127.0.0.1:7777", 4))
    await asyncio.sleep(2) # Allow worker to register

2. Programming Paradigms

A. Stateless Distributed Tasks (Functions)

import asyncio
import pymapreduce

# Decorate function to run remotely on worker nodes
@pymapreduce.remote
def square(x: int) -> int:
    return x * x

async def main():
    # Connect to the cluster
    driver = await pymapreduce.DriverWrapper.init("127.0.0.1:7777")

    # 1. Execute a single task
    res = await square.remote(10)
    print("Single Task Result:", res) # 100

    # 2. Execute parallel tasks across the cluster
    tasks = [square.remote(i) for i in range(10)]
    results = await asyncio.gather(*tasks)
    print("Parallel Results:", results) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

if __name__ == "__main__":
    asyncio.run(main())

B. Stateful Distributed Actors (Classes)

Actors maintain persistent state in worker memory across multiple remote method calls:

import asyncio
import pymapreduce

@pymapreduce.remote
class CounterActor:
    def __init__(self, initial_value: int = 0):
        self.count = initial_value

    def increment(self, step: int = 1) -> int:
        self.count += step
        return self.count

    def get_value(self) -> int:
        return self.count

async def main():
    driver = await pymapreduce.DriverWrapper.init("127.0.0.1:7777")

    # Instantiate Actor on a dedicated worker
    counter = await CounterActor.remote(initial_value=100)

    # Subsequent method invocations route deterministically to the same worker instance
    await counter.increment.remote(5)
    await counter.increment.remote(10)
    final_count = await counter.get_value.remote()

    print("Actor Value:", final_count) # 115

if __name__ == "__main__":
    asyncio.run(main())

C. Passing Large Objects (ObjectRef & Zero-Copy Pipeline)

When a task produces large outputs (e.g. DataFrames, Numpy arrays, ML models), the framework stores the binary payload in the tiered ObjectStore and returns a lightweight ObjectRef.

import asyncio
import pymapreduce
import pandas as pd

@pymapreduce.remote
def load_dataset() -> pd.DataFrame:
    # Heavy data loading
    return pd.DataFrame({"feature": range(1000000), "target": [1] * 1000000})

@pymapreduce.remote
def train_model(df: pd.DataFrame):
    return f"Model trained on {len(df)} rows"

async def main():
    driver = await pymapreduce.DriverWrapper.init("127.0.0.1:7777")

    # 1. load_dataset returns an ObjectRef handle
    data_ref = await load_dataset.remote()
    print("Object Reference:", data_ref.object_id)

    # 2. Pass data_ref directly into downstream task (P2P zero-copy transfer)
    result = await train_model.remote(data_ref)
    print("Training Output:", result)

    # 3. Or explicitly fetch data to driver if needed
    raw_df = await driver.get(data_ref.object_id)
    print("Fetched DataFrame Shape:", raw_df.shape)

if __name__ == "__main__":
    asyncio.run(main())

D. Dynamic Module Sync (runtime_env)

Ship custom Python scripts and modules to remote workers on the fly:

driver = await pymapreduce.DriverWrapper.init(
    address="192.168.1.100:7777",
    runtime_env={"working_dir": "./my_local_modules"}
)

🎛️ Low-Level Job API

For granular control over task dependencies, retry policies, and timeouts:

import pymapreduce

# Create custom job
job = pymapreduce.JobConfig("CustomPipeline")
job.with_max_time(120) # 120 seconds timeout limit

# Define task inputs
task = pymapreduce.TaskInput(pymapreduce.TaskKind.Map, (my_func, (arg1, arg2)))
job.add_task(task)

# Submit to cluster
results = await driver.submit(job)

🔬 Architecture Under The Hood

┌─────────────────────────────────────────────────────────────┐
│                      Python Driver (GIL)                    │
│   @remote calls -> cloudpickle serialization -> ObjectRef   │
└──────────────────────────────┬──────────────────────────────┘
                               │ PyO3 + Tokio Async Channels
┌──────────────────────────────▼──────────────────────────────┐
│                    Rust Worker Engine Core                  │
│    - Length-delimited TCP framing (up to 70MB per chunk)     │
│    - Semaphore back-pressure (physical CPU bounds)          │
│    - Tiered Object Store (Hot RAM -> Warm Disk LRU Spill)   │
└──────────────────────────────┬──────────────────────────────┘
                               │ IPC Binary Pipe (stdin/stdout)
┌──────────────────────────────▼──────────────────────────────┐
│                  Python Daemon Subprocess                   │
│    - Worker loop executing pure Python code                 │
│    - Dedicated memory space per worker process              │
│    - Exception tracebacks captured & reported to GCS        │
└─────────────────────────────────────────────────────────────┘

📜 License

Distributed under the MIT / Apache-2.0 License.

Metadata

Release files for pymapreduce-core 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pymapreduce-core 0.1.1
File Size Uploaded Provenance Actions
pymapreduce_core-0.1.1.tar.gz 320.0 kB Without provenance Details for pymapreduce_core-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pymapreduce-core 0.1.1
File Interpreter ABI Platform Actions
pymapreduce_core-0.1.1-cp312-cp312-manylinux_2_39_x86_64.whl CPython 3.12 CPython 3.12 Linux glibc 2.39+ x86-64 Details for pymapreduce_core-0.1.1-cp312-cp312-manylinux_2_39_x86_64.whl

Total release size: 1.9 MB

Release files / pymapreduce_core-0.1.1.tar.gz

Download URL pymapreduce_core-0.1.1.tar.gz
Size 320.0 kB
Tags Source
SHA-256 checksum
How to use checksums
12d396726d50c86c0e9376d0a0bde5461bc84c8aa245cfa7c08f9035dcf967fb
BLAKE2b-256 checksum
How to use checksums
483be90524b8be898cbff6ececcdd3ff343c314943c785d0b5b7e88744011091
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.1-cp312-cp312-manylinux_2_39_x86_64.whl

Download URL pymapreduce_core-0.1.1-cp312-cp312-manylinux_2_39_x86_64.whl
Size 1.6 MB
Tags CPython 3.12 Linux glibc 2.39+ x86-64
SHA-256 checksum
How to use checksums
f4e81dc552cf34fb4776c5339b509e1ccf23555aa6993e95d4bc6e1fc588bf08
BLAKE2b-256 checksum
How to use checksums
17367175b1e3cc81a6c53df3ace37d7a3597c9e6ef33362fdf1a398e0181a3e0
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.1

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page