text
stringlengths
81
112k
Draw top3 proposals for each gt. Args: proposals: NPx4 proposal_scores: NP gt_boxes: NG def draw_proposal_recall(img, proposals, proposal_scores, gt_boxes): """ Draw top3 proposals for each gt. Args: proposals: NPx4 proposal_scores: NP gt_boxes: NG """ box_ious = np_iou(gt_boxes, proposals) # ng x np box_ious_argsort = np.argsort(-box_ious, axis=1) good_proposals_ind = box_ious_argsort[:, :3] # for each gt, find 3 best proposals good_proposals_ind = np.unique(good_proposals_ind.ravel()) proposals = proposals[good_proposals_ind, :] tags = list(map(str, proposal_scores[good_proposals_ind])) img = viz.draw_boxes(img, proposals, tags) return img, good_proposals_ind
Args: boxes: kx4 scores: kxC def draw_predictions(img, boxes, scores): """ Args: boxes: kx4 scores: kxC """ if len(boxes) == 0: return img labels = scores.argmax(axis=1) scores = scores.max(axis=1) tags = ["{},{:.2f}".format(cfg.DATA.CLASS_NAMES[lb], score) for lb, score in zip(labels, scores)] return viz.draw_boxes(img, boxes, tags)
Args: results: [DetectionResult] def draw_final_outputs(img, results): """ Args: results: [DetectionResult] """ if len(results) == 0: return img # Display in largest to smallest order to reduce occlusion boxes = np.asarray([r.box for r in results]) areas = np_area(boxes) sorted_inds = np.argsort(-areas) ret = img tags = [] for result_id in sorted_inds: r = results[result_id] if r.mask is not None: ret = draw_mask(ret, r.mask) for r in results: tags.append( "{},{:.2f}".format(cfg.DATA.CLASS_NAMES[r.class_id], r.score)) ret = viz.draw_boxes(ret, boxes, tags) return ret
Overlay a mask on top of the image. Args: im: a 3-channel uint8 image in BGR mask: a binary 1-channel image of the same size color: if None, will choose automatically def draw_mask(im, mask, alpha=0.5, color=None): """ Overlay a mask on top of the image. Args: im: a 3-channel uint8 image in BGR mask: a binary 1-channel image of the same size color: if None, will choose automatically """ if color is None: color = PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1] im = np.where(np.repeat((mask > 0)[:, :, None], 3, axis=2), im * (1 - alpha) + color * alpha, im) im = im.astype('uint8') return im
Run DataFlow and send data to a ZMQ socket addr. It will serialize and send each datapoint to this address with a PUSH socket. This function never returns. Args: df (DataFlow): Will infinitely loop over the DataFlow. addr: a ZMQ socket endpoint. hwm (int): ZMQ high-water mark (buffer size) format (str): The serialization format. Default format uses :mod:`tensorpack.utils.serialize`. This format works with :class:`dataflow.RemoteDataZMQ`. An alternate format is 'zmq_ops', used by https://github.com/tensorpack/zmq_ops and :class:`input_source.ZMQInput`. bind (bool): whether to bind or connect to the endpoint address. def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False): """ Run DataFlow and send data to a ZMQ socket addr. It will serialize and send each datapoint to this address with a PUSH socket. This function never returns. Args: df (DataFlow): Will infinitely loop over the DataFlow. addr: a ZMQ socket endpoint. hwm (int): ZMQ high-water mark (buffer size) format (str): The serialization format. Default format uses :mod:`tensorpack.utils.serialize`. This format works with :class:`dataflow.RemoteDataZMQ`. An alternate format is 'zmq_ops', used by https://github.com/tensorpack/zmq_ops and :class:`input_source.ZMQInput`. bind (bool): whether to bind or connect to the endpoint address. """ assert format in [None, 'zmq_op', 'zmq_ops'] if format is None: dump_fn = dumps else: from zmq_ops import dump_arrays dump_fn = dump_arrays ctx = zmq.Context() socket = ctx.socket(zmq.PUSH) socket.set_hwm(hwm) if bind: socket.bind(addr) else: socket.connect(addr) try: df.reset_state() logger.info("Serving data to {} with {} format ...".format( addr, 'default' if format is None else 'zmq_ops')) INTERVAL = 200 q = deque(maxlen=INTERVAL) try: total = len(df) except NotImplementedError: total = 0 tqdm_args = get_tqdm_kwargs(leave=True, smoothing=0.8) tqdm_args['bar_format'] = tqdm_args['bar_format'] + "{postfix}" while True: with tqdm.trange(total, **tqdm_args) as pbar: for dp in df: start = time.time() socket.send(dump_fn(dp), copy=False) q.append(time.time() - start) pbar.update(1) if pbar.n % INTERVAL == 0: avg = "{:.3f}".format(sum(q) / len(q)) pbar.set_postfix({'AvgSendLat': avg}) finally: logger.info("Exiting send_dataflow_zmq ...") socket.setsockopt(zmq.LINGER, 0) socket.close() if not ctx.closed: ctx.destroy(0)
Convert a DataFlow to a :class:`multiprocessing.Queue`. The DataFlow will only be reset in the spawned process. Args: df (DataFlow): the DataFlow to dump. size (int): size of the queue nr_consumer (int): number of consumer of the queue. The producer will add this many of ``DIE`` sentinel to the end of the queue. Returns: tuple(queue, process): The process will take data from ``df`` and fill the queue, once you start it. Each element in the queue is (idx, dp). idx can be the ``DIE`` sentinel when ``df`` is exhausted. def dump_dataflow_to_process_queue(df, size, nr_consumer): """ Convert a DataFlow to a :class:`multiprocessing.Queue`. The DataFlow will only be reset in the spawned process. Args: df (DataFlow): the DataFlow to dump. size (int): size of the queue nr_consumer (int): number of consumer of the queue. The producer will add this many of ``DIE`` sentinel to the end of the queue. Returns: tuple(queue, process): The process will take data from ``df`` and fill the queue, once you start it. Each element in the queue is (idx, dp). idx can be the ``DIE`` sentinel when ``df`` is exhausted. """ q = mp.Queue(size) class EnqueProc(mp.Process): def __init__(self, df, q, nr_consumer): super(EnqueProc, self).__init__() self.df = df self.q = q def run(self): self.df.reset_state() try: for idx, dp in enumerate(self.df): self.q.put((idx, dp)) finally: for _ in range(nr_consumer): self.q.put((DIE, None)) proc = EnqueProc(df, q, nr_consumer) return q, proc
:returns: the current 3-channel image def _grab_raw_image(self): """ :returns: the current 3-channel image """ m = self.ale.getScreenRGB() return m.reshape((self.height, self.width, 3))
:returns: a gray-scale (h, w) uint8 image def _current_state(self): """ :returns: a gray-scale (h, w) uint8 image """ ret = self._grab_raw_image() # max-pooled over the last screen ret = np.maximum(ret, self.last_raw_screen) if self.viz: if isinstance(self.viz, float): cv2.imshow(self.windowname, ret) cv2.waitKey(int(self.viz * 1000)) ret = ret.astype('float32') # 0.299,0.587.0.114. same as rgb2y in torch/image ret = cv2.cvtColor(ret, cv2.COLOR_RGB2GRAY)[:, :] return ret.astype('uint8')
Args: boxes: nx4, xyxy window: [h, w] def clip_boxes(boxes, window, name=None): """ Args: boxes: nx4, xyxy window: [h, w] """ boxes = tf.maximum(boxes, 0.0) m = tf.tile(tf.reverse(window, [0]), [2]) # (4,) boxes = tf.minimum(boxes, tf.cast(m, tf.float32), name=name) return boxes
Args: box_predictions: (..., 4), logits anchors: (..., 4), floatbox. Must have the same shape Returns: box_decoded: (..., 4), float32. With the same shape. def decode_bbox_target(box_predictions, anchors): """ Args: box_predictions: (..., 4), logits anchors: (..., 4), floatbox. Must have the same shape Returns: box_decoded: (..., 4), float32. With the same shape. """ orig_shape = tf.shape(anchors) box_pred_txtytwth = tf.reshape(box_predictions, (-1, 2, 2)) box_pred_txty, box_pred_twth = tf.split(box_pred_txtytwth, 2, axis=1) # each is (...)x1x2 anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2)) anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y2, 2, axis=1) waha = anchors_x2y2 - anchors_x1y1 xaya = (anchors_x2y2 + anchors_x1y1) * 0.5 clip = np.log(config.PREPROC.MAX_SIZE / 16.) wbhb = tf.exp(tf.minimum(box_pred_twth, clip)) * waha xbyb = box_pred_txty * waha + xaya x1y1 = xbyb - wbhb * 0.5 x2y2 = xbyb + wbhb * 0.5 # (...)x1x2 out = tf.concat([x1y1, x2y2], axis=-2) return tf.reshape(out, orig_shape)
Args: boxes: (..., 4), float32 anchors: (..., 4), float32 Returns: box_encoded: (..., 4), float32 with the same shape. def encode_bbox_target(boxes, anchors): """ Args: boxes: (..., 4), float32 anchors: (..., 4), float32 Returns: box_encoded: (..., 4), float32 with the same shape. """ anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2)) anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y2, 2, axis=1) waha = anchors_x2y2 - anchors_x1y1 xaya = (anchors_x2y2 + anchors_x1y1) * 0.5 boxes_x1y1x2y2 = tf.reshape(boxes, (-1, 2, 2)) boxes_x1y1, boxes_x2y2 = tf.split(boxes_x1y1x2y2, 2, axis=1) wbhb = boxes_x2y2 - boxes_x1y1 xbyb = (boxes_x2y2 + boxes_x1y1) * 0.5 # Note that here not all boxes are valid. Some may be zero txty = (xbyb - xaya) / waha twth = tf.log(wbhb / waha) # may contain -inf for invalid boxes encoded = tf.concat([txty, twth], axis=1) # (-1x2x2) return tf.reshape(encoded, tf.shape(boxes))
Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes. Args: image: NCHW boxes: nx4, x1y1x2y2 box_ind: (n,) crop_size (int): Returns: n,C,size,size def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True): """ Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes. Args: image: NCHW boxes: nx4, x1y1x2y2 box_ind: (n,) crop_size (int): Returns: n,C,size,size """ assert isinstance(crop_size, int), crop_size boxes = tf.stop_gradient(boxes) # TF's crop_and_resize produces zeros on border if pad_border: # this can be quite slow image = tf.pad(image, [[0, 0], [0, 0], [1, 1], [1, 1]], mode='SYMMETRIC') boxes = boxes + 1 @under_name_scope() def transform_fpcoor_for_tf(boxes, image_shape, crop_shape): """ The way tf.image.crop_and_resize works (with normalized box): Initial point (the value of output[0]): x0_box * (W_img - 1) Spacing: w_box * (W_img - 1) / (W_crop - 1) Use the above grid to bilinear sample. However, what we want is (with fpcoor box): Spacing: w_box / W_crop Initial point: x0_box + spacing/2 - 0.5 (-0.5 because bilinear sample (in my definition) assumes floating point coordinate (0.0, 0.0) is the same as pixel value (0, 0)) This function transform fpcoor boxes to a format to be used by tf.image.crop_and_resize Returns: y1x1y2x2 """ x0, y0, x1, y1 = tf.split(boxes, 4, axis=1) spacing_w = (x1 - x0) / tf.cast(crop_shape[1], tf.float32) spacing_h = (y1 - y0) / tf.cast(crop_shape[0], tf.float32) imshape = [tf.cast(image_shape[0] - 1, tf.float32), tf.cast(image_shape[1] - 1, tf.float32)] nx0 = (x0 + spacing_w / 2 - 0.5) / imshape[1] ny0 = (y0 + spacing_h / 2 - 0.5) / imshape[0] nw = spacing_w * tf.cast(crop_shape[1] - 1, tf.float32) / imshape[1] nh = spacing_h * tf.cast(crop_shape[0] - 1, tf.float32) / imshape[0] return tf.concat([ny0, nx0, ny0 + nh, nx0 + nw], axis=1) # Expand bbox to a minium size of 1 # boxes_x1y1, boxes_x2y2 = tf.split(boxes, 2, axis=1) # boxes_wh = boxes_x2y2 - boxes_x1y1 # boxes_center = tf.reshape((boxes_x2y2 + boxes_x1y1) * 0.5, [-1, 2]) # boxes_newwh = tf.maximum(boxes_wh, 1.) # boxes_x1y1new = boxes_center - boxes_newwh * 0.5 # boxes_x2y2new = boxes_center + boxes_newwh * 0.5 # boxes = tf.concat([boxes_x1y1new, boxes_x2y2new], axis=1) image_shape = tf.shape(image)[2:] boxes = transform_fpcoor_for_tf(boxes, image_shape, [crop_size, crop_size]) image = tf.transpose(image, [0, 2, 3, 1]) # nhwc ret = tf.image.crop_and_resize( image, boxes, tf.cast(box_ind, tf.int32), crop_size=[crop_size, crop_size]) ret = tf.transpose(ret, [0, 3, 1, 2]) # ncss return ret
Args: featuremap: 1xCxHxW boxes: Nx4 floatbox resolution: output spatial resolution Returns: NxCx res x res def roi_align(featuremap, boxes, resolution): """ Args: featuremap: 1xCxHxW boxes: Nx4 floatbox resolution: output spatial resolution Returns: NxCx res x res """ # sample 4 locations per roi bin ret = crop_and_resize( featuremap, boxes, tf.zeros([tf.shape(boxes)[0]], dtype=tf.int32), resolution * 2) ret = tf.nn.avg_pool(ret, [1, 1, 2, 2], [1, 1, 2, 2], padding='SAME', data_format='NCHW') return ret
Slice anchors to the spatial size of this featuremap. def narrow_to(self, featuremap): """ Slice anchors to the spatial size of this featuremap. """ shape2d = tf.shape(featuremap)[2:] # h,w slice3d = tf.concat([shape2d, [-1]], axis=0) slice4d = tf.concat([shape2d, [-1, -1]], axis=0) boxes = tf.slice(self.boxes, [0, 0, 0, 0], slice4d) gt_labels = tf.slice(self.gt_labels, [0, 0, 0], slice3d) gt_boxes = tf.slice(self.gt_boxes, [0, 0, 0, 0], slice4d) return RPNAnchors(boxes, gt_labels, gt_boxes)
img: bgr, [0,255] heatmap: [0,1] def colorize(img, heatmap): """ img: bgr, [0,255] heatmap: [0,1] """ heatmap = viz.intensity_to_rgb(heatmap, cmap='jet')[:, :, ::-1] return img * 0.5 + heatmap * 0.5
The correct center is shape*0.5-0.5. This can be verified by: SHAPE = 7 arr = np.random.rand(SHAPE, SHAPE) orig = arr c = SHAPE * 0.5 - 0.5 c = (c, c) for k in range(4): mat = cv2.getRotationMatrix2D(c, 90, 1) arr = cv2.warpAffine(arr, mat, arr.shape) assert np.all(arr == orig) def _get_augment_params(self, img): center = img.shape[1::-1] * self._rand_range( self.center_range[0], self.center_range[1], (2,)) deg = self._rand_range(-self.max_deg, self.max_deg) if self.step_deg: deg = deg // self.step_deg * self.step_deg """ The correct center is shape*0.5-0.5. This can be verified by: SHAPE = 7 arr = np.random.rand(SHAPE, SHAPE) orig = arr c = SHAPE * 0.5 - 0.5 c = (c, c) for k in range(4): mat = cv2.getRotationMatrix2D(c, 90, 1) arr = cv2.warpAffine(arr, mat, arr.shape) assert np.all(arr == orig) """ mat = cv2.getRotationMatrix2D(tuple(center - 0.5), deg, 1) return WarpAffineTransform( mat, img.shape[1::-1], interp=self.interp, borderMode=self.border, borderValue=self.border_value)
Get largest rectangle after rotation. http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders def largest_rotated_rect(w, h, angle): """ Get largest rectangle after rotation. http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders """ angle = angle / 180.0 * math.pi if w <= 0 or h <= 0: return 0, 0 width_is_longer = w >= h side_long, side_short = (w, h) if width_is_longer else (h, w) # since the solutions for angle, -angle and 180-angle are all the same, # if suffices to look at the first quadrant and the absolute values of sin,cos: sin_a, cos_a = abs(math.sin(angle)), abs(math.cos(angle)) if side_short <= 2. * sin_a * cos_a * side_long: # half constrained case: two crop corners touch the longer side, # the other two corners are on the mid-line parallel to the longer line x = 0.5 * side_short wr, hr = (x / sin_a, x / cos_a) if width_is_longer else (x / cos_a, x / sin_a) else: # fully constrained case: crop touches all 4 sides cos_2a = cos_a * cos_a - sin_a * sin_a wr, hr = (w * cos_a - h * sin_a) / cos_2a, (h * cos_a - w * sin_a) / cos_2a return int(np.round(wr)), int(np.round(hr))
Apply a mapping on certain argument before calling the original function. Args: maps (dict): {argument_name: map_func} def map_arg(**maps): """ Apply a mapping on certain argument before calling the original function. Args: maps (dict): {argument_name: map_func} """ def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): if six.PY2: argmap = inspect.getcallargs(func, *args, **kwargs) else: # getcallargs was deprecated since 3.5 sig = inspect.signature(func) argmap = sig.bind_partial(*args, **kwargs).arguments for k, map_func in six.iteritems(maps): if k in argmap: argmap[k] = map_func(argmap[k]) return func(**argmap) return wrapper return deco
Like memoized, but keep one cache per default graph. def graph_memoized(func): """ Like memoized, but keep one cache per default graph. """ # TODO it keeps the graph alive from ..compat import tfv1 GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__' @memoized def func_with_graph_arg(*args, **kwargs): kwargs.pop(GRAPH_ARG_NAME) return func(*args, **kwargs) @functools.wraps(func) def wrapper(*args, **kwargs): assert GRAPH_ARG_NAME not in kwargs, "No Way!!" graph = tfv1.get_default_graph() kwargs[GRAPH_ARG_NAME] = graph return func_with_graph_arg(*args, **kwargs) return wrapper
A decorator. It performs memoization ignoring the arguments used to call the function. def memoized_ignoreargs(func): """ A decorator. It performs memoization ignoring the arguments used to call the function. """ def wrapper(*args, **kwargs): if func not in _MEMOIZED_NOARGS: res = func(*args, **kwargs) _MEMOIZED_NOARGS[func] = res return res return _MEMOIZED_NOARGS[func] return wrapper
Ensure a 2D shape. Args: a: a int or tuple/list of length 2 Returns: list: of length 2. if ``a`` is a int, return ``[a, a]``. def shape2d(a): """ Ensure a 2D shape. Args: a: a int or tuple/list of length 2 Returns: list: of length 2. if ``a`` is a int, return ``[a, a]``. """ if type(a) == int: return [a, a] if isinstance(a, (list, tuple)): assert len(a) == 2 return list(a) raise RuntimeError("Illegal shape: {}".format(a))
Ensuer a 4D shape, to use with 4D symbolic functions. Args: a: a int or tuple/list of length 2 Returns: list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]`` or ``[1, 1, a, a]`` depending on data_format. def shape4d(a, data_format='NHWC'): """ Ensuer a 4D shape, to use with 4D symbolic functions. Args: a: a int or tuple/list of length 2 Returns: list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]`` or ``[1, 1, a, a]`` depending on data_format. """ s2d = shape2d(a) if get_data_format(data_format, False) == 'NHWC': return [1] + s2d + [1] else: return [1, 1] + s2d
Decorate a method or property of a class, so that this method can only be called once for every instance. Calling it more than once will result in exception. def call_only_once(func): """ Decorate a method or property of a class, so that this method can only be called once for every instance. Calling it more than once will result in exception. """ @functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] # cannot use hasattr here, because hasattr tries to getattr, which # fails if func is a property assert func.__name__ in dir(self), "call_only_once can only be used on method or property!" if not hasattr(self, '_CALL_ONLY_ONCE_CACHE'): cache = self._CALL_ONLY_ONCE_CACHE = set() else: cache = self._CALL_ONLY_ONCE_CACHE cls = type(self) # cannot use ismethod(), because decorated method becomes a function is_method = inspect.isfunction(getattr(cls, func.__name__)) assert func not in cache, \ "{} {}.{} can only be called once per object!".format( 'Method' if is_method else 'Property', cls.__name__, func.__name__) cache.add(func) return func(*args, **kwargs) return wrapper
A decorator that performs memoization on methods. It stores the cache on the object instance itself. def memoized_method(func): """ A decorator that performs memoization on methods. It stores the cache on the object instance itself. """ @functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] assert func.__name__ in dir(self), "memoized_method can only be used on method!" if not hasattr(self, '_MEMOIZED_CACHE'): cache = self._MEMOIZED_CACHE = {} else: cache = self._MEMOIZED_CACHE key = (func, ) + args[1:] + tuple(kwargs) ret = cache.get(key, None) if ret is not None: return ret value = func(*args, **kwargs) cache[key] = value return value return wrapper
A decorator which automatically reuses the current variable scope if the function has been called with the same variable scope before. Example: .. code-block:: python @auto_reuse_variable_scope def myfunc(x): return tf.layers.conv2d(x, 128, 3) myfunc(x1) # will inherit parent scope reuse myfunc(x2) # will reuse with tf.variable_scope('newscope'): myfunc(x3) # will inherit parent scope reuse myfunc(x4) # will reuse def auto_reuse_variable_scope(func): """ A decorator which automatically reuses the current variable scope if the function has been called with the same variable scope before. Example: .. code-block:: python @auto_reuse_variable_scope def myfunc(x): return tf.layers.conv2d(x, 128, 3) myfunc(x1) # will inherit parent scope reuse myfunc(x2) # will reuse with tf.variable_scope('newscope'): myfunc(x3) # will inherit parent scope reuse myfunc(x4) # will reuse """ used_scope = set() @functools.wraps(func) def wrapper(*args, **kwargs): scope = tf.get_variable_scope() h = hash((tf.get_default_graph(), scope.name)) # print("Entering " + scope.name + " reuse: " + str(h in used_scope)) if h in used_scope: if get_tf_version_tuple() >= (1, 5): with tf.variable_scope(scope, reuse=True, auxiliary_name_scope=False): return func(*args, **kwargs) else: ns = tf.get_default_graph().get_name_scope() with tf.variable_scope(scope, reuse=True), \ tf.name_scope(ns + '/' if ns else ''): return func(*args, **kwargs) else: used_scope.add(h) return func(*args, **kwargs) return wrapper
Args: name_scope(str): the default scope to use. If None, will use the name of the function. Returns: A decorator which makes the function run under a name scope. The name scope is obtained by the following: 1. The 'name_scope' keyword argument when the decorated function is called. 2. The 'name_scope' argument of the decorator. 3. (default) The name of the decorated function itself. Example: .. code-block:: python @under_name_scope() def rms(x): return tf.sqrt( tf.reduce_mean(tf.square(x))) rms(tensor) # will be called under name scope 'rms' rms(tensor, name_scope='scope') # will be called under name scope 'scope' Todo: Add a reuse option. def under_name_scope(name_scope=None): """ Args: name_scope(str): the default scope to use. If None, will use the name of the function. Returns: A decorator which makes the function run under a name scope. The name scope is obtained by the following: 1. The 'name_scope' keyword argument when the decorated function is called. 2. The 'name_scope' argument of the decorator. 3. (default) The name of the decorated function itself. Example: .. code-block:: python @under_name_scope() def rms(x): return tf.sqrt( tf.reduce_mean(tf.square(x))) rms(tensor) # will be called under name scope 'rms' rms(tensor, name_scope='scope') # will be called under name scope 'scope' Todo: Add a reuse option. """ def _impl(func): @functools.wraps(func) def wrapper(*args, **kwargs): scopename = kwargs.pop('name_scope', name_scope) if scopename is None: scopename = func.__name__ with tf.name_scope(scopename): return func(*args, **kwargs) return wrapper return _impl
Returns: A decorator which makes the function happen under a variable scope, which is named by the function itself. Example: .. code-block:: python @under_variable_scope() def mid_level(x): with argscope(Conv2D, kernel_shape=3, nl=BNReLU): x = Conv2D('conv1', x, 512, stride=1) x = Conv2D('conv2', x, 256, stride=1) return x def under_variable_scope(): """ Returns: A decorator which makes the function happen under a variable scope, which is named by the function itself. Example: .. code-block:: python @under_variable_scope() def mid_level(x): with argscope(Conv2D, kernel_shape=3, nl=BNReLU): x = Conv2D('conv1', x, 512, stride=1) x = Conv2D('conv2', x, 256, stride=1) return x """ def _impl(func): @functools.wraps(func) def wrapper(*args, **kwargs): name = func.__name__ with tf.variable_scope(name): return func(*args, **kwargs) return wrapper return _impl
Return a context which either opens and caches a new name scope, or reenter an existing one. Args: top_level(bool): if True, the name scope will always be top-level. It will not be nested under any existing name scope of the caller. def cached_name_scope(name, top_level=True): """ Return a context which either opens and caches a new name scope, or reenter an existing one. Args: top_level(bool): if True, the name scope will always be top-level. It will not be nested under any existing name scope of the caller. """ if not top_level: current_ns = tf.get_default_graph().get_name_scope() if current_ns: name = current_ns + '/' + name ns = _get_cached_ns(name) with tf.name_scope(ns): yield ns
Args: grad_list: list of list of tuples, shape is Ngpu x Nvar x 2 def _check_grad_list(grad_list): """ Args: grad_list: list of list of tuples, shape is Ngpu x Nvar x 2 """ nvars = [len(k) for k in grad_list] def basename(x): return re.sub('tower[0-9]+/', '', x.op.name) if len(set(nvars)) != 1: names_per_gpu = [set([basename(k[1]) for k in grad_and_vars]) for grad_and_vars in grad_list] inters = copy.copy(names_per_gpu[0]) for s in names_per_gpu: inters &= s for s in names_per_gpu: s -= inters logger.error("Unique trainable variables on towers: " + pprint.pformat(names_per_gpu)) raise ValueError("Number of gradients from each tower is different! " + str(nvars))
Run `func` on all GPUs (towers) and return the results. Args: towers (list[int]): a list of GPU id. func: a lambda to be called inside each tower devices: a list of devices to be used. By default will use '/gpu:{tower}' use_vs (list[bool]): list of use_vs to passed to TowerContext Returns: List of outputs of ``func``, evaluated on each tower. def call_for_each_tower( towers, func, devices=None, use_vs=None): """ Run `func` on all GPUs (towers) and return the results. Args: towers (list[int]): a list of GPU id. func: a lambda to be called inside each tower devices: a list of devices to be used. By default will use '/gpu:{tower}' use_vs (list[bool]): list of use_vs to passed to TowerContext Returns: List of outputs of ``func``, evaluated on each tower. """ ret = [] if devices is not None: assert len(devices) == len(towers) if use_vs is not None: assert len(use_vs) == len(towers) tower_names = ['tower{}'.format(idx) for idx in range(len(towers))] for idx, t in enumerate(towers): device = devices[idx] if devices is not None else '/gpu:{}'.format(t) usevs = use_vs[idx] if use_vs is not None else False reuse = not usevs and idx > 0 with tfv1.device(device), _maybe_reuse_vs(reuse), TrainTowerContext( tower_names[idx], vs_name=tower_names[idx] if usevs else '', index=idx, total=len(towers)): if len(str(device)) < 10: # a device function doesn't have good string description logger.info("Building graph for training tower {} on device {} ...".format(idx, device)) else: logger.info("Building graph for training tower {} ...".format(idx)) # When use_vs is True, use LOCAL_VARIABLES, # so these duplicated variables won't be saved by default. with override_to_local_variable(enable=usevs): ret.append(func()) return ret
Reduce the gradients, apply them with the optimizer, and set self.grads to a list of (g, v), containing the averaged gradients. Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: tf.Operation: the training op def build(self, grad_list, get_opt_fn): """ Reduce the gradients, apply them with the optimizer, and set self.grads to a list of (g, v), containing the averaged gradients. Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: tf.Operation: the training op """ assert len(grad_list) == len(self.towers) DataParallelBuilder._check_grad_list(grad_list) # debug tower performance (without update): # ops = [k[0] for k in grad_list[1]] + [k[0] for k in grad_list[0]] # self.train_op = tf.group(*ops) # return self.grads = aggregate_grads(grad_list, colocation=True) # grads = grad_list[0] opt = get_opt_fn() if self.ps_device == 'cpu': with tf.device('/cpu:0'): train_op = opt.apply_gradients(self.grads, name='train_op') else: train_op = opt.apply_gradients(self.grads, name='train_op') return train_op
Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower. def call_for_each_tower(self, tower_fn): """ Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower. """ # if tower_fn returns [(grad, var), ...], this returns #GPU x #VAR x 2 return DataParallelBuilder.build_on_towers( self.towers, tower_fn, # use no variable scope for the first tower use_vs=[False] + [True] * (len(self.towers) - 1))
Reduce the gradients, apply them with the optimizer, and set self.grads to #GPU number of lists of (g, v), containing the all-reduced gradients on each device. Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: (tf.Operation, tf.Operation) 1. the training op. 2. the op which sync variables from GPU 0 to other GPUs. It has to be run before the training has started. And you can optionally run it later to sync non-trainable variables. def build(self, grad_list, get_opt_fn): """ Reduce the gradients, apply them with the optimizer, and set self.grads to #GPU number of lists of (g, v), containing the all-reduced gradients on each device. Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: (tf.Operation, tf.Operation) 1. the training op. 2. the op which sync variables from GPU 0 to other GPUs. It has to be run before the training has started. And you can optionally run it later to sync non-trainable variables. """ assert len(grad_list) == len(self.towers) raw_devices = ['/gpu:{}'.format(k) for k in self.towers] DataParallelBuilder._check_grad_list(grad_list) dtypes = set([x[0].dtype.base_dtype for x in grad_list[0]]) dtypes_nccl_supported = [tf.float32, tf.float64] if get_tf_version_tuple() >= (1, 8): dtypes_nccl_supported.append(tf.float16) valid_for_nccl = all([k in dtypes_nccl_supported for k in dtypes]) if self._mode == 'nccl' and not valid_for_nccl: logger.warn("Cannot use mode='nccl' because some gradients have unsupported types. Fallback to mode='cpu'") self._mode = 'cpu' if self._mode in ['nccl', 'hierarchical']: all_grads, all_vars = split_grad_list(grad_list) # use allreduce from tf-benchmarks # from .batch_allreduce import AllReduceSpecAlgorithm # algo = AllReduceSpecAlgorithm('nccl', list(range(8)), 0, 10) # all_grads, warmup_ops = algo.batch_all_reduce(all_grads, 1, True, False) # print("WARMUP OPS", warmup_ops) if self._mode == 'nccl': all_grads = allreduce_grads(all_grads, average=self._average) # #gpu x #param else: packer = GradientPacker(len(raw_devices)) succ = packer.compute_strategy(all_grads[0]) if succ: packed_grads = packer.pack_all(all_grads, raw_devices) packed_grads_aggr = allreduce_grads_hierarchical( packed_grads, raw_devices, average=self._average) all_grads = packer.unpack_all(packed_grads_aggr, raw_devices) else: all_grads = allreduce_grads_hierarchical(all_grads, raw_devices, average=self._average) self.grads = merge_grad_list(all_grads, all_vars) elif self._mode == 'cpu': agg_grad_and_vars = aggregate_grads( grad_list, colocation=False, devices=['/cpu:0'], average=self._average) # #param x 2 self.grads = [] # #gpu x #param x 2 for grad_and_vars in grad_list: # grad_and_vars: #paramx2 # take v from each tower, and g from average. self.grads.append( [(g, v) for (_, v), (g, _) in zip(grad_and_vars, agg_grad_and_vars)]) train_ops = [] opt = get_opt_fn() with tf.name_scope('apply_gradients'): for idx, grad_and_vars in enumerate(self.grads): with tf.device(raw_devices[idx]): # apply_gradients may create variables. Make them LOCAL_VARIABLES with override_to_local_variable(enable=idx > 0): train_ops.append(opt.apply_gradients( grad_and_vars, name='apply_grad_{}'.format(idx))) train_op = tf.group(*train_ops, name='train_op') with tf.name_scope('sync_variables'): post_init_op = SyncMultiGPUReplicatedBuilder.get_post_init_ops() return train_op, post_init_op
Copy values of variables on GPU 0 to other GPUs. def get_post_init_ops(): """ Copy values of variables on GPU 0 to other GPUs. """ # literally all variables, because it's better to sync optimizer-internal variables as well all_vars = tf.global_variables() + tf.local_variables() var_by_name = dict([(v.name, v) for v in all_vars]) trainable_names = set([x.name for x in tf.trainable_variables()]) post_init_ops = [] def log_failure(name, reason): logger.warn("[ReplicatedTrainer] Do not know how to sync variable '{}' across GPUs. " "Reason: {} ".format(name, reason)) assert name not in trainable_names, \ "The aforementioned variable is trainable, so this is probably a fatal error." logger.warn( "[ReplicatedTrainer] This variable is non-trainable. " "Ignore this warning if you know it's OK to leave it out-of-sync.") for v in all_vars: if not v.name.startswith('tower'): continue if v.name.startswith('tower0'): # in this trainer, the master name doesn't have the towerx/ prefix log_failure(v.name, "Name should not have prefix 'tower0' in this trainer!") continue # TODO some vars (EMA) may still startswith tower0 split_name = v.name.split('/') prefix = split_name[0] realname = '/'.join(split_name[1:]) if prefix in realname: log_failure(v.name, "Prefix {} appears multiple times in its name!".format(prefix)) continue copy_from = var_by_name.get(realname) if copy_from is not None: post_init_ops.append(v.assign(copy_from.read_value())) else: log_failure(v.name, "Cannot find {} in the graph!".format(realname)) logger.info( "'sync_variables_from_main_tower' includes {} operations.".format(len(post_init_ops))) return tf.group(*post_init_ops, name='sync_variables_from_main_tower')
Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower. def call_for_each_tower(self, tower_fn): """ Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower. """ ps_device = 'cpu' if len(self.towers) >= 4 else 'gpu' raw_devices = ['/gpu:{}'.format(k) for k in self.towers] if ps_device == 'gpu': devices = [LeastLoadedDeviceSetter(d, raw_devices) for d in raw_devices] else: devices = [tf.train.replica_device_setter( worker_device=d, ps_device='/cpu:0', ps_tasks=1) for d in raw_devices] return DataParallelBuilder.build_on_towers(self.towers, tower_fn, devices)
Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: tf.Operation: the training op def build(self, grad_list, get_opt_fn): """ Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: tf.Operation: the training op """ assert len(grad_list) == len(self.towers) DataParallelBuilder._check_grad_list(grad_list) if self._scale_gradient and len(self.towers) > 1: # pretend to average the grads, in order to make async and # sync have consistent effective learning rate gradproc = ScaleGradient(('.*', 1.0 / len(self.towers)), verbose=False) grad_list = [gradproc.process(gv) for gv in grad_list] # Ngpu x Nvar x 2 train_ops = [] opt = get_opt_fn() with tf.name_scope('async_apply_gradients'): for i, grad_and_vars in enumerate(zip(*grad_list)): # Ngpu x 2 v = grad_and_vars[0][1] with tf.device(v.device): # will call apply_gradients (therefore gradproc) multiple times train_ops.append(opt.apply_gradients( grad_and_vars, name='apply_grad_{}'.format(i))) return tf.group(*train_ops, name='train_op')
Humanize timedelta given in seconds Args: sec (float): time difference in seconds. Must be positive. Returns: str - time difference as a readable string Example: .. code-block:: python print(humanize_time_delta(1)) # 1 second print(humanize_time_delta(60 + 1)) # 1 minute 1 second print(humanize_time_delta(87.6)) # 1 minute 27 seconds print(humanize_time_delta(0.01)) # 0.01 seconds print(humanize_time_delta(60 * 60 + 1)) # 1 hour 1 second print(humanize_time_delta(60 * 60 * 24 + 1)) # 1 day 1 second print(humanize_time_delta(60 * 60 * 24 + 60 * 2 + 60*60*9 + 3)) # 1 day 9 hours 2 minutes 3 seconds def humanize_time_delta(sec): """Humanize timedelta given in seconds Args: sec (float): time difference in seconds. Must be positive. Returns: str - time difference as a readable string Example: .. code-block:: python print(humanize_time_delta(1)) # 1 second print(humanize_time_delta(60 + 1)) # 1 minute 1 second print(humanize_time_delta(87.6)) # 1 minute 27 seconds print(humanize_time_delta(0.01)) # 0.01 seconds print(humanize_time_delta(60 * 60 + 1)) # 1 hour 1 second print(humanize_time_delta(60 * 60 * 24 + 1)) # 1 day 1 second print(humanize_time_delta(60 * 60 * 24 + 60 * 2 + 60*60*9 + 3)) # 1 day 9 hours 2 minutes 3 seconds """ if sec < 0: logger.warn("humanize_time_delta() obtains negative seconds!") return "{:.3g} seconds".format(sec) if sec == 0: return "0 second" time = datetime(2000, 1, 1) + timedelta(seconds=int(sec)) units = ['day', 'hour', 'minute', 'second'] vals = [int(sec // 86400), time.hour, time.minute, time.second] if sec < 60: vals[-1] = sec def _format(v, u): return "{:.3g} {}{}".format(v, u, "s" if v > 1 else "") ans = [] for v, u in zip(vals, units): if v > 0: ans.append(_format(v, u)) return " ".join(ans)
Args: name(str), val(str): Returns: a context where the environment variable ``name`` being set to ``val``. It will be set back after the context exits. def change_env(name, val): """ Args: name(str), val(str): Returns: a context where the environment variable ``name`` being set to ``val``. It will be set back after the context exits. """ oldval = os.environ.get(name, None) os.environ[name] = val yield if oldval is None: del os.environ[name] else: os.environ[name] = oldval
Get a good RNG seeded with time, pid and the object. Args: obj: some object to use to generate random seed. Returns: np.random.RandomState: the RNG. def get_rng(obj=None): """ Get a good RNG seeded with time, pid and the object. Args: obj: some object to use to generate random seed. Returns: np.random.RandomState: the RNG. """ seed = (id(obj) + os.getpid() + int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 4294967295 if _RNG_SEED is not None: seed = _RNG_SEED return np.random.RandomState(seed)
Each called in the code to this function is guaranteed to return True the first time and False afterwards. Returns: bool: whether this is the first time this function gets called from this line of code. Example: .. code-block:: python if execute_only_once(): # do something only once def execute_only_once(): """ Each called in the code to this function is guaranteed to return True the first time and False afterwards. Returns: bool: whether this is the first time this function gets called from this line of code. Example: .. code-block:: python if execute_only_once(): # do something only once """ f = inspect.currentframe().f_back ident = (f.f_code.co_filename, f.f_lineno) if ident in _EXECUTE_HISTORY: return False _EXECUTE_HISTORY.add(ident) return True
Return default arguments to be used with tqdm. Args: kwargs: extra arguments to be used. Returns: dict: def get_tqdm_kwargs(**kwargs): """ Return default arguments to be used with tqdm. Args: kwargs: extra arguments to be used. Returns: dict: """ default = dict( smoothing=0.5, dynamic_ncols=True, ascii=True, bar_format='{l_bar}{bar}|{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_noinv_fmt}]' ) try: # Use this env var to override the refresh interval setting interval = float(os.environ['TENSORPACK_PROGRESS_REFRESH']) except KeyError: interval = _pick_tqdm_interval(kwargs.get('file', sys.stderr)) default['mininterval'] = interval default.update(kwargs) return default
Similar to `from ctypes.util import find_library`, but try to return full path if possible. def find_library_full_path(name): """ Similar to `from ctypes.util import find_library`, but try to return full path if possible. """ from ctypes.util import find_library if os.name == "posix" and sys.platform == "darwin": # on Mac, ctypes already returns full path return find_library(name) def _use_proc_maps(name): """ Find so from /proc/pid/maps Only works with libraries that has already been loaded. But this is the most accurate method -- it finds the exact library that's being used. """ procmap = os.path.join('/proc', str(os.getpid()), 'maps') if not os.path.isfile(procmap): return None with open(procmap, 'r') as f: for line in f: line = line.strip().split(' ') sofile = line[-1] basename = os.path.basename(sofile) if 'lib' + name + '.so' in basename: if os.path.isfile(sofile): return os.path.realpath(sofile) # The following two methods come from https://github.com/python/cpython/blob/master/Lib/ctypes/util.py def _use_ld(name): """ Find so with `ld -lname -Lpath`. It will search for files in LD_LIBRARY_PATH, but not in ldconfig. """ cmd = "ld -t -l{} -o {}".format(name, os.devnull) ld_lib_path = os.environ.get('LD_LIBRARY_PATH', '') for d in ld_lib_path.split(':'): cmd = cmd + " -L " + d result, ret = subproc_call(cmd + '|| true') expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name) res = re.search(expr, result.decode('utf-8')) if res: res = res.group(0) if not os.path.isfile(res): return None return os.path.realpath(res) def _use_ldconfig(name): """ Find so in `ldconfig -p`. It does not handle LD_LIBRARY_PATH. """ with change_env('LC_ALL', 'C'), change_env('LANG', 'C'): ldconfig, ret = subproc_call("ldconfig -p") ldconfig = ldconfig.decode('utf-8') if ret != 0: return None expr = r'\s+(lib%s\.[^\s]+)\s+\(.*=>\s+(.*)' % (re.escape(name)) res = re.search(expr, ldconfig) if not res: return None else: ret = res.group(2) return os.path.realpath(ret) if sys.platform.startswith('linux'): return _use_proc_maps(name) or _use_ld(name) or _use_ldconfig(name) or find_library(name) return find_library(name)
Args: df (DataFlow): the DataFlow to serialize. path (str): output path. Either a directory or an lmdb file. write_frequency (int): the frequency to write back data to disk. def save(df, path, write_frequency=5000): """ Args: df (DataFlow): the DataFlow to serialize. path (str): output path. Either a directory or an lmdb file. write_frequency (int): the frequency to write back data to disk. """ assert isinstance(df, DataFlow), type(df) isdir = os.path.isdir(path) if isdir: assert not os.path.isfile(os.path.join(path, 'data.mdb')), "LMDB file exists!" else: assert not os.path.isfile(path), "LMDB file {} exists!".format(path) db = lmdb.open(path, subdir=isdir, map_size=1099511627776 * 2, readonly=False, meminit=False, map_async=True) # need sync() at the end size = _reset_df_and_get_size(df) with get_tqdm(total=size) as pbar: idx = -1 # LMDB transaction is not exception-safe! # although it has a context manager interface txn = db.begin(write=True) for idx, dp in enumerate(df): txn.put(u'{:08}'.format(idx).encode('ascii'), dumps(dp)) pbar.update() if (idx + 1) % write_frequency == 0: txn.commit() txn = db.begin(write=True) txn.commit() keys = [u'{:08}'.format(k).encode('ascii') for k in range(idx + 1)] with db.begin(write=True) as txn: txn.put(b'__keys__', dumps(keys)) logger.info("Flushing database ...") db.sync() db.close()
Note: If you found deserialization being the bottleneck, you can use :class:`LMDBData` as the reader and run deserialization as a mapper in parallel. def load(path, shuffle=True): """ Note: If you found deserialization being the bottleneck, you can use :class:`LMDBData` as the reader and run deserialization as a mapper in parallel. """ df = LMDBData(path, shuffle=shuffle) return MapData(df, lambda dp: loads(dp[1]))
Args: df (DataFlow): the DataFlow to serialize. path (str): output npz file. def save(df, path): """ Args: df (DataFlow): the DataFlow to serialize. path (str): output npz file. """ buffer = [] size = _reset_df_and_get_size(df) with get_tqdm(total=size) as pbar: for dp in df: buffer.append(dp) pbar.update() np.savez_compressed(path, buffer=np.asarray(buffer, dtype=np.object))
Args: df (DataFlow): the DataFlow to serialize. path (str): output tfrecord file. def save(df, path): """ Args: df (DataFlow): the DataFlow to serialize. path (str): output tfrecord file. """ if os.environ.get('TENSORPACK_COMPATIBLE_SERIALIZE', 'msgpack') == 'msgpack': def _dumps(dp): return dumps(dp) else: def _dumps(dp): return dumps(dp).to_pybytes() size = _reset_df_and_get_size(df) with tf.python_io.TFRecordWriter(path) as writer, get_tqdm(total=size) as pbar: for dp in df: writer.write(_dumps(dp)) pbar.update()
Args: size (int): total number of records. If not provided, the returned dataflow will have no `__len__()`. It's needed because this metadata is not stored in the TFRecord file. def load(path, size=None): """ Args: size (int): total number of records. If not provided, the returned dataflow will have no `__len__()`. It's needed because this metadata is not stored in the TFRecord file. """ gen = tf.python_io.tf_record_iterator(path) ds = DataFromGenerator(gen) ds = MapData(ds, loads) if size is not None: ds = FixedSizeData(ds, size) return ds
Args: df (DataFlow): the DataFlow to serialize. path (str): output hdf5 file. data_paths (list[str]): list of h5 paths. It should have the same length as each datapoint, and each path should correspond to one component of the datapoint. def save(df, path, data_paths): """ Args: df (DataFlow): the DataFlow to serialize. path (str): output hdf5 file. data_paths (list[str]): list of h5 paths. It should have the same length as each datapoint, and each path should correspond to one component of the datapoint. """ size = _reset_df_and_get_size(df) buffer = defaultdict(list) with get_tqdm(total=size) as pbar: for dp in df: assert len(dp) == len(data_paths), "Datapoint has {} components!".format(len(dp)) for k, el in zip(data_paths, dp): buffer[k].append(el) pbar.update() with h5py.File(path, 'w') as hf, get_tqdm(total=len(data_paths)) as pbar: for data_path in data_paths: hf.create_dataset(data_path, data=buffer[data_path]) pbar.update()
Args: trainer (SingleCostTrainer): get_model (input1, input2, ... -> tf.keras.Model): A function which takes tensors, builds and returns a Keras model. It will be part of the tower function. input (InputSource): optimizer (tf.train.Optimizer): loss, metrics: list of strings def setup_keras_trainer( trainer, get_model, input_signature, target_signature, input, optimizer, loss, metrics): """ Args: trainer (SingleCostTrainer): get_model (input1, input2, ... -> tf.keras.Model): A function which takes tensors, builds and returns a Keras model. It will be part of the tower function. input (InputSource): optimizer (tf.train.Optimizer): loss, metrics: list of strings """ assert isinstance(optimizer, tf.train.Optimizer), optimizer assert isinstance(loss, list), loss assert len(loss) >= 1, "No loss was given!" assert isinstance(metrics, list), metrics model_caller = KerasModelCaller(get_model) nr_inputs = len(input_signature) def get_cost(*inputs): ctx = get_current_tower_context() input_tensors = list(inputs[:nr_inputs]) target_tensors = list(inputs[nr_inputs:]) # TODO mapping between target tensors & output tensors outputs = model_caller(input_tensors) if isinstance(outputs, tf.Tensor): outputs = [outputs] assert len(outputs) == len(target_tensors), \ "len({}) != len({})".format(str(outputs), str(target_tensors)) assert len(outputs) == len(loss), \ "len({}) != len({})".format(str(outputs), str(loss)) loss_tensors = [] for idx, loss_name in enumerate(loss): with cached_name_scope('keras_loss', top_level=False): loss_fn = keras.losses.get(loss_name) curr_loss = loss_fn(target_tensors[idx], outputs[idx]) curr_loss = tf.reduce_mean(curr_loss, name=loss_name) _check_name(curr_loss, loss_name) loss_tensors.append(curr_loss) loss_reg = regularize_cost_from_collection() if loss_reg is not None: total_loss = tf.add_n(loss_tensors + [loss_reg], name=TOTAL_LOSS_NAME) add_moving_summary(loss_reg, total_loss, *loss_tensors) else: total_loss = tf.add_n(loss_tensors, name=TOTAL_LOSS_NAME) add_moving_summary(total_loss, *loss_tensors) if metrics and (ctx.is_main_training_tower or not ctx.is_training): # for list: one metric for each output metric_tensors = [] for oid, metric_name in enumerate(metrics): output_tensor = outputs[oid] target_tensor = target_tensors[oid] # TODO may not have the same mapping? with cached_name_scope('keras_metric', top_level=False): metric_fn = keras.metrics.get(metric_name) metric_tensor = metric_fn(target_tensor, output_tensor) metric_tensor = tf.reduce_mean(metric_tensor, name=metric_name) _check_name(metric_tensor, metric_name) # check name conflict here metric_tensors.append(metric_tensor) add_moving_summary(*metric_tensors) return total_loss trainer.setup_graph( input_signature + target_signature, input, get_cost, lambda: optimizer) if len(keras.backend.learning_phase().consumers()) > 0: # check if learning_phase is used in this model trainer.register_callback(KerasPhaseCallback(True))
Args: optimizer (tf.train.Optimizer): loss, metrics: string or list of strings def compile(self, optimizer, loss, metrics=None): """ Args: optimizer (tf.train.Optimizer): loss, metrics: string or list of strings """ if isinstance(loss, six.string_types): loss = [loss] if metrics is None: metrics = [] if isinstance(metrics, six.string_types): metrics = [metrics] self._stats_to_inference = loss + metrics + [TOTAL_LOSS_NAME] setup_keras_trainer( self.trainer, get_model=self.get_model, input_signature=self.input_signature, target_signature=self.target_signature, input=self.input, optimizer=optimizer, loss=loss, metrics=metrics)
Args: validation_data (DataFlow or InputSource): to be used for inference. The inference callback is added as the first in the callback list. If you need to use it in a different order, please write it in the callback list manually. kwargs: same arguments as :meth:`Trainer.train_with_defaults`. def fit(self, validation_data=None, **kwargs): """ Args: validation_data (DataFlow or InputSource): to be used for inference. The inference callback is added as the first in the callback list. If you need to use it in a different order, please write it in the callback list manually. kwargs: same arguments as :meth:`Trainer.train_with_defaults`. """ callbacks = kwargs.pop('callbacks', []) if validation_data is not None: # There is no way to guess where users want this callback. So we have to choose one. # MinSaver may need results from this callback, # so we put this callback at first. callbacks.insert(0, InferenceRunner( validation_data, ScalarStats(self._stats_to_inference))) self.trainer.train_with_defaults(callbacks=callbacks, **kwargs)
Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively def get_dorefa(bitW, bitA, bitG): """ Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively """ def quantize(x, k): n = float(2 ** k - 1) @tf.custom_gradient def _quantize(x): return tf.round(x * n) / n, lambda dy: dy return _quantize(x) def fw(x): if bitW == 32: return x if bitW == 1: # BWN E = tf.stop_gradient(tf.reduce_mean(tf.abs(x))) @tf.custom_gradient def _sign(x): return tf.where(tf.equal(x, 0), tf.ones_like(x), tf.sign(x / E)) * E, lambda dy: dy return _sign(x) x = tf.tanh(x) x = x / tf.reduce_max(tf.abs(x)) * 0.5 + 0.5 return 2 * quantize(x, bitW) - 1 def fa(x): if bitA == 32: return x return quantize(x, bitA) def fg(x): if bitG == 32: return x @tf.custom_gradient def _identity(input): def grad_fg(x): rank = x.get_shape().ndims assert rank is not None maxx = tf.reduce_max(tf.abs(x), list(range(1, rank)), keep_dims=True) x = x / maxx n = float(2**bitG - 1) x = x * 0.5 + 0.5 + tf.random_uniform( tf.shape(x), minval=-0.5 / n, maxval=0.5 / n) x = tf.clip_by_value(x, 0.0, 1.0) x = quantize(x, bitG) - 0.5 return x * maxx * 2 return input, grad_fg return _identity(x) return fw, fa, fg
Implemented Trained Ternary Quantization: https://arxiv.org/abs/1612.01064 Code modified from the authors' at: https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py def ternarize(x, thresh=0.05): """ Implemented Trained Ternary Quantization: https://arxiv.org/abs/1612.01064 Code modified from the authors' at: https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py """ shape = x.get_shape() thre_x = tf.stop_gradient(tf.reduce_max(tf.abs(x)) * thresh) w_p = tf.get_variable('Wp', initializer=1.0, dtype=tf.float32) w_n = tf.get_variable('Wn', initializer=1.0, dtype=tf.float32) tf.summary.scalar(w_p.op.name + '-summary', w_p) tf.summary.scalar(w_n.op.name + '-summary', w_n) mask = tf.ones(shape) mask_p = tf.where(x > thre_x, tf.ones(shape) * w_p, mask) mask_np = tf.where(x < -thre_x, tf.ones(shape) * w_n, mask_p) mask_z = tf.where((x < thre_x) & (x > - thre_x), tf.zeros(shape), mask) @tf.custom_gradient def _sign_mask(x): return tf.sign(x) * mask_z, lambda dy: dy w = _sign_mask(x) w = w * mask_np tf.summary.histogram(w.name, w) return w
Args: img (np.ndarray): an image (expect BGR) to show. lclick_cb, rclick_cb: a callback ``func(img, x, y)`` for left/right click event. kwargs: can be {key_cb_a: callback_img, key_cb_b: callback_img}, to specify a callback ``func(img)`` for keypress. Some existing keypress event handler: * q: destroy the current window * x: execute ``sys.exit()`` * s: save image to "out.png" def interactive_imshow(img, lclick_cb=None, rclick_cb=None, **kwargs): """ Args: img (np.ndarray): an image (expect BGR) to show. lclick_cb, rclick_cb: a callback ``func(img, x, y)`` for left/right click event. kwargs: can be {key_cb_a: callback_img, key_cb_b: callback_img}, to specify a callback ``func(img)`` for keypress. Some existing keypress event handler: * q: destroy the current window * x: execute ``sys.exit()`` * s: save image to "out.png" """ name = 'tensorpack_viz_window' cv2.imshow(name, img) def mouse_cb(event, x, y, *args): if event == cv2.EVENT_LBUTTONUP and lclick_cb is not None: lclick_cb(img, x, y) elif event == cv2.EVENT_RBUTTONUP and rclick_cb is not None: rclick_cb(img, x, y) cv2.setMouseCallback(name, mouse_cb) key = cv2.waitKey(-1) while key >= 128: key = cv2.waitKey(-1) key = chr(key & 0xff) cb_name = 'key_cb_' + key if cb_name in kwargs: kwargs[cb_name](img) elif key == 'q': cv2.destroyWindow(name) elif key == 'x': sys.exit() elif key == 's': cv2.imwrite('out.png', img) elif key in ['+', '=']: img = cv2.resize(img, None, fx=1.3, fy=1.3, interpolation=cv2.INTER_CUBIC) interactive_imshow(img, lclick_cb, rclick_cb, **kwargs) elif key == '-': img = cv2.resize(img, None, fx=0.7, fy=0.7, interpolation=cv2.INTER_CUBIC) interactive_imshow(img, lclick_cb, rclick_cb, **kwargs)
Stacked patches into grid, to produce visualizations like the following: .. image:: https://github.com/tensorpack/tensorpack/raw/master/examples/GAN/demo/BEGAN-CelebA-samples.jpg Args: patch_list(list[ndarray] or ndarray): NHW or NHWC images in [0,255]. nr_row(int), nr_col(int): rows and cols of the grid. ``nr_col * nr_row`` must be no less than ``len(patch_list)``. border(int): border length between images. Defaults to ``0.05 * min(patch_width, patch_height)``. pad (boolean): when `patch_list` is a list, pad all patches to the maximum height and width. This option allows stacking patches of different shapes together. bgcolor(int or 3-tuple): background color in [0, 255]. Either an int or a BGR tuple. viz(bool): whether to use :func:`interactive_imshow` to visualize the results. lclick_cb: A callback function ``f(patch, patch index in patch_list)`` to get called when a patch get clicked in imshow. Returns: np.ndarray: the stacked image. def stack_patches( patch_list, nr_row, nr_col, border=None, pad=False, bgcolor=255, viz=False, lclick_cb=None): """ Stacked patches into grid, to produce visualizations like the following: .. image:: https://github.com/tensorpack/tensorpack/raw/master/examples/GAN/demo/BEGAN-CelebA-samples.jpg Args: patch_list(list[ndarray] or ndarray): NHW or NHWC images in [0,255]. nr_row(int), nr_col(int): rows and cols of the grid. ``nr_col * nr_row`` must be no less than ``len(patch_list)``. border(int): border length between images. Defaults to ``0.05 * min(patch_width, patch_height)``. pad (boolean): when `patch_list` is a list, pad all patches to the maximum height and width. This option allows stacking patches of different shapes together. bgcolor(int or 3-tuple): background color in [0, 255]. Either an int or a BGR tuple. viz(bool): whether to use :func:`interactive_imshow` to visualize the results. lclick_cb: A callback function ``f(patch, patch index in patch_list)`` to get called when a patch get clicked in imshow. Returns: np.ndarray: the stacked image. """ if pad: patch_list = _pad_patch_list(patch_list, bgcolor) patch_list = _preprocess_patch_list(patch_list) if lclick_cb is not None: viz = True ph, pw = patch_list.shape[1:3] canvas = Canvas(ph, pw, nr_row, nr_col, patch_list.shape[-1], border, bgcolor) if lclick_cb is not None: def lclick_callback(img, x, y): idx = canvas.get_patchid_from_coord(x, y) lclick_cb(patch_list[idx], idx) else: lclick_callback = None canvas.draw_patches(patch_list) if viz: interactive_imshow(canvas.canvas, lclick_cb=lclick_callback) return canvas.canvas
Similar to :func:`stack_patches` but with a generator interface. It takes a much-longer list and yields stacked results one by one. For example, if ``patch_list`` contains 1000 images and ``nr_row==nr_col==10``, this generator yields 10 stacked images. Args: nr_row(int), nr_col(int): rows and cols of each result. max_width(int), max_height(int): Maximum allowed size of the stacked image. If ``nr_row/nr_col`` are None, this number will be used to infer the rows and cols. Otherwise the option is ignored. patch_list, border, viz, lclick_cb: same as in :func:`stack_patches`. Yields: np.ndarray: the stacked image. def gen_stack_patches(patch_list, nr_row=None, nr_col=None, border=None, max_width=1000, max_height=1000, bgcolor=255, viz=False, lclick_cb=None): """ Similar to :func:`stack_patches` but with a generator interface. It takes a much-longer list and yields stacked results one by one. For example, if ``patch_list`` contains 1000 images and ``nr_row==nr_col==10``, this generator yields 10 stacked images. Args: nr_row(int), nr_col(int): rows and cols of each result. max_width(int), max_height(int): Maximum allowed size of the stacked image. If ``nr_row/nr_col`` are None, this number will be used to infer the rows and cols. Otherwise the option is ignored. patch_list, border, viz, lclick_cb: same as in :func:`stack_patches`. Yields: np.ndarray: the stacked image. """ # setup parameters patch_list = _preprocess_patch_list(patch_list) if lclick_cb is not None: viz = True ph, pw = patch_list.shape[1:3] if border is None: border = int(0.05 * min(ph, pw)) if nr_row is None: nr_row = int(max_height / (ph + border)) if nr_col is None: nr_col = int(max_width / (pw + border)) canvas = Canvas(ph, pw, nr_row, nr_col, patch_list.shape[-1], border, bgcolor) nr_patch = nr_row * nr_col start = 0 if lclick_cb is not None: def lclick_callback(img, x, y): idx = canvas.get_patchid_from_coord(x, y) idx = idx + start if idx < end: lclick_cb(patch_list[idx], idx) else: lclick_callback = None while True: end = start + nr_patch cur_list = patch_list[start:end] if not len(cur_list): return canvas.draw_patches(cur_list) if viz: interactive_imshow(canvas.canvas, lclick_cb=lclick_callback) yield canvas.canvas start = end
Dump or visualize images of a :class:`DataFlow`. Args: df (DataFlow): the DataFlow. index (int): the index of the image component. batched (bool): whether the component contains batched images (NHW or NHWC) or not (HW or HWC). number (int): how many datapoint to take from the DataFlow. output_dir (str): output directory to save images, default to not save. scale (float): scale the value, usually either 1 or 255. resize (tuple or None): tuple of (h, w) to resize the images to. viz (tuple or None): tuple of (h, w) determining the grid size to use with :func:`gen_stack_patches` for visualization. No visualization will happen by default. flipRGB (bool): apply a RGB<->BGR conversion or not. def dump_dataflow_images(df, index=0, batched=True, number=1000, output_dir=None, scale=1, resize=None, viz=None, flipRGB=False): """ Dump or visualize images of a :class:`DataFlow`. Args: df (DataFlow): the DataFlow. index (int): the index of the image component. batched (bool): whether the component contains batched images (NHW or NHWC) or not (HW or HWC). number (int): how many datapoint to take from the DataFlow. output_dir (str): output directory to save images, default to not save. scale (float): scale the value, usually either 1 or 255. resize (tuple or None): tuple of (h, w) to resize the images to. viz (tuple or None): tuple of (h, w) determining the grid size to use with :func:`gen_stack_patches` for visualization. No visualization will happen by default. flipRGB (bool): apply a RGB<->BGR conversion or not. """ if output_dir: mkdir_p(output_dir) if viz is not None: viz = shape2d(viz) vizsize = viz[0] * viz[1] if resize is not None: resize = tuple(shape2d(resize)) vizlist = [] df.reset_state() cnt = 0 while True: for dp in df: if not batched: imgbatch = [dp[index]] else: imgbatch = dp[index] for img in imgbatch: cnt += 1 if cnt == number: return if scale != 1: img = img * scale if resize is not None: img = cv2.resize(img, resize) if flipRGB: img = img[:, :, ::-1] if output_dir: fname = os.path.join(output_dir, '{:03d}.jpg'.format(cnt)) cv2.imwrite(fname, img) if viz is not None: vizlist.append(img) if viz is not None and len(vizlist) >= vizsize: stack_patches( vizlist[:vizsize], nr_row=viz[0], nr_col=viz[1], viz=True) vizlist = vizlist[vizsize:]
Convert a 1-channel matrix of intensities to an RGB image employing a colormap. This function requires matplotlib. See `matplotlib colormaps <http://matplotlib.org/examples/color/colormaps_reference.html>`_ for a list of available colormap. Args: intensity (np.ndarray): array of intensities such as saliency. cmap (str): name of the colormap to use. normalize (bool): if True, will normalize the intensity so that it has minimum 0 and maximum 1. Returns: np.ndarray: an RGB float32 image in range [0, 255], a colored heatmap. def intensity_to_rgb(intensity, cmap='cubehelix', normalize=False): """ Convert a 1-channel matrix of intensities to an RGB image employing a colormap. This function requires matplotlib. See `matplotlib colormaps <http://matplotlib.org/examples/color/colormaps_reference.html>`_ for a list of available colormap. Args: intensity (np.ndarray): array of intensities such as saliency. cmap (str): name of the colormap to use. normalize (bool): if True, will normalize the intensity so that it has minimum 0 and maximum 1. Returns: np.ndarray: an RGB float32 image in range [0, 255], a colored heatmap. """ assert intensity.ndim == 2, intensity.shape intensity = intensity.astype("float") if normalize: intensity -= intensity.min() intensity /= intensity.max() cmap = plt.get_cmap(cmap) intensity = cmap(intensity)[..., :3] return intensity.astype('float32') * 255.0
Draw text on an image. Args: pos (tuple): x, y; the position of the text text (str): font_scale (float): color (tuple): a 3-tuple BGR color in [0, 255] def draw_text(img, pos, text, color, font_scale=0.4): """ Draw text on an image. Args: pos (tuple): x, y; the position of the text text (str): font_scale (float): color (tuple): a 3-tuple BGR color in [0, 255] """ img = img.astype(np.uint8) x0, y0 = int(pos[0]), int(pos[1]) # Compute text size. font = cv2.FONT_HERSHEY_SIMPLEX ((text_w, text_h), _) = cv2.getTextSize(text, font, font_scale, 1) # Place text background. if x0 + text_w > img.shape[1]: x0 = img.shape[1] - text_w if y0 - int(1.15 * text_h) < 0: y0 = int(1.15 * text_h) back_topleft = x0, y0 - int(1.3 * text_h) back_bottomright = x0 + text_w, y0 cv2.rectangle(img, back_topleft, back_bottomright, color, -1) # Show text. text_bottomleft = x0, y0 - int(0.25 * text_h) cv2.putText(img, text, text_bottomleft, font, font_scale, (222, 222, 222), lineType=cv2.LINE_AA) return img
Args: im (np.ndarray): a BGR image in range [0,255]. It will not be modified. boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2]. labels: (list[str] or None) color: a 3-tuple BGR color (in range [0, 255]) Returns: np.ndarray: a new image. def draw_boxes(im, boxes, labels=None, color=None): """ Args: im (np.ndarray): a BGR image in range [0,255]. It will not be modified. boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2]. labels: (list[str] or None) color: a 3-tuple BGR color (in range [0, 255]) Returns: np.ndarray: a new image. """ boxes = np.asarray(boxes, dtype='int32') if labels is not None: assert len(labels) == len(boxes), "{} != {}".format(len(labels), len(boxes)) areas = (boxes[:, 2] - boxes[:, 0] + 1) * (boxes[:, 3] - boxes[:, 1] + 1) sorted_inds = np.argsort(-areas) # draw large ones first assert areas.min() > 0, areas.min() # allow equal, because we are not very strict about rounding error here assert boxes[:, 0].min() >= 0 and boxes[:, 1].min() >= 0 \ and boxes[:, 2].max() <= im.shape[1] and boxes[:, 3].max() <= im.shape[0], \ "Image shape: {}\n Boxes:\n{}".format(str(im.shape), str(boxes)) im = im.copy() if color is None: color = (15, 128, 15) if im.ndim == 2 or (im.ndim == 3 and im.shape[2] == 1): im = cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) for i in sorted_inds: box = boxes[i, :] if labels is not None: im = draw_text(im, (box[0], box[1]), labels[i], color=color) cv2.rectangle(im, (box[0], box[1]), (box[2], box[3]), color=color, thickness=1) return im
A wrapper around ``tf.concat`` to cooperate with :class:`LinearWrap`. Args: x (tf.Tensor): input tensor (list[tf.Tensor]): a tensor or list of tensors to concatenate with x. x will be at the beginning dim (int): the dimension along which to concatenate Returns: tf.Tensor: ``tf.concat([x] + tensor, dim)`` def ConcatWith(x, tensor, dim): """ A wrapper around ``tf.concat`` to cooperate with :class:`LinearWrap`. Args: x (tf.Tensor): input tensor (list[tf.Tensor]): a tensor or list of tensors to concatenate with x. x will be at the beginning dim (int): the dimension along which to concatenate Returns: tf.Tensor: ``tf.concat([x] + tensor, dim)`` """ if type(tensor) != list: tensor = [tensor] return tf.concat([x] + tensor, dim)
Args: points: (nx4)x2 Returns: nx4 boxes (x1y1x2y2) def point8_to_box(points): """ Args: points: (nx4)x2 Returns: nx4 boxes (x1y1x2y2) """ p = points.reshape((-1, 4, 2)) minxy = p.min(axis=1) # nx2 maxxy = p.max(axis=1) # nx2 return np.concatenate((minxy, maxxy), axis=1)
Convert polygons to binary masks. Args: polys: a list of nx2 float array. Each array contains many (x, y) coordinates. Returns: a binary matrix of (height, width) def segmentation_to_mask(polys, height, width): """ Convert polygons to binary masks. Args: polys: a list of nx2 float array. Each array contains many (x, y) coordinates. Returns: a binary matrix of (height, width) """ polys = [p.flatten().tolist() for p in polys] assert len(polys) > 0, "Polygons are empty!" import pycocotools.mask as cocomask rles = cocomask.frPyObjects(polys, height, width) rle = cocomask.merge(rles) return cocomask.decode(rle)
Args: boxes: (...)x4, float shape: h, w def clip_boxes(boxes, shape): """ Args: boxes: (...)x4, float shape: h, w """ orig_shape = boxes.shape boxes = boxes.reshape([-1, 4]) h, w = shape boxes[:, [0, 1]] = np.maximum(boxes[:, [0, 1]], 0) boxes[:, 2] = np.minimum(boxes[:, 2], w) boxes[:, 3] = np.minimum(boxes[:, 3], h) return boxes.reshape(orig_shape)
Args: boxes: (nx4), float shape: (h, w) Returns: indices: (k, ) selection: (kx4) def filter_boxes_inside_shape(boxes, shape): """ Args: boxes: (nx4), float shape: (h, w) Returns: indices: (k, ) selection: (kx4) """ assert boxes.ndim == 2, boxes.shape assert len(shape) == 2, shape h, w = shape indices = np.where( (boxes[:, 0] >= 0) & (boxes[:, 1] >= 0) & (boxes[:, 2] <= w) & (boxes[:, 3] <= h))[0] return indices, boxes[indices, :]
Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size. def MaxPooling( inputs, pool_size, strides=None, padding='valid', data_format='channels_last'): """ Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size. """ if strides is None: strides = pool_size layer = tf.layers.MaxPooling2D(pool_size, strides, padding=padding, data_format=data_format) ret = layer.apply(inputs, scope=tf.get_variable_scope()) return tf.identity(ret, name='output')
Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size. def AvgPooling( inputs, pool_size, strides=None, padding='valid', data_format='channels_last'): """ Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size. """ if strides is None: strides = pool_size layer = tf.layers.AveragePooling2D(pool_size, strides, padding=padding, data_format=data_format) ret = layer.apply(inputs, scope=tf.get_variable_scope()) return tf.identity(ret, name='output')
Global average pooling as in the paper `Network In Network <http://arxiv.org/abs/1312.4400>`_. Args: x (tf.Tensor): a 4D tensor. Returns: tf.Tensor: a NC tensor named ``output``. def GlobalAvgPooling(x, data_format='channels_last'): """ Global average pooling as in the paper `Network In Network <http://arxiv.org/abs/1312.4400>`_. Args: x (tf.Tensor): a 4D tensor. Returns: tf.Tensor: a NC tensor named ``output``. """ assert x.shape.ndims == 4 data_format = get_data_format(data_format) axis = [1, 2] if data_format == 'channels_last' else [2, 3] return tf.reduce_mean(x, axis, name='output')
Unpool the input with a fixed matrix to perform kronecker product with. Args: x (tf.Tensor): a 4D image tensor shape: int or (h, w) tuple unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape. If is None, will use a matrix with 1 at top-left corner. Returns: tf.Tensor: a 4D image tensor. def FixedUnPooling(x, shape, unpool_mat=None, data_format='channels_last'): """ Unpool the input with a fixed matrix to perform kronecker product with. Args: x (tf.Tensor): a 4D image tensor shape: int or (h, w) tuple unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape. If is None, will use a matrix with 1 at top-left corner. Returns: tf.Tensor: a 4D image tensor. """ data_format = get_data_format(data_format, keras_mode=False) shape = shape2d(shape) output_shape = StaticDynamicShape(x) output_shape.apply(1 if data_format == 'NHWC' else 2, lambda x: x * shape[0]) output_shape.apply(2 if data_format == 'NHWC' else 3, lambda x: x * shape[1]) # a faster implementation for this special case if shape[0] == 2 and shape[1] == 2 and unpool_mat is None and data_format == 'NHWC': ret = UnPooling2x2ZeroFilled(x) else: # check unpool_mat if unpool_mat is None: mat = np.zeros(shape, dtype='float32') mat[0][0] = 1 unpool_mat = tf.constant(mat, name='unpool_mat') elif isinstance(unpool_mat, np.ndarray): unpool_mat = tf.constant(unpool_mat, name='unpool_mat') assert unpool_mat.shape.as_list() == list(shape) if data_format == 'NHWC': x = tf.transpose(x, [0, 3, 1, 2]) # perform a tensor-matrix kronecker product x = tf.expand_dims(x, -1) # bchwx1 mat = tf.expand_dims(unpool_mat, 0) # 1xshxsw ret = tf.tensordot(x, mat, axes=1) # bxcxhxwxshxsw if data_format == 'NHWC': ret = tf.transpose(ret, [0, 2, 4, 3, 5, 1]) else: ret = tf.transpose(ret, [0, 1, 2, 4, 3, 5]) shape3_dyn = [output_shape.get_dynamic(k) for k in range(1, 4)] ret = tf.reshape(ret, tf.stack([-1] + shape3_dyn)) ret.set_shape(tf.TensorShape(output_shape.get_static())) return ret
Args: varname(str): a variable name in the graph varname_prefix(str): an optional prefix that may need to be removed in varname savename_prefix(str): an optional prefix to append to all savename Returns: str: the name used to save the variable def get_savename_from_varname( varname, varname_prefix=None, savename_prefix=None): """ Args: varname(str): a variable name in the graph varname_prefix(str): an optional prefix that may need to be removed in varname savename_prefix(str): an optional prefix to append to all savename Returns: str: the name used to save the variable """ name = varname if varname_prefix is not None \ and name.startswith(varname_prefix): name = name[len(varname_prefix) + 1:] if savename_prefix is not None: name = savename_prefix + '/' + name return name
Dump value of all TRAINABLE + MODEL variables to a dict, and save as npz format (loadable by :func:`sessinit.get_model_loader`). Args: path(str): the file name to save the parameters. Must ends with npz. def dump_session_params(path): """ Dump value of all TRAINABLE + MODEL variables to a dict, and save as npz format (loadable by :func:`sessinit.get_model_loader`). Args: path(str): the file name to save the parameters. Must ends with npz. """ # save variables that are GLOBAL, and either TRAINABLE or MODEL var = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) var.extend(tf.get_collection(tf.GraphKeys.MODEL_VARIABLES)) # TODO dedup assert len(set(var)) == len(var), "TRAINABLE and MODEL variables have duplication!" gvars = set([k.name for k in tf.global_variables()]) var = [v for v in var if v.name in gvars] result = {} for v in var: result[v.name] = v.eval() save_chkpt_vars(result, path)
Save variables in dic to path. Args: dic: {name: value} path: save as npz if the name ends with '.npz', otherwise save as a checkpoint. def save_chkpt_vars(dic, path): """ Save variables in dic to path. Args: dic: {name: value} path: save as npz if the name ends with '.npz', otherwise save as a checkpoint. """ logger.info("Variables to save to {}:".format(path)) keys = sorted(list(dic.keys())) logger.info(pprint.pformat(keys)) assert not path.endswith('.npy') if path.endswith('.npz'): np.savez_compressed(path, **dic) else: with tf.Graph().as_default(), \ tf.Session() as sess: for k, v in six.iteritems(dic): k = get_op_tensor_name(k)[0] _ = tf.Variable(name=k, initial_value=v) # noqa sess.run(tf.global_variables_initializer()) saver = tf.train.Saver() saver.save(sess, path, write_meta_graph=False)
Work around TF problems in checkpoint path handling. Args: model_path: a user-input path Returns: str: the argument that can be passed to NewCheckpointReader def get_checkpoint_path(model_path): """ Work around TF problems in checkpoint path handling. Args: model_path: a user-input path Returns: str: the argument that can be passed to NewCheckpointReader """ if os.path.basename(model_path) == model_path: model_path = os.path.join('.', model_path) # avoid #4921 and #6142 if os.path.basename(model_path) == 'checkpoint': assert tfv1.gfile.Exists(model_path), model_path model_path = tf.train.latest_checkpoint(os.path.dirname(model_path)) # to be consistent with either v1 or v2 # fix paths if provided a wrong one new_path = model_path if '00000-of-00001' in model_path: new_path = model_path.split('.data')[0] elif model_path.endswith('.index'): new_path = model_path.split('.index')[0] if new_path != model_path: logger.info( "Checkpoint path {} is auto-corrected to {}.".format(model_path, new_path)) model_path = new_path assert tfv1.gfile.Exists(model_path) or tfv1.gfile.Exists(model_path + '.index'), model_path return model_path
Load all variables from a checkpoint to a dict. Args: model_path(str): path to a checkpoint. Returns: dict: a name:value dict def load_chkpt_vars(model_path): """ Load all variables from a checkpoint to a dict. Args: model_path(str): path to a checkpoint. Returns: dict: a name:value dict """ model_path = get_checkpoint_path(model_path) reader = tfv1.train.NewCheckpointReader(model_path) var_names = reader.get_variable_to_shape_map().keys() result = {} for n in var_names: result[n] = reader.get_tensor(n) return result
**Guess** if this variable is only used in training. Only used internally to avoid too many logging. Do not use it. def is_training_name(name): """ **Guess** if this variable is only used in training. Only used internally to avoid too many logging. Do not use it. """ # TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES? # TODO or use get_slot_names() name = get_op_tensor_name(name)[0] if name.endswith('/Adam') or name.endswith('/Adam_1'): return True if name.endswith('/Momentum'): return True if name.endswith('/Adadelta') or name.endswith('/Adadelta_1'): return True if name.endswith('/RMSProp') or name.endswith('/RMSProp_1'): return True if name.endswith('/Adagrad'): return True if name.startswith('EMA/') or '/EMA/' in name: # all the moving average summaries return True if name.startswith('AccumGrad') or name.endswith('/AccumGrad'): return True if name.startswith('apply_gradients'): return True return False
Returns a relaxed (possibly reshaped/upcast-ed) version of value, to be loaded to the given variable. Args: value (ndarray): an numpy array to be loaded to var var (tf.Variable): Returns: ndarray: a possibly reshaped or casted version of value def relaxed_value_for_var(value, var): """ Returns a relaxed (possibly reshaped/upcast-ed) version of value, to be loaded to the given variable. Args: value (ndarray): an numpy array to be loaded to var var (tf.Variable): Returns: ndarray: a possibly reshaped or casted version of value """ assert isinstance(var, tf.Variable) name = var.op.name # check incompatible shape varshape = tuple(var.get_shape().as_list()) if varshape != value.shape: # TODO only allow reshape when shape different by empty axis if np.prod(varshape) != np.prod(value.shape): raise ValueError( "Trying to load a tensor of shape {} into the variable '{}' whose shape is {}.".format( value.shape, name, varshape)) logger.warn("The tensor is reshaped from {} to {} when assigned to '{}'".format( value.shape, varshape, name)) value = value.reshape(varshape) # fix some common type incompatibility problems, but not all def upcast(vartype, valtype): # vartype: a tf dtype # valtype: a numpy dtype # allow up-casting if vartype == tf.float64 and valtype == np.float32: return np.float64 if vartype in [tf.int64, tf.int32] and valtype in [np.int32, np.int16, np.int8]: return np.int64 if vartype == tf.int64 else np.int32 return None if hasattr(value, 'dtype'): vartype = var.dtype.as_numpy_dtype if vartype != value.dtype: msg = "Variable {} has dtype {} but was given a value of dtype {}.".format(name, vartype, value.dtype) newtype = upcast(var.dtype.base_dtype, value.dtype) if newtype is not None: value = newtype(value) logger.warn(msg + " Load it after casting!") else: assert vartype == value.dtype, msg return value
Args: prms(dict): dict of {variable name: value} Any name in prms must be in the graph and in vars_to_update. def update(self, prms): """ Args: prms(dict): dict of {variable name: value} Any name in prms must be in the graph and in vars_to_update. """ with self.sess.as_default(): fetches = [] feeds = {} for name, value in six.iteritems(prms): assert name in self.name_map var = self.name_map[name] fetches.append(var.initializer) # This is the implementation of `var.load` feeds[var.initializer.inputs[1]] = SessionUpdate.relaxed_value_for_var(value, var) self.sess.run(fetches, feed_dict=feeds)
Args: server (tf.train.Server): Returns: tf.train.SessionCreator def get_distributed_session_creator(server): """ Args: server (tf.train.Server): Returns: tf.train.SessionCreator """ server_def = server.server_def is_chief = (server_def.job_name == 'worker') and (server_def.task_index == 0) init_op = tf.global_variables_initializer() local_init_op = tf.local_variables_initializer() ready_op = tf.report_uninitialized_variables() ready_for_local_init_op = tf.report_uninitialized_variables(tf.global_variables()) sm = tf.train.SessionManager( local_init_op=local_init_op, ready_op=ready_op, ready_for_local_init_op=ready_for_local_init_op, graph=tf.get_default_graph()) # to debug wrong variable collection # from pprint import pprint # print("GLOBAL:") # pprint([(k.name, k.device) for k in tf.global_variables()]) # print("LOCAL:") # pprint([(k.name, k.device) for k in tf.local_variables()]) class _Creator(tf.train.SessionCreator): def create_session(self): if is_chief: return sm.prepare_session(master=server.target, init_op=init_op) else: tf.logging.set_verbosity(tf.logging.INFO) # print message about uninitialized vars ret = sm.wait_for_session(master=server.target) tf.logging.set_verbosity(tf.logging.WARN) return ret return _Creator()
Returns: int: #available GPUs in CUDA_VISIBLE_DEVICES, or in the system. def get_num_gpu(): """ Returns: int: #available GPUs in CUDA_VISIBLE_DEVICES, or in the system. """ def warn_return(ret, message): try: import tensorflow as tf except ImportError: return ret built_with_cuda = tf.test.is_built_with_cuda() if not built_with_cuda and ret > 0: logger.warn(message + "But TensorFlow was not built with CUDA support and could not use GPUs!") return ret env = os.environ.get('CUDA_VISIBLE_DEVICES', None) if env: return warn_return(len(env.split(',')), "Found non-empty CUDA_VISIBLE_DEVICES. ") output, code = subproc_call("nvidia-smi -L", timeout=5) if code == 0: output = output.decode('utf-8') return warn_return(len(output.strip().split('\n')), "Found nvidia-smi. ") try: # Use NVML to query device properties with NVMLContext() as ctx: return warn_return(ctx.num_devices(), "NVML found nvidia devices. ") except Exception: # Fallback logger.info("Loading local devices by TensorFlow ...") try: import tensorflow as tf # available since TF 1.14 gpu_devices = tf.config.experimental.list_physical_devices('GPU') except AttributeError: from tensorflow.python.client import device_lib local_device_protos = device_lib.list_local_devices() # Note this will initialize all GPUs and therefore has side effect # https://github.com/tensorflow/tensorflow/issues/8136 gpu_devices = [x.name for x in local_device_protos if x.device_type == 'GPU'] return len(gpu_devices)
Put a `tf.Summary`. def put_summary(self, summary): """ Put a `tf.Summary`. """ if isinstance(summary, six.binary_type): summary = tf.Summary.FromString(summary) assert isinstance(summary, tf.Summary), type(summary) # TODO other types for val in summary.value: if val.WhichOneof('value') == 'simple_value': val.tag = re.sub('tower[0-9]+/', '', val.tag) # TODO move to subclasses # TODO This hack is still needed, seem to disappear only when # compiled from source. suffix = '-summary' # tensorflow#6150, tensorboard#59 if val.tag.endswith(suffix): val.tag = val.tag[:-len(suffix)] self._dispatch(lambda m: m.process_scalar(val.tag, val.simple_value)) self._dispatch(lambda m: m.process_summary(summary))
Put a scalar. def put_scalar(self, name, val): """ Put a scalar. """ if isinstance(val, np.floating): val = float(val) if isinstance(val, np.integer): val = int(val) self._dispatch(lambda m: m.process_scalar(name, val)) s = create_scalar_summary(name, val) self._dispatch(lambda m: m.process_summary(s))
Put an image. Args: name (str): val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images in range [0,255]. If channel is 3, assumed to be RGB. def put_image(self, name, val): """ Put an image. Args: name (str): val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images in range [0,255]. If channel is 3, assumed to be RGB. """ assert isinstance(val, np.ndarray) arr = image_to_nhwc(val) self._dispatch(lambda m: m.process_image(name, arr)) s = create_image_summary(name, arr) self._dispatch(lambda m: m.process_summary(s))
Put an :class:`tf.Event`. `step` and `wall_time` fields of :class:`tf.Event` will be filled automatically. Args: evt (tf.Event): def put_event(self, evt): """ Put an :class:`tf.Event`. `step` and `wall_time` fields of :class:`tf.Event` will be filled automatically. Args: evt (tf.Event): """ evt.step = self.global_step evt.wall_time = time.time() self._dispatch(lambda m: m.process_event(evt))
Look for an existing json under :meth:`logger.get_logger_dir()` named "stats.json", and return the loaded list of statistics if found. Returns None otherwise. def load_existing_json(): """ Look for an existing json under :meth:`logger.get_logger_dir()` named "stats.json", and return the loaded list of statistics if found. Returns None otherwise. """ dir = logger.get_logger_dir() fname = os.path.join(dir, JSONWriter.FILENAME) if tf.gfile.Exists(fname): with open(fname) as f: stats = json.load(f) assert isinstance(stats, list), type(stats) return stats return None
Add stats to json and dump to disk. Note that this method is idempotent. def _trigger(self): """ Add stats to json and dump to disk. Note that this method is idempotent. """ if len(self._stat_now): self._stat_now['epoch_num'] = self.epoch_num self._stat_now['global_step'] = self.global_step self._stats.append(self._stat_now) self._stat_now = {} self._write_stat()
Args: img: bxhxwxc coords: bxh2xw2x2. each coordinate is (y, x) integer. Out of boundary coordinates will be clipped. Return: bxh2xw2xc image def sample(img, coords): """ Args: img: bxhxwxc coords: bxh2xw2x2. each coordinate is (y, x) integer. Out of boundary coordinates will be clipped. Return: bxh2xw2xc image """ shape = img.get_shape().as_list()[1:] # h, w, c batch = tf.shape(img)[0] shape2 = coords.get_shape().as_list()[1:3] # h2, w2 assert None not in shape2, coords.get_shape() max_coor = tf.constant([shape[0] - 1, shape[1] - 1], dtype=tf.float32) coords = tf.clip_by_value(coords, 0., max_coor) # borderMode==repeat coords = tf.cast(coords, tf.int32) batch_index = tf.range(batch, dtype=tf.int32) batch_index = tf.reshape(batch_index, [-1, 1, 1, 1]) batch_index = tf.tile(batch_index, [1, shape2[0], shape2[1], 1]) # bxh2xw2x1 indices = tf.concat([batch_index, coords], axis=3) # bxh2xw2x3 sampled = tf.gather_nd(img, indices) return sampled
Sample the images using the given coordinates, by bilinear interpolation. This was described in the paper: `Spatial Transformer Networks <http://arxiv.org/abs/1506.02025>`_. This is equivalent to `torch.nn.functional.grid_sample`, up to some non-trivial coordinate transformation. This implementation returns pixel value at pixel (1, 1) for a floating point coordinate (1.0, 1.0). Note that this may not be what you need. Args: inputs (list): [images, coords]. images has shape NHWC. coords has shape (N, H', W', 2), where each pair of the last dimension is a (y, x) real-value coordinate. borderMode: either "repeat" or "constant" (zero-filled) Returns: tf.Tensor: a tensor named ``output`` of shape (N, H', W', C). def GridSample(inputs, borderMode='repeat'): """ Sample the images using the given coordinates, by bilinear interpolation. This was described in the paper: `Spatial Transformer Networks <http://arxiv.org/abs/1506.02025>`_. This is equivalent to `torch.nn.functional.grid_sample`, up to some non-trivial coordinate transformation. This implementation returns pixel value at pixel (1, 1) for a floating point coordinate (1.0, 1.0). Note that this may not be what you need. Args: inputs (list): [images, coords]. images has shape NHWC. coords has shape (N, H', W', 2), where each pair of the last dimension is a (y, x) real-value coordinate. borderMode: either "repeat" or "constant" (zero-filled) Returns: tf.Tensor: a tensor named ``output`` of shape (N, H', W', C). """ image, mapping = inputs assert image.get_shape().ndims == 4 and mapping.get_shape().ndims == 4 input_shape = image.get_shape().as_list()[1:] assert None not in input_shape, \ "Images in GridSample layer must have fully-defined shape" assert borderMode in ['repeat', 'constant'] orig_mapping = mapping mapping = tf.maximum(mapping, 0.0) lcoor = tf.floor(mapping) ucoor = lcoor + 1 diff = mapping - lcoor neg_diff = 1.0 - diff # bxh2xw2x2 lcoory, lcoorx = tf.split(lcoor, 2, 3) ucoory, ucoorx = tf.split(ucoor, 2, 3) lyux = tf.concat([lcoory, ucoorx], 3) uylx = tf.concat([ucoory, lcoorx], 3) diffy, diffx = tf.split(diff, 2, 3) neg_diffy, neg_diffx = tf.split(neg_diff, 2, 3) ret = tf.add_n([sample(image, lcoor) * neg_diffx * neg_diffy, sample(image, ucoor) * diffx * diffy, sample(image, lyux) * neg_diffy * diffx, sample(image, uylx) * diffy * neg_diffx], name='sampled') if borderMode == 'constant': max_coor = tf.constant([input_shape[0] - 1, input_shape[1] - 1], dtype=tf.float32) mask = tf.greater_equal(orig_mapping, 0.0) mask2 = tf.less_equal(orig_mapping, max_coor) mask = tf.logical_and(mask, mask2) # bxh2xw2x2 mask = tf.reduce_all(mask, [3]) # bxh2xw2 boolean mask = tf.expand_dims(mask, 3) ret = ret * tf.cast(mask, tf.float32) return tf.identity(ret, name='output')
Enable trace for calls to any function. def enable_call_trace(): """ Enable trace for calls to any function. """ def tracer(frame, event, arg): if event == 'call': co = frame.f_code func_name = co.co_name if func_name == 'write' or func_name == 'print': # ignore write() calls from print statements return func_line_no = frame.f_lineno func_filename = co.co_filename caller = frame.f_back if caller: caller_line_no = caller.f_lineno caller_filename = caller.f_code.co_filename print('Call to `%s` on line %s:%s from %s:%s' % (func_name, func_filename, func_line_no, caller_filename, caller_line_no)) return sys.settrace(tracer)
Apply a set of default rules to make a fast :class:`InputSource`. Args: input_source_or_dataflow(InputSource | DataFlow): trainer (Trainer): Returns: InputSource def apply_default_prefetch(input_source_or_dataflow, trainer): """ Apply a set of default rules to make a fast :class:`InputSource`. Args: input_source_or_dataflow(InputSource | DataFlow): trainer (Trainer): Returns: InputSource """ if not isinstance(input_source_or_dataflow, InputSource): # to mimic same behavior of the old trainer interface if type(trainer) == SimpleTrainer: input = FeedInput(input_source_or_dataflow) else: logger.info("Automatically applying QueueInput on the DataFlow.") input = QueueInput(input_source_or_dataflow) else: input = input_source_or_dataflow if hasattr(trainer, 'devices'): towers = trainer.devices if len(towers) > 1: # seem to only improve on >1 GPUs assert not isinstance(trainer, SimpleTrainer) if isinstance(input, FeedfreeInput) and \ not isinstance(input, (StagingInput, DummyConstantInput)): logger.info("Automatically applying StagingInput on the DataFlow.") input = StagingInput(input) return input
Train with a :class:`TrainConfig` and a :class:`Trainer`, to present the simple and old training interface. It basically does the following 3 things (and you can easily do them by yourself if you need more control): 1. Setup the input with automatic prefetching heuristics, from `config.data` or `config.dataflow`. 2. Call `trainer.setup_graph` with the input as well as `config.model`. 3. Call `trainer.train` with rest of the attributes of config. See the `related tutorial <https://tensorpack.readthedocs.io/tutorial/training-interface.html#with-modeldesc-and-trainconfig>`_ to learn more. Args: config (TrainConfig): trainer (Trainer): an instance of :class:`SingleCostTrainer`. Example: .. code-block:: python launch_train_with_config( config, SyncMultiGPUTrainerParameterServer(8, ps_device='gpu')) def launch_train_with_config(config, trainer): """ Train with a :class:`TrainConfig` and a :class:`Trainer`, to present the simple and old training interface. It basically does the following 3 things (and you can easily do them by yourself if you need more control): 1. Setup the input with automatic prefetching heuristics, from `config.data` or `config.dataflow`. 2. Call `trainer.setup_graph` with the input as well as `config.model`. 3. Call `trainer.train` with rest of the attributes of config. See the `related tutorial <https://tensorpack.readthedocs.io/tutorial/training-interface.html#with-modeldesc-and-trainconfig>`_ to learn more. Args: config (TrainConfig): trainer (Trainer): an instance of :class:`SingleCostTrainer`. Example: .. code-block:: python launch_train_with_config( config, SyncMultiGPUTrainerParameterServer(8, ps_device='gpu')) """ if is_tfv2(): tfv1.disable_eager_execution() assert isinstance(trainer, SingleCostTrainer), trainer assert isinstance(config, TrainConfig), config assert config.model is not None assert config.dataflow is not None or config.data is not None model = config.model input = config.data or config.dataflow input = apply_default_prefetch(input, trainer) # This is the only place where the `ModelDesc` abstraction is useful. # We should gradually stay away from this unuseful abstraction. # TowerFuncWrapper is a better abstraction (similar to tf.defun in the future) trainer.setup_graph( model.get_input_signature(), input, model.build_graph, model.get_optimizer) _check_unused_regularization() trainer.train_with_defaults( callbacks=config.callbacks, monitors=config.monitors, session_creator=config.session_creator, session_init=config.session_init, steps_per_epoch=config.steps_per_epoch, starting_epoch=config.starting_epoch, max_epoch=config.max_epoch, extra_callbacks=config.extra_callbacks)
Delegate property to self.loop def _get_property(name): """ Delegate property to self.loop """ ret = property( lambda self: getattr(self.loop, name)) if six.PY3: # __doc__ is readonly in Py2 try: ret.__doc__ = getattr(TrainLoop, name).__doc__ except AttributeError: pass return ret
Configure the loop given the settings. def config(self, steps_per_epoch, starting_epoch, max_epoch): """ Configure the loop given the settings. """ self.starting_epoch = int(starting_epoch) self.max_epoch = int(max_epoch) self.steps_per_epoch = int(steps_per_epoch) # Allow empty epoch (no steps), if we want to run the callbacks only. assert self.steps_per_epoch >= 0 and self.max_epoch >= 0 self._epoch_num = starting_epoch - 1
Register callbacks to the trainer. It can only be called before :meth:`Trainer.train()`. Args: cb (Callback or [Callback]): a callback or a list of callbacks Returns: succeed or not def _register_callback(self, cb): """ Register callbacks to the trainer. It can only be called before :meth:`Trainer.train()`. Args: cb (Callback or [Callback]): a callback or a list of callbacks Returns: succeed or not """ if isinstance(cb, (list, tuple)): for x in cb: self._register_callback(x) return assert isinstance(cb, Callback), cb assert not isinstance(self._callbacks, Callbacks), \ "Cannot register more callbacks after trainer was setup!" if not self.is_chief and cb.chief_only: logger.warn("Callback {} is chief-only, skipped.".format(str(cb))) return False else: self._callbacks.append(cb) return True
Defines what to do in one iteration. The default is: ``self.hooked_sess.run(self.train_op)``. The behavior of each iteration can be changed by either setting ``trainer.train_op``, or overriding this method. def run_step(self): """ Defines what to do in one iteration. The default is: ``self.hooked_sess.run(self.train_op)``. The behavior of each iteration can be changed by either setting ``trainer.train_op``, or overriding this method. """ if not hasattr(self, 'train_op'): raise NotImplementedError( "Please either set `Trainer.train_op` or provide an implementation " "of Trainer.run_step()!") self.hooked_sess.run(self.train_op)
Setup callbacks and monitors. Must be called after the main graph is built. Args: callbacks ([Callback]): monitors ([MonitorBase]): def setup_callbacks(self, callbacks, monitors): """ Setup callbacks and monitors. Must be called after the main graph is built. Args: callbacks ([Callback]): monitors ([MonitorBase]): """ assert isinstance(callbacks, list), callbacks assert isinstance(monitors, list), monitors describe_trainable_vars() # TODO weird self.register_callback(MaintainStepCounter()) for cb in callbacks: self.register_callback(cb) for cb in self._callbacks: assert not isinstance(cb, MonitorBase), "Monitor cannot be pre-registered for now!" registered_monitors = [] for m in monitors: if self.register_callback(m): registered_monitors.append(m) self.monitors = Monitors(registered_monitors) self.register_callback(self.monitors) # monitors is also a callback # some final operations that might modify the graph logger.info("Setup callbacks graph ...") self._callbacks = Callbacks(self._callbacks) self._callbacks.setup_graph(weakref.proxy(self))
Create the session and set `self.sess`. Call `self.initiailize_hooks()` Finalize the graph. It must be called after callbacks are setup. Args: session_creator (tf.train.SessionCreator): session_init (sessinit.SessionInit): def initialize(self, session_creator, session_init): """ Create the session and set `self.sess`. Call `self.initiailize_hooks()` Finalize the graph. It must be called after callbacks are setup. Args: session_creator (tf.train.SessionCreator): session_init (sessinit.SessionInit): """ assert isinstance(session_creator, tfv1.train.SessionCreator), session_creator assert isinstance(session_init, SessionInit), session_init session_init._setup_graph() logger.info("Creating the session ...") self.sess = session_creator.create_session() self.initialize_hooks() if self.is_chief: logger.info("Initializing the session ...") session_init._run_init(self.sess) else: if not isinstance(session_init, JustCurrentSession): logger.warn("This is not a chief worker, 'session_init' was ignored!") self.sess.graph.finalize() logger.info("Graph Finalized.")
Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`. A new trainer may override this method to create multiple groups of hooks, which can be useful when the training is not done by a single `train_op`. def initialize_hooks(self): """ Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`. A new trainer may override this method to create multiple groups of hooks, which can be useful when the training is not done by a single `train_op`. """ hooks = self._callbacks.get_hooks() self.hooked_sess = tfv1.train.MonitoredSession( session_creator=ReuseSessionCreator(self.sess), hooks=hooks)
Run the main training loop. Args: steps_per_epoch, starting_epoch, max_epoch (int): def main_loop(self, steps_per_epoch, starting_epoch, max_epoch): """ Run the main training loop. Args: steps_per_epoch, starting_epoch, max_epoch (int): """ with self.sess.as_default(): self.loop.config(steps_per_epoch, starting_epoch, max_epoch) self.loop.update_global_step() try: self._callbacks.before_train() # refresh global step (might have changed by callbacks) TODO ugly # what if gs is changed later? self.loop.update_global_step() for self.loop._epoch_num in range( self.loop.starting_epoch, self.loop.max_epoch + 1): logger.info("Start Epoch {} ...".format(self.loop.epoch_num)) self._callbacks.before_epoch() start_time = time.time() for self.loop._local_step in range(self.loop.steps_per_epoch): if self.hooked_sess.should_stop(): return self.run_step() # implemented by subclass self._callbacks.trigger_step() self._callbacks.after_epoch() logger.info("Epoch {} (global_step {}) finished, time:{}.".format( self.loop.epoch_num, self.loop.global_step, humanize_time_delta(time.time() - start_time))) # trigger epoch outside the timing region. self._callbacks.trigger_epoch() logger.info("Training has finished!") except (StopTraining, tf.errors.OutOfRangeError) as e: logger.info("Training was stopped by exception {}.".format(str(e))) except KeyboardInterrupt: logger.info("Detected Ctrl-C and exiting main loop.") raise finally: self._callbacks.after_train() self.hooked_sess.close()
Implemented by three lines: .. code-block:: python self.setup_callbacks(callbacks, monitors) self.initialize(session_creator, session_init) self.main_loop(steps_per_epoch, starting_epoch, max_epoch) You can call those methods by yourself to have better control on details if needed. def train(self, callbacks, monitors, session_creator, session_init, steps_per_epoch, starting_epoch=1, max_epoch=9999999): """ Implemented by three lines: .. code-block:: python self.setup_callbacks(callbacks, monitors) self.initialize(session_creator, session_init) self.main_loop(steps_per_epoch, starting_epoch, max_epoch) You can call those methods by yourself to have better control on details if needed. """ self.setup_callbacks(callbacks, monitors) self.initialize(session_creator, session_init) self.main_loop(steps_per_epoch, starting_epoch, max_epoch)
Same as :meth:`train()`, except: 1. Add `extra_callbacks` to callbacks. The default value for `extra_callbacks` is :meth:`DEFAULT_CALLBACKS()`. 2. Default value for `monitors` is :meth:`DEFAULT_MONITORS()`. 3. Provide default values for every option except `steps_per_epoch`. def train_with_defaults( self, _sentinel=None, callbacks=None, monitors=None, session_creator=None, session_init=None, steps_per_epoch=None, starting_epoch=1, max_epoch=9999999, extra_callbacks=None): """ Same as :meth:`train()`, except: 1. Add `extra_callbacks` to callbacks. The default value for `extra_callbacks` is :meth:`DEFAULT_CALLBACKS()`. 2. Default value for `monitors` is :meth:`DEFAULT_MONITORS()`. 3. Provide default values for every option except `steps_per_epoch`. """ assert _sentinel is None, "Please call `train_with_defaults` with keyword arguments only!" callbacks = copy.copy(callbacks or []) monitors = DEFAULT_MONITORS() if monitors is None else monitors extra_callbacks = DEFAULT_CALLBACKS() if extra_callbacks is None else extra_callbacks callbacks.extend(extra_callbacks) assert steps_per_epoch is not None session_creator = session_creator or NewSessionCreator() session_init = session_init or JustCurrentSession() self.train(callbacks, monitors, session_creator, session_init, steps_per_epoch, starting_epoch, max_epoch)