multithreading Pool resulting in non-random numbers - python-3.x

I previously asked Repeatedly run a function in parallel on how to run a function in parallel. The function that I am wanting to run has a stochastic element, where random integers are drawn.
When I use the code in that answer it returns repeated numbers within one process (and also between runs if I add an outer loop to repeat the process). For example,
import numpy as np
from multiprocessing.pool import Pool
def f(_):
x = np.random.uniform()
return x*x
if __name__ == "__main__":
processes = 3
p = Pool(processes)
print(p.map(f, range(6)))
returns
[0.8484870744666029, 0.8484870744666029, 0.04019012715175054, 0.04019012715175054, 0.7741414835156634, 0.7741414835156634]
Another run may give
[0.17390735240615365, 0.17390735240615365, 0.5188673758527017, 1.308159884267618e-08, 0.09140498447418667, 0.021537291489524404]
It seems as if there is some internal seed that is being used -- how can I generate random numbers similar to what would be returned from np.random.uniform(size=6) please?

Same output in different workers in multiprocessing indicates that the seed needs to be included in the function. Python multiprocessing pool.map for multiple arguments provides a way to pass multiple arguments to Pool -- one for the repeats and one for a list of seeds. This allows for a new seed for each process, and is reproducible.
import numpy as np
from multiprocessing.pool import Pool
def f(reps, seed):
np.random.seed(seed)
x = np.random.uniform()
return x*x
#np.random.seed(1)
if __name__ == "__main__":
processes = 3
p = Pool(processes)
print(p.starmap(f, zip(range(6), range(6))))
Where the second argument is the vector of seeds (to see change the line to print(p.starmap(f, zip(range(0,6), np.repeat(1,6)))))

Related

How do I run two python functions simultaneously and stop others when any one them returns a value?

I want to write two python functions that request data from two different APIs (with similar data). Both the functions should start simultaneously and as soon as one of the functions (say fun1()) returns the result, the other function (say fun2()) is terminated and the rest of the program is carried out with the result obtained from fun1().
For example,
from datetime import datetime
def fun1(n): #Obtaining data from Source 1
sums = -1
if n > -1:
sums = sum([x*x for x in range(n)])
return sums
def fun2(n): #Obtaining data from source 2
sums = -1
if n > -1:
sums = (n*(2*n+1)*(n+1))/6
return int(sums)
if __name__ == '__main__':
no = 999999
print(fun1(no)) #Function Call 1
print(fun2(no)) #Function Call 2
So I want to run both the functions fun1() and fun2() simultaneously so that as soon as one of them returns the value, the program stops the other function and prints the value from fun1().
I tried to explore multiprocessing in python that offers parallel processing but in addition to that, I'm looking for some solution that stops other functions as soon as one of the functions returns some value.
Note: I'm using Python 3.10.6 on Ubuntu. The program above is just a dummy program to represent the problem.

How to accelerate the application of the following for loop and function?

I have the following for loop:
for j in range(len(list_list_int)):
arr_1_, arr_2_, arr_3_ = foo(bar, list_of_ints[j])
arr_1[j,:] = arr_1_.data.numpy()
arr_2[j,:] = arr_2_.data.numpy()
arr_3[j,:] = arr_3_.data.numpy()
I would like to apply foo with multiprocessing, mainly because it is taking a lot of time to finish. I tried to do it in batches with funcy's chunks method:
for j in chunks(1000, list_list_int):
arr_1_, arr_2_, arr_3_ = foo(bar, list_of_ints[j])
arr_1[j,:] = arr_1_.data.numpy()
arr_2[j,:] = arr_2_.data.numpy()
arr_3[j,:] = arr_3_.data.numpy()
However, I am getting list object cannot be interpreted as an integer. What is the correct way of applying foo using multiprocessing?
list_list_int = [1,2,3,4,5,6]
for j in chunks(2, list_list_int):
for i in j:
avg_, max_, last_ = foo(bar, i)
I don't have chunks installed, but from the docs I suspect it produces (for size 2 chunks, from:
alist = [[1,2],[3,4],[5,6],[7,8]]
j = [[1,2],[3,4]]
j = [[5,6],[7,8]]
which would produce an error:
In [116]: alist[j]
TypeError: list indices must be integers or slices, not list
And if your foo can't work with the full list of lists, I don't see how it will work with that list split into chunks. Apparently it can only work with one sublist at a time.
If you are looking to perform parallel operations on a numpy array, then I would use Dask.
With just a few lines of code, your operation should be able to be easily ran on multiple processes and the highly developed Dask scheduler will balance the load for you. A huge benefit to Dask compared to other parallel libraries like joblib, is that it maintains the native numpy API.
import dask.array as da
# Setting up a random array with dimensions 10K rows and 10 columns
# This data is stored distributed across 10 chunks, and the columns are kept together (1_000, 10)
x = da.random.random((10_000, 10), chunks=(1_000, 10))
x = x.persist() # Allow the entire array to persist in memory to speed up calculation
def foo(x):
return x / 10
# Using the native numpy function, apply_along_axis, applying foo to each row in the matrix in parallel
result_foo = da.apply_along_axis(foo, 0, x)
# View original contents
x[0:10].compute()
# View sample of results
result_foo = result_foo.compute()
result_foo[0:10]

What is the usage of MPI in python3?

I'm trying to find the usage of mpi4py for multiprocessing in python3. In docs i read bout ranks and their usage, and how to transfer data from a rank to another, but I could not understand how to implement it, suppose I have function that i want to run on one processor, so should I write that function under if rank == 0, and for another function if rank == 1 ..., The syntax here is confusing me. Is it like spawning process1 = multiprocessing.Process()
MPI4PY provides bindings of the Message Passing Interface (MPI) standard for the Python and allows any Python program to exploit multiple processors.
It supports communications of any picklable Python object
point-to-point (sends, receives)
collective (broadcasts, scatters, gathers)
An example for collective scatters,
consider a list having values 0 to 79
import mpi4py
from mpi4py import MPI
mpi4py.rc.initialize = True
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
def processParallel(unitList):
subList=[i**2 for i in unitList]
return subList
if comm.rank == 0:
#Read the data in to a list
elementList=list(range(80))
#divide the data in do different chunks [small groups]
mainList = [elementList[x:x+10] for x in range(0, len(elementList), 10)]
else:
mainList = None
unitList = comm.scatter(mainList, root=0)
comm.Barrier()
processedResult=processParallel(unitList)
# Gathering the results back to Rank 0
final_detected_data = comm.gather(processedResult, root=0)
if comm.rank == 0:
print(final_detected_data)
Run the code as : python -n python eg : python -n 8 python sample.py
Compare the time taken to process the entire list

"Maximum recursion depth exceeded" when using lru_cache

I wanted to calculate a recursive function using lru_cache. Here is a simplified version of it:
from functools import lru_cache
#lru_cache(maxsize=None)
def f(n:int)->int:
if (n==0): return 1
return n+f(n-1)
### MAIN ###
print(f(1000))
It works well when I run f(100), but with f(1000) I get:
RecursionError: maximum recursion depth exceeded in comparison
One solution is to calculate a table of values for f myself. Is there a solution that does not require me to manually create a table of values?
Note that you can use your function as-is, but you need to ensure each fresh call doesn't have to recurse more than several hundred levels before it hits a cached value or recursive base case; e.g.,
>>> f(400)
80201
>>> f(800) # will stop recursing at 400
320401
>>> f(1000) # will stop recursing at 800
500501
I've resorted to that at times ;-) More generally, you could write a wrapper function that repeatedly tries f(n), catches RecursionError, and backs off to calling it with ever-smaller values of n. For example,
def superf(n, step=400):
pending = []
while True:
pending.append(n)
try:
f(n)
break
except RecursionError:
n = max(n - step, 0)
while pending:
x = f(pending.pop())
return x
Then
>>> superf(100000)
5000050001

Python fails to parallelize buffer reads

I'm having performances issues in multi-threading.
I have a code snippet that reads 8MB buffers in parallel:
import copy
import itertools
import threading
import time
# Basic implementation of thread pool.
# Based on multiprocessing.Pool
class ThreadPool:
def __init__(self, nb_threads):
self.nb_threads = nb_threads
def map(self, fun, iter):
if self.nb_threads <= 1:
return map(fun, iter)
nb_threads = min(self.nb_threads, len(iter))
# ensure 'iter' does not evaluate lazily
# (generator or xrange...)
iter = list(iter)
# map to results list
results = [None] * nb_threads
def wrapper(i):
def f(args):
results[i] = map(fun, args)
return f
# slice iter in chunks
chunks = [iter[i::nb_threads] for i in range(nb_threads)]
# create threads
threads = [threading.Thread(target = wrapper(i), args = [chunk]) \
for i, chunk in enumerate(chunks)]
# start and join threads
[thread.start() for thread in threads]
[thread.join() for thread in threads]
# reorder results
r = list(itertools.chain.from_iterable(map(None, *results)))
return r
payload = [0] * (1000 * 1000) # 8 MB
payloads = [copy.deepcopy(payload) for _ in range(40)]
def process(i):
for i in payloads[i]:
j = i + 1
if __name__ == '__main__':
for nb_threads in [1, 2, 4, 8, 20]:
t = time.time()
c = time.clock()
pool = ThreadPool(nb_threads)
pool.map(process, xrange(40))
t = time.time() - t
c = time.clock() - c
print nb_threads, t, c
Output:
1 1.04805707932 1.05
2 1.45473504066 2.23
4 2.01357698441 3.98
8 1.56527090073 3.66
20 1.9085559845 4.15
Why does the threading module miserably fail at parallelizing mere buffer reads?
Is it because of the GIL? Or because of some weird configuration on my machine, one process
is allowed only one access to the RAM at a time (I have decent speed-up if I switch ThreadPool for multiprocessing.Pool is the code above)?
I'm using CPython 2.7.8 on a linux distro.
Yes, Python's GIL prevents Python code from running in parallel across multiple threads. You describe your code as doing "buffer reads", but it's really running arbitrary Python code (in this case, iterating over a list adding 1 to other integers). If your threads were making blocking system calls (like reading from a file, or from a network socket), then the GIL would usually be released while the thread blocked waiting on the external data. But since most operations on Python objects can have side effects, you can't do several of them in parallel.
One important reason for this is that CPython's garbage collector uses reference counting as its main way to know when an object can be cleaned up. If several threads try to update the reference count of the same object at the same time, they might end up in a race condition and leave the object with the wrong count. The GIL prevents that from happening, as only one thread can be making such internal changes at a time. Every time your process code does j = i + 1, it's going to be updating the reference counts of the integer objects 0 and 1 a couple of times each. That's exactly the kind of thing the GIL exists to guard.

Resources