Simulate a MapReduce framework using Python multiprocessing. Implement a generic map_reduce function that partitions input, spawns worker processes for map phase, shuffles and sorts intermediate keys, and runs reduce phase in parallel.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The plan defines a generic Python multiprocessing map_reduce function that partitions input, maps over chunks with worker processes producing key-value pairs, shuffles by grouping and sorting keys, then reduces each key-group in parallel, and returns aggregated results. The approach uses top-level functions for pickling, careful chunking to balance workload, and pools for both map and reduce phases to simulate distributed MapReduce behavior.
Here's a minimal, generic MapReduce “framework” using the multiprocessing module. It partitions the input into chunks, runs the map phase in parallel processes, shuffles/sorts the intermediate keys, and then runs the reduce phase in parallel:
python
import multiprocessing as mp
from collections import defaultdict
from typing import Iterable, Any, Callable, List, Tuple
def chunkify(seq, n_chunks):
"""Yield n_chunks slices from seq as evenly as possible."""
n_chunks = max(1, n_chunks)
k, m = divmod(len(seq), n_chunks)
for i in range(n_chunks):
start = i * k + min(i, m)
end = (i + 1) * k + min(i + 1, m)
chunk = seq[start:end]
if chunk:
yield chunk
def _map_worker(mapper: Callable[[Any], Iterable[Tuple[Any, Any]]], chunk):
"""Run the mapper over a chunk of input records."""
out = []
for record in chunk:
pairs = mapper(record)
if pairs is None:
continue
for kv in pairs:
out.append(kv)
return out
def _reduce_worker(args):
"""Run the reducer on a single (key, [values]) group."""
key, values, reducer = args
return key, reducer(key, values)
def map_reduce(
data: List[Any],
mapper: Callable[[Any], Iterable[Tuple[Any, Any]]],
reducer: Callable[[Any, List[Any]], Any],
num_workers: int = None,
):
"""
Simulate MapReduce over `data`.
mapper: function that takes a record and yields (key, value) pairs.
reducer: function that takes a key and list of values, and returns a reduced value.
"""
if num_workers is None:
num_workers = mp.cpu_count()
# Partition input
chunks = list(chunkify(data, num_workers))
# Map phase
with mp.Pool(processes=num_workers) as pool:
map_results = pool.starmap(_map_worker, [(mapper, chunk) for chunk in chunks])
# Shuffle and sort
grouped = defaultdict(list)
for pairs in map_results:
for k, v in pairs:
grouped[k].append(v)
# Reduce phase (process each key group in parallel)
reduce_args = [(k, grouped[k], reducer) for k in sorted(grouped.keys())]
with mp.Pool(processes=num_workers) as pool:
reduced = pool.map(_reduce_worker, reduce_args)
return dict(reduced)
# Example usage: word count
if __name__ == "__main__":
lines = [
"to be or not to be",
"that is the question",
"whether tis nobler in the mind",
]
def map_words(line):
for word in line.split():
yield word, 1
def reduce_counts(key, values):
return sum(values)
counts = map_reduce(lines, map_words, reduce_counts)
for word, count in counts.items():
print(f"{word}: {count}")
In this example map_reduce splits the input lines into chunks, runs map_words across them in parallel, groups the intermediate (word,1) pairs by word, and then runs reduce_counts on each word’s list of counts in parallel.