Performing net-surgery in pycaffe on a caffe.SGDSolver net
I have an issue concerning the python wrapper. It seems that a network initialized by the caffe.SGDSolver provides only part of the functionality of a network initialized through caffe.Net. Specifically I tried to use the backward() method as well as the net surgery trick (copy weights from a caffe.Net to a caffe.SGDSolver net) without success. Everything executes, however, without the expected behavior.
In the following you find my example code for the net surgery. It seems to me that in the background no params are copied. Since I have only a very limited understanding of the python wrapper, I wonder if this is expected behavior and the caffe.SGDSolver net only allows read-only access. Do the efforts in https://github.com/BVLC/caffe/pull/1228 provide a possible workaround?
# init SGD solver (using memory data layers for train and test)
solver = caffe.SGDSolver('../models/bvlc_reference_caffenet/solver_memory_train_val.prototxt')
solver.net.set_mode_gpu()
testnet = solver.test_nets[0]
# load caffe reference model
caffenet = caffe.Net('../models/bvlc_reference_caffenet/deploy.prototxt', '../models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel')
# generate dictionaries of the parameters
params = caffenet.params.keys()
source_params = {pr: (caffenet.params[pr][0].data, caffenet.params[pr][1].data) for pr in params}
target_params = {pr: (solver.net.params[pr][0].data, solver.net.params[pr][1].data) for pr in params}
# copy weights from caffenet to solver
for pr in params:
target_params[pr][1][...] = source_params [pr][1] #bias
target_params[pr][0][...] = source_params [pr][0] #weights
# load and preprocess input data
input_image = caffe.io.load_image('../examples/images/cat.jpg')
input_oversampled = caffe.io.oversample([caffe.io.resize_image(input_image, (256, 256))], (227, 227))
data = np.asarray([solver.net.preprocess('data', in_) for in_ in input_oversampled])
testnet.set_input_arrays(data, labels)
# run solver
solver.solve()
# top-3 outputs
data_prob = testnet.blobs['prob'].data
top_k = data_prob[0].flatten().argsort()[-1:-4:-1]
# class_id [794 599 728] and corresponding probs [ 0.00169671 0.00153411 0.00147332]
Solver nets should support read and write just like any other net, and #1228 is unrelated to that property.
I don't immediately see why your code above would not have the expected results. However, you are in danger of running into the unexpected behavior described around https://github.com/BVLC/caffe/pull/311#issuecomment-40047852 due to storing the data attribute. (For example, target_params and source_params will be invalid after calling solver.solve.) The way things are now (which should at least be more thoroughly documented), it's best to always write .data explicitly.
Note that you can always read the params back out to check that they are what you expect (or at least not obviously wrong).
The #311 comments should at least be hinted at in the tutorial documentation: https://github.com/BVLC/caffe/blob/master/docs/tutorial/interfaces.md.
What would help is auto-generated docs for pycaffe from our docstrings and such. We should be able to incorporate this into doxygen.
On Fri, Oct 10, 2014 at 12:38 PM, longjon [email protected] wrote:
Solver nets should support read and write just like any other net, and #1228 https://github.com/BVLC/caffe/pull/1228 is unrelated to that property.
I don't immediately see why your code above would not have the expected results. However, you are in danger of running into the unexpected behavior described around #311 (comment) https://github.com/BVLC/caffe/pull/311#issuecomment-40047852 due to storing the data attribute. (For example, target_params and source_params will be invalid after calling solver.solve.) The way things are now (which should at least be more thoroughly documented), it's best to always write .data explicitly.
Note that you can always read the params back out to check that they are what you expect (or at least not obviously wrong).
— Reply to this email directly or view it on GitHub https://github.com/BVLC/caffe/issues/1257#issuecomment-58705784.
@longjon Thanks for your explanation! I added the following lines before and after the solver.solve() command:
print 'caffenet: ', caffenet.params['fc7'][0].data
print 'trainnet: ', solver.net.params['fc7'][0].data
print 'testnet: ', solver.test_nets[0].params['fc7'][0].data
I could verify that caffenet and trainnet share the same params before solve() and trainnet and testnet share the same params after solve().
I figured out that the reason for the bad prediction results is the usage of solver.net.preprocess('data', in_) which uses the wrong preprocessing setup with regard to the reference caffenet. To fix this I first tried to use the following lines
solver.test_nets[0].set_mean('data', np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy')) # ImageNet mean
solver.test_nets[0].set_raw_scale('data', 255) # the reference model operates on images in [0,255] range instead of [0,1]
solver.test_nets[0].set_channel_swap('data', (2, 1, 0)) # the reference model has channels in BGR order instead of RGB
that give the following error:
File "../python/caffe/pycaffe.py", line 216, in _Net_set_mean
raise Exception('Input not in {}'.format(self.inputs))
Exception: Input not in []
My current workaround is to set the properties for the input of caffenet and then to use the caffenet.preprocess(). Is there a better option?
Right. Currently, if your net starts with any data layer (even a MemoryDataLayer), all preprocessing must happen inside the net; the Python-level preprocessing only works if your net has unattached bottoms ("input blobs"). This is true even though the preprocessing itself doesn't strictly depend on the net. The plan to clean this up is to unify all preprocessing as in-net only, so that the Python-level processing won't be necessary. For now your workaround suffices, or do preprocessing manually.
In fact (@shelhamer), we should probably check that input_ in self.inputs in Net.preprocess, because right now you can ask pycaffe to do preprocessing for blobs that aren't input blobs, but you can't set any preprocessing options. Or we could drop the checks when setting the options, and assume that users know what they are doing if they want to preprocess for mid-net blobs.
@longjon yet another reason for the migration in #1245. The effort is better directed there than further development of pycaffe.preprocess stop gap in my opinion.
Closing as the problem here seems to have been resolved, and the underlying issues have either been fixed or are documented in other issues.