IPython.parallel doesn't do much in the way of serialization. It has custom zero-copy handling of numpy arrays, but other than that, it doesn't do anything other than the bare minimum to make basic interactively defined functions and classes sendable.
There are a few projects that extend pickle to make just about anything sendable, and one of these is dill.
NOTE: This requires IPython 1.0-dev and latest dill, currently only available from:
pip install dill-0.2a.dev-20120503.tar.gz
First, as always, we create our
def make_closure(a):
"""make a function with a closure, and return it"""
def has_closure(b):
return a * b
return has_closure
closer = make_closure(5)
closer(2)
import pickle
Without help, pickle can't deal with closures
pickle.dumps(closer)
But after we import dill, magic happens
import dill
pickle.dumps(closer)[:64] + '...'
So from now on, pretty much everything is pickleable.
As usual, we start by creating our Client and View
from IPython import parallel
rc = parallel.Client()
view = rc.load_balanced_view()
We can use dill to allow IPython.parallel to send anything.
Step 1. Disable IPython's special handling of function objects (nothing to work around anymore):
from types import FunctionType
from IPython.utils.pickleutil import can_map
can_map.pop(FunctionType, None)
Step 2. Switch the serialize module to use Python pickle instead of cPickle (dill extends pickle
to be able to dump anything, but this doesn't work with the optimized cPickle)
from IPython.kernel.zmq import serialize
serialize.pickle = pickle
And that's it! Now we can send closures and other previously non-pickleables to our engines.
view.apply_sync(closer, 3)
But wait, there's more!
view.apply_sync(make_closure, 2)
We can also apply very same patch to the engines, then we can send previously unpickleable objects both ways. Here's a way to do dill patch the pickle everywhere at once:
%%px --local
# load dill
import dill
# disable special function handling
from types import FunctionType
from IPython.utils.pickleutil import can_map
can_map.pop(FunctionType, None)
# fallback to pickle instead of cPickle, so that dill can take over
import pickle
from IPython.kernel.zmq import serialize
serialize.pickle = pickle
remote_closure = view.apply_sync(make_closure, 4)
remote_closure(5)
At this point, we can send/recv all kinds of stuff
def outer(a):
def inner(b):
def inner_again(c):
return c * b * a
return inner_again
return inner
So outer returns a function with a closure, which returns a function with a closure.
Now, we can resolve the first closure on the engine, the second here, and the third on a different engine, after passing through a lambda we define here and call there, just for good measure.
view.apply_sync(lambda f: f(3),view.apply_sync(outer, 1)(2))