Guest User

pycaffe.py

a guest
Nov 22nd, 2015
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.68 KB | None | 0 0
  1. """
  2. Wrap the internal caffe C++ module (_caffe.so) with a clean, Pythonic
  3. interface.
  4. """
  5.  
  6. from collections import OrderedDict
  7. try:
  8.     from itertools import izip_longest
  9. except:
  10.     from itertools import zip_longest as izip_longest
  11. import numpy as np
  12.  
  13. from ._caffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, \
  14.         RMSPropSolver, AdaDeltaSolver, AdamSolver
  15. import caffe.io
  16.  
  17. # We directly update methods from Net here (rather than using composition or
  18. # inheritance) so that nets created by caffe (e.g., by SGDSolver) will
  19. # automatically have the improved interface.
  20.  
  21.  
  22. @property
  23. def _Net_blobs(self):
  24.     """
  25.    An OrderedDict (bottom to top, i.e., input to output) of network
  26.    blobs indexed by name
  27.    """
  28.     return OrderedDict(zip(self._blob_names, self._blobs))
  29.  
  30.  
  31. @property
  32. def _Net_blob_loss_weights(self):
  33.     """
  34.    An OrderedDict (bottom to top, i.e., input to output) of network
  35.    blob loss weights indexed by name
  36.    """
  37.     return OrderedDict(zip(self._blob_names, self._blob_loss_weights))
  38.  
  39.  
  40. @property
  41. def _Net_params(self):
  42.     """
  43.    An OrderedDict (bottom to top, i.e., input to output) of network
  44.    parameters indexed by name; each is a list of multiple blobs (e.g.,
  45.    weights and biases)
  46.    """
  47.     return OrderedDict([(name, lr.blobs)
  48.                         for name, lr in zip(self._layer_names, self.layers)
  49.                         if len(lr.blobs) > 0])
  50.  
  51.  
  52. @property
  53. def _Net_inputs(self):
  54.     return [list(self.blobs.keys())[i] for i in self._inputs]
  55.  
  56.  
  57. @property
  58. def _Net_outputs(self):
  59.     return [list(self.blobs.keys())[i] for i in self._outputs]
  60.  
  61.  
  62. def _Net_forward(self, blobs=None, start=None, end=None, **kwargs):
  63.     """
  64.    Forward pass: prepare inputs and run the net forward.
  65.  
  66.    Parameters
  67.    ----------
  68.    blobs : list of blobs to return in addition to output blobs.
  69.    kwargs : Keys are input blob names and values are blob ndarrays.
  70.             For formatting inputs for Caffe, see Net.preprocess().
  71.             If None, input is taken from data layers.
  72.    start : optional name of layer at which to begin the forward pass
  73.    end : optional name of layer at which to finish the forward pass
  74.          (inclusive)
  75.  
  76.    Returns
  77.    -------
  78.    outs : {blob name: blob ndarray} dict.
  79.    """
  80.     if blobs is None:
  81.         blobs = []
  82.  
  83.     if start is not None:
  84.         start_ind = list(self._layer_names).index(start)
  85.     else:
  86.         start_ind = 0
  87.  
  88.     if end is not None:
  89.         end_ind = list(self._layer_names).index(end)
  90.         outputs = set([end] + blobs)
  91.     else:
  92.         end_ind = len(self.layers) - 1
  93.         outputs = set(self.outputs + blobs)
  94.  
  95.     if kwargs:
  96.         if set(kwargs.keys()) != set(self.inputs):
  97.             raise Exception('Input blob arguments do not match net inputs.')
  98.         # Set input according to defined shapes and make arrays single and
  99.         # C-contiguous as Caffe expects.
  100.         for in_, blob in kwargs.iteritems():
  101.             if blob.shape[0] != self.blobs[in_].num:
  102.                 raise Exception('Input is not batch sized')
  103.             self.blobs[in_].data[...] = blob
  104.  
  105.     self._forward(start_ind, end_ind)
  106.  
  107.     # Unpack blobs to extract
  108.     return {out: self.blobs[out].data for out in outputs}
  109.  
  110.  
  111. def _Net_backward(self, diffs=None, start=None, end=None, **kwargs):
  112.     """
  113.    Backward pass: prepare diffs and run the net backward.
  114.  
  115.    Parameters
  116.    ----------
  117.    diffs : list of diffs to return in addition to bottom diffs.
  118.    kwargs : Keys are output blob names and values are diff ndarrays.
  119.            If None, top diffs are taken from forward loss.
  120.    start : optional name of layer at which to begin the backward pass
  121.    end : optional name of layer at which to finish the backward pass
  122.        (inclusive)
  123.  
  124.    Returns
  125.    -------
  126.    outs: {blob name: diff ndarray} dict.
  127.    """
  128.     if diffs is None:
  129.         diffs = []
  130.  
  131.     if start is not None:
  132.         start_ind = list(self._layer_names).index(start)
  133.     else:
  134.         start_ind = len(self.layers) - 1
  135.  
  136.     if end is not None:
  137.         end_ind = list(self._layer_names).index(end)
  138.         outputs = set([end] + diffs)
  139.     else:
  140.         end_ind = 0
  141.         outputs = set(self.inputs + diffs)
  142.  
  143.     if kwargs:
  144.         if set(kwargs.keys()) != set(self.outputs):
  145.             raise Exception('Top diff arguments do not match net outputs.')
  146.         # Set top diffs according to defined shapes and make arrays single and
  147.         # C-contiguous as Caffe expects.
  148.         for top, diff in kwargs.iteritems():
  149.             if diff.shape[0] != self.blobs[top].num:
  150.                 raise Exception('Diff is not batch sized')
  151.             self.blobs[top].diff[...] = diff
  152.  
  153.     self._backward(start_ind, end_ind)
  154.  
  155.     # Unpack diffs to extract
  156.     return {out: self.blobs[out].diff for out in outputs}
  157.  
  158.  
  159. def _Net_forward_all(self, blobs=None, **kwargs):
  160.     """
  161.    Run net forward in batches.
  162.  
  163.    Parameters
  164.    ----------
  165.    blobs : list of blobs to extract as in forward()
  166.    kwargs : Keys are input blob names and values are blob ndarrays.
  167.             Refer to forward().
  168.  
  169.    Returns
  170.    -------
  171.    all_outs : {blob name: list of blobs} dict.
  172.    """
  173.     # Collect outputs from batches
  174.     all_outs = {out: [] for out in set(self.outputs + (blobs or []))}
  175.     for batch in self._batch(kwargs):
  176.         outs = self.forward(blobs=blobs, **batch)
  177.         for out, out_blob in outs.iteritems():
  178.             all_outs[out].extend(out_blob.copy())
  179.     # Package in ndarray.
  180.     for out in all_outs:
  181.         all_outs[out] = np.asarray(all_outs[out])
  182.     # Discard padding.
  183.     pad = len(all_outs.itervalues().next()) - len(kwargs.itervalues().next())
  184.     if pad:
  185.         for out in all_outs:
  186.             all_outs[out] = all_outs[out][:-pad]
  187.     return all_outs
  188.  
  189.  
  190. def _Net_forward_backward_all(self, blobs=None, diffs=None, **kwargs):
  191.     """
  192.    Run net forward + backward in batches.
  193.  
  194.    Parameters
  195.    ----------
  196.    blobs: list of blobs to extract as in forward()
  197.    diffs: list of diffs to extract as in backward()
  198.    kwargs: Keys are input (for forward) and output (for backward) blob names
  199.            and values are ndarrays. Refer to forward() and backward().
  200.            Prefilled variants are called for lack of input or output blobs.
  201.  
  202.    Returns
  203.    -------
  204.    all_blobs: {blob name: blob ndarray} dict.
  205.    all_diffs: {blob name: diff ndarray} dict.
  206.    """
  207.     # Batch blobs and diffs.
  208.     all_outs = {out: [] for out in set(self.outputs + (blobs or []))}
  209.     all_diffs = {diff: [] for diff in set(self.inputs + (diffs or []))}
  210.     forward_batches = self._batch({in_: kwargs[in_]
  211.                                    for in_ in self.inputs if in_ in kwargs})
  212.     backward_batches = self._batch({out: kwargs[out]
  213.                                     for out in self.outputs if out in kwargs})
  214.     # Collect outputs from batches (and heed lack of forward/backward batches).
  215.     for fb, bb in izip_longest(forward_batches, backward_batches, fillvalue={}):
  216.         batch_blobs = self.forward(blobs=blobs, **fb)
  217.         batch_diffs = self.backward(diffs=diffs, **bb)
  218.         for out, out_blobs in batch_blobs.iteritems():
  219.             all_outs[out].extend(out_blobs.copy())
  220.         for diff, out_diffs in batch_diffs.iteritems():
  221.             all_diffs[diff].extend(out_diffs.copy())
  222.     # Package in ndarray.
  223.     for out, diff in zip(all_outs, all_diffs):
  224.         all_outs[out] = np.asarray(all_outs[out])
  225.         all_diffs[diff] = np.asarray(all_diffs[diff])
  226.     # Discard padding at the end and package in ndarray.
  227.     pad = len(all_outs.itervalues().next()) - len(kwargs.itervalues().next())
  228.     if pad:
  229.         for out, diff in zip(all_outs, all_diffs):
  230.             all_outs[out] = all_outs[out][:-pad]
  231.             all_diffs[diff] = all_diffs[diff][:-pad]
  232.     return all_outs, all_diffs
  233.  
  234.  
  235. def _Net_set_input_arrays(self, data, labels):
  236.     """
  237.    Set input arrays of the in-memory MemoryDataLayer.
  238.    (Note: this is only for networks declared with the memory data layer.)
  239.    """
  240.     if labels.ndim == 1:
  241.         labels = np.ascontiguousarray(labels[:, np.newaxis, np.newaxis,
  242.                                              np.newaxis])
  243.     return self._set_input_arrays(data, labels)
  244.  
  245.  
  246. def _Net_batch(self, blobs):
  247.     """
  248.    Batch blob lists according to net's batch size.
  249.  
  250.    Parameters
  251.    ----------
  252.    blobs: Keys blob names and values are lists of blobs (of any length).
  253.           Naturally, all the lists should have the same length.
  254.  
  255.    Yields
  256.    ------
  257.    batch: {blob name: list of blobs} dict for a single batch.
  258.    """
  259.     num = len(blobs.itervalues().next())
  260.     batch_size = self.blobs.itervalues().next().num
  261.     remainder = num % batch_size
  262.     num_batches = num / batch_size
  263.  
  264.     # Yield full batches.
  265.     for b in range(num_batches):
  266.         i = b * batch_size
  267.         yield {name: blobs[name][i:i + batch_size] for name in blobs}
  268.  
  269.     # Yield last padded batch, if any.
  270.     if remainder > 0:
  271.         padded_batch = {}
  272.         for name in blobs:
  273.             padding = np.zeros((batch_size - remainder,)
  274.                                + blobs[name].shape[1:])
  275.             padded_batch[name] = np.concatenate([blobs[name][-remainder:],
  276.                                                  padding])
  277.         yield padded_batch
  278.  
  279. # Attach methods to Net.
  280. Net.blobs = _Net_blobs
  281. Net.blob_loss_weights = _Net_blob_loss_weights
  282. Net.params = _Net_params
  283. Net.forward = _Net_forward
  284. Net.backward = _Net_backward
  285. Net.forward_all = _Net_forward_all
  286. Net.forward_backward_all = _Net_forward_backward_all
  287. Net.set_input_arrays = _Net_set_input_arrays
  288. Net._batch = _Net_batch
  289. Net.inputs = _Net_inputs
  290. Net.outputs = _Net_outputs
Advertisement
Add Comment
Please, Sign In to add comment