Python: Unpickle (or similar) generator

Status
Not open for further replies.

lostnihilist

Ars Scholae Palatinae
1,436
I was trying to use Hadoop's streaming pattern to use python code on a largish data set. However, uploading my data to the cluster actually takes approximately forever (I've not yet actually succeeded in doing so), and I'm sick of attempting to churn processes to keep my reservation active and all this other BS that is a waste of my time.

So, I decided to waste my time by writing my own little mini, single threaded map reduce functionality in python.

It is up and running and runs the scripts fine (though instead of using stdin/stdout, i'm passing things around with generators and such). However, one thing that I'm not very happy with is that as I'm sorting the data and caching it to disk (it is much too large to store all in memory at once), I am needing to convert from a python representation of the data (a sorted list of two tuples (key, value) pairs) to a flat file, forcing myself to write functions to convert to and from the flat file format back into the appropriate python representation. For merging the data, I just have a heap of tuples of the first (parsed) line of each file and the file handle, pop from the (min) heap, send the line to be processed, and replace that item in the heap with the next line from the file handle and the file handle itself.

What I'd rather do, if it is possible and faster, is have the python data be written as such, without the need to write converters for it. But, I don't want - can't, really -to read the entire file into memory at once. I'd rather just read each item from the cached list at a time.

Perhaps a bit of pseudo-Python will make this more clear:

Code:
def cache(iterable, filename):
    """Write iterable to a new file located at filename"""

def uncache(filename):
    for item in uncached.process(filename):
        yield item

with it being quite important that uncache being not too aggressive about reading forward into the file as I'll have some several thousand files open and caching all that will get expensive.

edit: If it wasn't obvious, I would basically want to do something like:
my_reducer(heapq.merge(uncache(x) for x in os.listdir(tmpfiles)))
 

herko

Tone down Your Control issues.
7,014
Moderator
I've done a very similar thing before. My solution is (I'll post code later if I have a bit of time):

Create a queue. Set the size of the queue to how far ahead you want to read.
Spawn a thread to do the actual reading. The thread reads, then places the items in the queue. When the queue is full, the put operation will block, stalling the read.
In the generator, pop items from the queue and yield them.
 

herko

Tone down Your Control issues.
7,014
Moderator
Here's code to generate the sample file you'll need for the actual example. The size of the output is obviously variable. On my machine it was 580 Mb.

It just builds some big heterogeneous objects and pickles them one by one to a file.

Code:
# gen_objects.py

import random
import pickle

class BigBadObject(object):
	def __init__(self):
		self.a_dictionary={}
		for x in xrange(random.randint(1, 1000)):
			self.a_dictionary[random.randint(1,98675676)]=random.random()
		self.a_list=[]
		for x in xrange(random.randint(1000, 10000)):
			self.a_list.append(random.random())
		self.a_string=''.join([chr(random.randint(65, 90)) 
							   for x in xrange(random.randint(100, 10000))])

if __name__=="__main__":
	output=open('lotsa_objects.pickled', 'wb')
	for i in xrange(10000):
		pickle.dump(BigBadObject(), output, pickle.HIGHEST_PROTOCOL)
	output.close()

And here is an example of a reader that unpickles in a background thread, while making that available via a queue to another thread. I've put in a bit of a delay after starting the thread to allow the queue to fill up for demonstration purposes. It will compute an average, just to have something to do, and then print it.

Code:
# reader.py

from threading import Thread
from Queue import Queue, Empty
import cPickle as pickle
import time
import operator

from gen_objects import BigBadObject

class Reader(Thread):
	def __init__(self, filename, q):
		Thread.__init__(self, target=None)
		self._file=open(filename, 'rb')
		self._queue=q
	def run(self):
		while True:
			try:
				one_object=pickle.load(self._file)
			except EOFError:
				break
			self._queue.put(one_object)
	
class uncached(object):
	def __init__(self, filename, queue_size=100):
		self._my_queue=Queue(maxsize=queue_size)
		self._my_reader=Reader(filename, self._my_queue)
		self._my_reader.start()
		time.sleep(1.0) # Give the reader a head start for demo purposes
	def __iter__(self):
		while True:
			if not self._my_reader.is_alive():
				break
			# Loop until we get something or the thread is done processing.
			try:
				print "Getting from the queue. Queue size=", self._my_queue.qsize()
				o=self._my_queue.get(True, timeout=0.1) # Block for 0.1 seconds 
				yield o
			except Empty:
				pass
		return

# Compute an average of all the numbers in a_lists, just for show.
list_avg=0.0
list_count=0

for x in uncached('lotsa_objects.pickled'):
	list_avg+=reduce(operator.add, x.a_list)
	list_count+=len(x.a_list)

print "Average: ", list_avg/list_count

Note that thanks to the GIL, this will max out at about 101% CPU utilization on a multicore system.
 

lostnihilist

Ars Scholae Palatinae
1,436
Ok, I'm sorry. I've totally misunderstood pickle.load. I always thought the entire file was loaded instead of the first object. I guess it has never been an issue for me since I've always created a container for all the data I was pickling before pickling it. But now that I see that, this is trivial, though now I'm not sure that it is the right approach. It is hard to know how fast pickle is at doing its thing. I'm starting to get the impression that it is quite slow.
 

herko

Tone down Your Control issues.
7,014
Moderator
pickle.load will load as much as it needs to get an entire object. If the file contains only one object, it'll load that and be done. But yes, if you pickle serially you can use pickle.load repeatedly and that might be a much simpler solution overall for you.

Make sure you're using cPickle and not plain old pickle, as it's much, much faster. Also, you might get some performance gains from using pickle.HIGHEST_PROTOCOL as it's more compact than the default.

Finally, if you don't care about some of the state of your objects, look at the __setstate__ and __getstate__ methods. You may be able to come up with a faster/more compact representation of your objects and regenerate some state upon loading.
 
Status
Not open for further replies.