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).
  • High-Performance runtime_env: Automatically packages project source code with .gitignore and default excludes, extracts once into shared memory (/dev/shm), and provides 3-tier automatic lifecycle cleanup.
  • $O(1)$ Load-Balancing & Adaptive Scheduler: Dynamic task routing preventing deadlocks and maximizing CPU utilization across multiple physical nodes.
  • Embedded & Distributed Modes: Seamlessly transition from a local zero-setup embedded cluster (pymapreduce.init()) 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_core-0.1.3-*.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.9

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.9
File Size Uploaded Provenance Actions
pymapreduce_core-0.1.9.tar.gz 322.5 kB Without provenance Details for pymapreduce_core-0.1.9.tar.gz

Built distribution (wheel)

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

Total release size: 1.7 MB

Release files / pymapreduce_core-0.1.9.tar.gz

Download URL pymapreduce_core-0.1.9.tar.gz
Size 322.5 kB
Tags Source
SHA-256 checksum
How to use checksums
6adff2f284f19eaa407f30af19b225c4d083813169e61449786844bac2384631
BLAKE2b-256 checksum
How to use checksums
dacedfcbf0e4fd6af57dfb132c450496fadb7aa46d170482c9886326705bad0f
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.9-cp312-cp312-manylinux_2_28_x86_64.whl

Download URL pymapreduce_core-0.1.9-cp312-cp312-manylinux_2_28_x86_64.whl
Size 1.4 MB
Tags CPython 3.12 Linux glibc 2.28+ x86-64
SHA-256 checksum
How to use checksums
4b02ea3037f6b87aa71bd30815834c0fbb5e3a51092e77a9508058391abcdea7
BLAKE2b-256 checksum
How to use checksums
29c80edad2c68348e52dbc72507337c373232f69899202550ab01c2bc11d7e1b
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.9

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