Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def num_devices(self): c_count = c_uint() _check_return(_NVML.get_function( "nvmlDeviceGetCount_v2")(byref(c_count))) return c_count.value
[ "Get number of devices " ]
Please provide a description of the function:def device(self, idx): class GpuDevice(Structure): pass c_nvmlDevice_t = POINTER(GpuDevice) c_index = c_uint(idx) device = c_nvmlDevice_t() _check_return(_NVML.get_function( "nvmlDeviceGetHandleByIndex_v2")(c_index, byref(device))) return NvidiaDevice(device)
[ "Get a specific GPU device\n\n Args:\n idx: index of device\n\n Returns:\n NvidiaDevice: single GPU device\n " ]
Please provide a description of the function:def maybe_download_and_extract(dest_directory, cifar_classnum): assert cifar_classnum == 10 or cifar_classnum == 100 if cifar_classnum == 10: cifar_foldername = 'cifar-10-batches-py' else: cifar_foldername = 'cifar-100-python' if os.path.isdir(os.path.join(dest_directory, cifar_foldername)): logger.info("Found cifar{} data in {}.".format(cifar_classnum, dest_directory)) return else: DATA_URL = DATA_URL_CIFAR_10 if cifar_classnum == 10 else DATA_URL_CIFAR_100 filename = DATA_URL[0].split('/')[-1] filepath = os.path.join(dest_directory, filename) download(DATA_URL[0], dest_directory, expect_size=DATA_URL[1]) tarfile.open(filepath, 'r:gz').extractall(dest_directory)
[ "Download and extract the tarball from Alex's website. Copied from tensorflow example " ]
Please provide a description of the function:def get_per_pixel_mean(self, names=('train', 'test')): for name in names: assert name in ['train', 'test'], name train_files, test_files, _ = get_filenames(self.dir, self.cifar_classnum) all_files = [] if 'train' in names: all_files.extend(train_files) if 'test' in names: all_files.extend(test_files) all_imgs = [x[0] for x in read_cifar(all_files, self.cifar_classnum)] arr = np.array(all_imgs, dtype='float32') mean = np.mean(arr, axis=0) return mean
[ "\n Args:\n names (tuple[str]): the names ('train' or 'test') of the datasets\n\n Returns:\n a mean image of all images in the given datasets, with size 32x32x3\n " ]
Please provide a description of the function:def get_per_channel_mean(self, names=('train', 'test')): mean = self.get_per_pixel_mean(names) return np.mean(mean, axis=(0, 1))
[ "\n Args:\n names (tuple[str]): the names ('train' or 'test') of the datasets\n\n Returns:\n An array of three values as mean of each channel, for all images in the given datasets.\n " ]
Please provide a description of the function:def maskrcnn_loss(mask_logits, fg_labels, fg_target_masks): num_fg = tf.size(fg_labels, out_type=tf.int64) indices = tf.stack([tf.range(num_fg), fg_labels - 1], axis=1) # #fgx2 mask_logits = tf.gather_nd(mask_logits, indices) # #fgxhxw mask_probs = tf.sigmoid(mask_logits) # add some training visualizations to tensorboard with tf.name_scope('mask_viz'): viz = tf.concat([fg_target_masks, mask_probs], axis=1) viz = tf.expand_dims(viz, 3) viz = tf.cast(viz * 255, tf.uint8, name='viz') tf.summary.image('mask_truth|pred', viz, max_outputs=10) loss = tf.nn.sigmoid_cross_entropy_with_logits( labels=fg_target_masks, logits=mask_logits) loss = tf.reduce_mean(loss, name='maskrcnn_loss') pred_label = mask_probs > 0.5 truth_label = fg_target_masks > 0.5 accuracy = tf.reduce_mean( tf.cast(tf.equal(pred_label, truth_label), tf.float32), name='accuracy') pos_accuracy = tf.logical_and( tf.equal(pred_label, truth_label), tf.equal(truth_label, True)) pos_accuracy = tf.reduce_mean(tf.cast(pos_accuracy, tf.float32), name='pos_accuracy') fg_pixel_ratio = tf.reduce_mean(tf.cast(truth_label, tf.float32), name='fg_pixel_ratio') add_moving_summary(loss, accuracy, fg_pixel_ratio, pos_accuracy) return loss
[ "\n Args:\n mask_logits: #fg x #category xhxw\n fg_labels: #fg, in 1~#class, int64\n fg_target_masks: #fgxhxw, float32\n " ]
Please provide a description of the function:def maskrcnn_upXconv_head(feature, num_category, num_convs, norm=None): assert norm in [None, 'GN'], norm l = feature with argscope([Conv2D, Conv2DTranspose], data_format='channels_first', kernel_initializer=tf.variance_scaling_initializer( scale=2.0, mode='fan_out', distribution='untruncated_normal' if get_tf_version_tuple() >= (1, 12) else 'normal')): # c2's MSRAFill is fan_out for k in range(num_convs): l = Conv2D('fcn{}'.format(k), l, cfg.MRCNN.HEAD_DIM, 3, activation=tf.nn.relu) if norm is not None: l = GroupNorm('gn{}'.format(k), l) l = Conv2DTranspose('deconv', l, cfg.MRCNN.HEAD_DIM, 2, strides=2, activation=tf.nn.relu) l = Conv2D('conv', l, num_category, 1) return l
[ "\n Args:\n feature (NxCx s x s): size is 7 in C4 models and 14 in FPN models.\n num_category(int):\n num_convs (int): number of convolution layers\n norm (str or None): either None or 'GN'\n\n Returns:\n mask_logits (N x num_category x 2s x 2s):\n " ]
Please provide a description of the function:def get_per_pixel_mean(names=('train', 'test', 'extra')): for name in names: assert name in ['train', 'test', 'extra'], name images = [SVHNDigit(x).X for x in names] return np.concatenate(tuple(images)).mean(axis=0)
[ "\n Args:\n names (tuple[str]): names of the dataset split\n\n Returns:\n a 32x32x3 image, the mean of all images in the given datasets\n " ]
Please provide a description of the function:def build_or_reuse_placeholder(tensor_spec): g = tfv1.get_default_graph() name = tensor_spec.name try: tensor = g.get_tensor_by_name(name + ':0') assert "Placeholder" in tensor.op.type, "Tensor {} exists but is not a placeholder!".format(name) assert tensor_spec.is_compatible_with(tensor), \ "Tensor {} exists but is not compatible with the signature!".format(tensor) return tensor except KeyError: with tfv1.name_scope(None): # clear any name scope it might get called in ret = tfv1.placeholder( tensor_spec.dtype, shape=tensor_spec.shape, name=tensor_spec.name) return ret
[ "\n Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one.\n\n Args:\n tensor_spec (tf.TensorSpec):\n\n Returns:\n tf.Tensor:\n " ]
Please provide a description of the function:def get_input_signature(self): with tf.Graph().as_default() as G: # create these placeholder in a temporary graph inputs = self.inputs() if isinstance(inputs[0], tf.Tensor): for p in inputs: assert "Placeholder" in p.op.type, \ "inputs() have to return TensorSpec or placeholders! Found {} instead.".format(p) assert p.graph == G, "Placeholders returned by inputs() should be created inside inputs()!" return [TensorSpec(shape=p.shape, dtype=p.dtype, name=get_op_tensor_name(p.name)[0]) for p in inputs]
[ "\n Returns:\n A list of :class:`tf.TensorSpec`, which describes the inputs of this model.\n The result is cached for each instance of :class:`ModelDescBase`.\n " ]
Please provide a description of the function:def dependency_of_targets(targets, op): # TODO tensorarray? sparsetensor? if isinstance(op, tf.Tensor): op = op.op assert isinstance(op, tf.Operation), op from tensorflow.contrib.graph_editor import get_backward_walk_ops # alternative implementation can use graph_util.extract_sub_graph dependent_ops = get_backward_walk_ops(targets, control_inputs=True) return op in dependent_ops
[ "\n Check that op is in the subgraph induced by the dependencies of targets.\n The result is memoized.\n\n This is useful if some SessionRunHooks should be run only together with certain ops.\n\n Args:\n targets: a tuple of ops or tensors. The targets to find dependencies of.\n op (tf.Operation or tf.Tensor):\n\n Returns:\n bool: True if any one of `targets` depend on `op`.\n " ]
Please provide a description of the function:def dependency_of_fetches(fetches, op): try: from tensorflow.python.client.session import _FetchHandler as FetchHandler # use the graph of the op, so that this function can be called without being under a default graph handler = FetchHandler(op.graph, fetches, {}) targets = tuple(handler.fetches() + handler.targets()) except ImportError: if isinstance(fetches, list): targets = tuple(fetches) elif isinstance(fetches, dict): raise ValueError("Don't know how to parse dictionary to fetch list! " "This is a bug of tensorpack.") else: targets = (fetches, ) return dependency_of_targets(targets, op)
[ "\n Check that op is in the subgraph induced by the dependencies of fetches.\n fetches may have more general structure.\n\n Args:\n fetches: An argument to `sess.run`. Nested structure will affect performance.\n op (tf.Operation or tf.Tensor):\n\n Returns:\n bool: True if any of `fetches` depend on `op`.\n " ]
Please provide a description of the function:def create_scalar_summary(name, v): assert isinstance(name, six.string_types), type(name) v = float(v) s = tf.Summary() s.value.add(tag=name, simple_value=v) return s
[ "\n Args:\n name (str):\n v (float): scalar value\n Returns:\n tf.Summary: a tf.Summary object with name and simple scalar value v.\n " ]
Please provide a description of the function:def create_image_summary(name, val): assert isinstance(name, six.string_types), type(name) n, h, w, c = val.shape val = val.astype('uint8') s = tf.Summary() imparams = [cv2.IMWRITE_PNG_COMPRESSION, 9] for k in range(n): arr = val[k] # CV2 will only write correctly in BGR chanel order if c == 3: arr = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR) elif c == 4: arr = cv2.cvtColor(arr, cv2.COLOR_RGBA2BGRA) tag = name if n == 1 else '{}/{}'.format(name, k) retval, img_str = cv2.imencode('.png', arr, imparams) if not retval: # Encoding has failed. continue img_str = img_str.tostring() img = tf.Summary.Image() img.height = h img.width = w # 1 - grayscale 3 - RGB 4 - RGBA img.colorspace = c img.encoded_image_string = img_str s.value.add(tag=tag, image=img) return s
[ "\n Args:\n name(str):\n val(np.ndarray): 4D tensor of NHWC. assume RGB if C==3.\n Can be either float or uint8. Range has to be [0,255].\n\n Returns:\n tf.Summary:\n " ]
Please provide a description of the function:def add_tensor_summary(x, types, name=None, collections=None, main_tower_only=True): types = set(types) if name is None: name = x.op.name ctx = get_current_tower_context() if main_tower_only and ctx is not None and not ctx.is_main_training_tower: return SUMMARY_TYPES_DIC = { 'scalar': lambda: tf.summary.scalar(name + '-summary', x, collections=collections), 'histogram': lambda: tf.summary.histogram(name + '-histogram', x, collections=collections), 'sparsity': lambda: tf.summary.scalar( name + '-sparsity', tf.nn.zero_fraction(x), collections=collections), 'mean': lambda: tf.summary.scalar( name + '-mean', tf.reduce_mean(x), collections=collections), 'rms': lambda: tf.summary.scalar( name + '-rms', rms(x), collections=collections) } for typ in types: SUMMARY_TYPES_DIC[typ]()
[ "\n Summarize a tensor by different methods.\n\n Args:\n x (tf.Tensor): a tensor to summarize\n types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms\n name (str): summary name. Defaults to be the op name.\n collections (list[str]): collections of the summary ops.\n main_tower_only (bool): Only run under main training tower. If\n set to True, calling this function under other TowerContext\n has no effect.\n\n Example:\n\n .. code-block:: python\n\n with tf.name_scope('mysummaries'): # to not mess up tensorboard\n add_tensor_summary(\n tensor, ['histogram', 'rms', 'sparsity'], name='mytensor')\n " ]
Please provide a description of the function:def add_activation_summary(x, types=None, name=None, collections=None): ndim = x.get_shape().ndims if ndim < 2: logger.warn("Cannot summarize scalar activation {}".format(x.name)) return if types is None: types = ['sparsity', 'rms', 'histogram'] with cached_name_scope('activation-summary'): add_tensor_summary(x, types, name=name, collections=collections)
[ "\n Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope.\n This function is a no-op if not calling from main training tower.\n\n Args:\n x (tf.Tensor): the tensor to summary.\n types (list[str]): summary types, defaults to ``['sparsity', 'rms', 'histogram']``.\n name (str): if is None, use x.name.\n collections (list[str]): collections of the summary ops.\n " ]
Please provide a description of the function:def add_param_summary(*summary_lists, **kwargs): collections = kwargs.pop('collections', None) assert len(kwargs) == 0, "Unknown kwargs: " + str(kwargs) ctx = get_current_tower_context() if ctx is not None and not ctx.is_main_training_tower: return params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) with cached_name_scope('param-summary'): for p in params: name = p.op.name for rgx, actions in summary_lists: if not rgx.endswith('$'): rgx = rgx + '$' if re.match(rgx, name): add_tensor_summary(p, actions, name=name, collections=collections)
[ "\n Add summary ops for all trainable variables matching the regex, under a\n reused 'param-summary' name scope.\n This function is a no-op if not calling from main training tower.\n\n Args:\n summary_lists (list): each is (regex, [list of summary type]).\n Summary type is defined in :func:`add_tensor_summary`.\n collections (list[str]): collections of the summary ops.\n\n Example:\n\n .. code-block:: python\n\n add_param_summary(\n ('.*/W', ['histogram', 'rms']),\n ('.*/gamma', ['scalar']),\n )\n " ]
Please provide a description of the function:def add_moving_summary(*args, **kwargs): decay = kwargs.pop('decay', 0.95) coll = kwargs.pop('collection', MOVING_SUMMARY_OPS_KEY) summ_coll = kwargs.pop('summary_collections', None) assert len(kwargs) == 0, "Unknown arguments: " + str(kwargs) ctx = get_current_tower_context() # allow ctx to be none if ctx is not None and not ctx.is_main_training_tower: return [] graph = tf.get_default_graph() try: control_flow_ctx = graph._get_control_flow_context() # XLA does not support summaries anyway # However, this function will generate unnecessary dependency edges, # which makes the tower function harder to compile under XLA, so we skip it if control_flow_ctx is not None and control_flow_ctx.IsXLAContext(): return except Exception: pass if tf.get_variable_scope().reuse is True: logger.warn("add_moving_summary() called under reuse=True scope, ignored.") return [] for x in args: assert isinstance(x, (tf.Tensor, tf.Variable)), x assert x.get_shape().ndims == 0, \ "add_moving_summary() only accepts scalar tensor! Got one with {}".format(x.get_shape()) ema_ops = [] for c in args: name = re.sub('tower[0-9]+/', '', c.op.name) with tf.name_scope(None): if not c.dtype.is_floating: c = tf.cast(c, tf.float32) # assign_moving_average creates variables with op names, therefore clear ns first. with _enter_vs_reuse_ns('EMA') as vs: ema_var = tf.get_variable(name, shape=c.shape, dtype=c.dtype, initializer=tf.constant_initializer(), trainable=False) ns = vs.original_name_scope with tf.name_scope(ns): # reuse VS&NS so that EMA_1 won't appear ema_op = moving_averages.assign_moving_average( ema_var, c, decay, zero_debias=True, name=name + '_EMA_apply') ema_ops.append(ema_op) with tf.name_scope(None): tf.summary.scalar( name + '-summary', ema_op, collections=summ_coll) # write the EMA value as a summary if coll is not None: for op in ema_ops: tf.add_to_collection(coll, op) return ema_ops
[ "\n Summarize the moving average for scalar tensors.\n This function is a no-op if not calling from main training tower.\n\n Args:\n args: scalar tensors to summarize\n decay (float): the decay rate. Defaults to 0.95.\n collection (str or None): the name of the collection to add EMA-maintaining ops.\n The default will work together with the default\n :class:`MovingAverageSummary` callback.\n summary_collections ([str]): the names of collections to add the\n summary op. Default is TF's default (`tf.GraphKeys.SUMMARIES`).\n\n Returns:\n [tf.Tensor]: list of tensors returned by assign_moving_average,\n which can be used to maintain the EMA.\n " ]
Please provide a description of the function:def run_head(self, proposals, stage): reg_weights = tf.constant(cfg.CASCADE.BBOX_REG_WEIGHTS[stage], dtype=tf.float32) pooled_feature = self.roi_func(proposals.boxes) # N,C,S,S pooled_feature = self.scale_gradient(pooled_feature) head_feature = self.fastrcnn_head_func('head', pooled_feature) label_logits, box_logits = fastrcnn_outputs( 'outputs', head_feature, self.num_classes, class_agnostic_regression=True) head = FastRCNNHead(proposals, box_logits, label_logits, self.gt_boxes, reg_weights) refined_boxes = head.decoded_output_boxes_class_agnostic() refined_boxes = clip_boxes(refined_boxes, self.image_shape2d) return head, tf.stop_gradient(refined_boxes, name='output_boxes')
[ "\n Args:\n proposals: BoxProposals\n stage: 0, 1, 2\n\n Returns:\n FastRCNNHead\n Nx4, updated boxes\n " ]
Please provide a description of the function:def match_box_with_gt(self, boxes, iou_threshold): if self.is_training: with tf.name_scope('match_box_with_gt_{}'.format(iou_threshold)): iou = pairwise_iou(boxes, self.gt_boxes) # NxM max_iou_per_box = tf.reduce_max(iou, axis=1) # N best_iou_ind = tf.argmax(iou, axis=1) # N labels_per_box = tf.gather(self.gt_labels, best_iou_ind) fg_mask = max_iou_per_box >= iou_threshold fg_inds_wrt_gt = tf.boolean_mask(best_iou_ind, fg_mask) labels_per_box = tf.stop_gradient(labels_per_box * tf.cast(fg_mask, tf.int64)) return BoxProposals(boxes, labels_per_box, fg_inds_wrt_gt) else: return BoxProposals(boxes)
[ "\n Args:\n boxes: Nx4\n Returns:\n BoxProposals\n " ]
Please provide a description of the function:def decoded_output_boxes(self): ret = self._cascade_boxes[-1] ret = tf.expand_dims(ret, 1) # class-agnostic return tf.tile(ret, [1, self.num_classes, 1])
[ "\n Returns:\n Nx#classx4\n " ]
Please provide a description of the function:def output_scores(self, name=None): scores = [head.output_scores('cascade_scores_stage{}'.format(idx + 1)) for idx, head in enumerate(self._heads)] return tf.multiply(tf.add_n(scores), (1.0 / self.num_cascade_stages), name=name)
[ "\n Returns:\n Nx#class\n " ]
Please provide a description of the function:def do_visualize(model, model_path, nr_visualize=100, output_dir='output'): df = get_train_dataflow() # we don't visualize mask stuff df.reset_state() pred = OfflinePredictor(PredictConfig( model=model, session_init=get_model_loader(model_path), input_names=['image', 'gt_boxes', 'gt_labels'], output_names=[ 'generate_{}_proposals/boxes'.format('fpn' if cfg.MODE_FPN else 'rpn'), 'generate_{}_proposals/scores'.format('fpn' if cfg.MODE_FPN else 'rpn'), 'fastrcnn_all_scores', 'output/boxes', 'output/scores', 'output/labels', ])) if os.path.isdir(output_dir): shutil.rmtree(output_dir) utils.fs.mkdir_p(output_dir) with tqdm.tqdm(total=nr_visualize) as pbar: for idx, dp in itertools.islice(enumerate(df), nr_visualize): img, gt_boxes, gt_labels = dp['image'], dp['gt_boxes'], dp['gt_labels'] rpn_boxes, rpn_scores, all_scores, \ final_boxes, final_scores, final_labels = pred(img, gt_boxes, gt_labels) # draw groundtruth boxes gt_viz = draw_annotation(img, gt_boxes, gt_labels) # draw best proposals for each groundtruth, to show recall proposal_viz, good_proposals_ind = draw_proposal_recall(img, rpn_boxes, rpn_scores, gt_boxes) # draw the scores for the above proposals score_viz = draw_predictions(img, rpn_boxes[good_proposals_ind], all_scores[good_proposals_ind]) results = [DetectionResult(*args) for args in zip(final_boxes, final_scores, final_labels, [None] * len(final_labels))] final_viz = draw_final_outputs(img, results) viz = tpviz.stack_patches([ gt_viz, proposal_viz, score_viz, final_viz], 2, 2) if os.environ.get('DISPLAY', None): tpviz.interactive_imshow(viz) cv2.imwrite("{}/{:03d}.png".format(output_dir, idx), viz) pbar.update()
[ "\n Visualize some intermediate results (proposals, raw predictions) inside the pipeline.\n " ]
Please provide a description of the function:def get_registered_layer(name): ret = _LAYER_REGISTRY.get(name, None) if ret == _NameConflict: raise KeyError("Layer named '{}' is registered with `@layer_register` more than once!".format(name)) return ret
[ "\n Args:\n name (str): the name of the layer, e.g. 'Conv2D'\n Returns:\n the wrapped layer function, or None if not registered.\n " ]
Please provide a description of the function:def layer_register( log_shape=False, use_scope=True): def wrapper(func): @wraps(func) def wrapped_func(*args, **kwargs): assert args[0] is not None, args if use_scope: name, inputs = args[0], args[1] args = args[1:] # actual positional args used to call func assert isinstance(name, six.string_types), "First argument for \"{}\" should be a string. ".format( func.__name__) + "Did you forget to specify the name of the layer?" else: assert not log_shape if isinstance(args[0], six.string_types): if use_scope is False: logger.warn( "Please call layer {} without the first scope name argument, " "or register the layer with use_scope=None to allow " "two calling methods.".format(func.__name__)) name, inputs = args[0], args[1] args = args[1:] # actual positional args used to call func else: inputs = args[0] name = None if not (isinstance(inputs, (tf.Tensor, tf.Variable)) or (isinstance(inputs, (list, tuple)) and isinstance(inputs[0], (tf.Tensor, tf.Variable)))): raise ValueError("Invalid inputs to layer: " + str(inputs)) # use kwargs from current argument scope actual_args = copy.copy(get_arg_scope()[func.__name__]) # explicit kwargs overwrite argscope actual_args.update(kwargs) # if six.PY3: # # explicit positional args also override argscope. only work in PY3 # posargmap = inspect.signature(func).bind_partial(*args).arguments # for k in six.iterkeys(posargmap): # if k in actual_args: # del actual_args[k] if name is not None: # use scope with tfv1.variable_scope(name) as scope: # this name is only used to surpress logging, doesn't hurt to do some heuristics scope_name = re.sub('tower[0-9]+/', '', scope.name) do_log_shape = log_shape and scope_name not in _LAYER_LOGGED if do_log_shape: logger.info("{} input: {}".format(scope.name, get_shape_str(inputs))) # run the actual function outputs = func(*args, **actual_args) if do_log_shape: # log shape info and add activation logger.info("{} output: {}".format( scope.name, get_shape_str(outputs))) _LAYER_LOGGED.add(scope_name) else: # run the actual function outputs = func(*args, **actual_args) return outputs wrapped_func.symbolic_function = func # attribute to access the underlying function object wrapped_func.use_scope = use_scope _register(func.__name__, wrapped_func) return wrapped_func return wrapper
[ "\n Args:\n log_shape (bool): log input/output shape of this layer\n use_scope (bool or None):\n Whether to call this layer with an extra first argument as variable scope.\n When set to None, it can be called either with or without\n the scope name argument, depend on whether the first argument\n is string or not.\n\n Returns:\n A decorator used to register a layer.\n\n Example:\n\n .. code-block:: python\n\n @layer_register(use_scope=True)\n def add10(x):\n return x + tf.get_variable('W', shape=[10])\n\n # use it:\n output = add10('layer_name', input) # the function will be called under variable scope \"layer_name\".\n " ]
Please provide a description of the function:def get_predictor(self, input_names, output_names, device=0): assert self.tower_func is not None, "Must set tower_func on the trainer to use get_predictor()!" tower_name = 'tower-pred-{}'.format(device) if device >= 0 else 'tower-pred-cpu' device_id = device device = '/gpu:{}'.format(device_id) if device_id >= 0 else '/cpu:0' try: tower = self.tower_func.towers[tower_name] assert tower is not None, "This is a bug!" except KeyError: tower = None if tower is None: input = PlaceholderInput() input.setup(self.input_signature) vs_name = self._vs_name_for_predictor(device_id) with tfv1.variable_scope(tfv1.get_variable_scope(), reuse=True), \ tf.device(device), PredictTowerContext( tower_name, vs_name=vs_name): logger.info("Building graph for predict tower '{}' on device {} {}...".format( tower_name, device, "with variable scope '{}'".format(vs_name) if vs_name else '')) self.tower_func(*input.get_input_tensors()) tower = self.tower_func.towers[tower_name] input_tensors = tower.get_tensors(input_names) output_tensors = tower.get_tensors(output_names) predictor = OnlinePredictor(input_tensors, output_tensors) self._predictors.append(predictor) return predictor
[ "\n This method will build the trainer's tower function under ``TowerContext(is_training=False)``,\n and returns a callable predictor with input placeholders & output tensors in this tower.\n\n This method handles the common case of inference with the same tower function.\n If you want to do inference with a different tower function, you can always build the tower by yourself,\n under a \"reuse\" variable scope and a `TowerContext(is_training=False)`.\n\n Args:\n input_names (list): list of input names, matching the inputs declared for the trainer.\n output_names(list): list of tensor names without the tower prefix.\n device (int): build the predictor on device '/gpu:{device}' or use -1 for '/cpu:0'.\n\n Returns:\n an :class:`OnlinePredictor`.\n\n Example:\n\n .. code-block:: none\n\n # in the graph:\n interesting_tensor = tf.identity(x, name='fun')\n # in _setup_graph callback method:\n self._predictor = self.trainer.get_predictor(['input1', 'input2'], ['fun'])\n # After session is initialized (see Tutorials - Write a Callback), can use it by:\n outputs = self._predictor(input1, input2)\n\n The CycleGAN example and DQN example have more concrete use of this method.\n " ]
Please provide a description of the function:def export_serving(model_path): pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['prediction_img_bytes']) ModelExporter(pred_config).export_serving('/tmp/exported')
[ "Export trained model to use it in TensorFlow Serving or cloudML. " ]
Please provide a description of the function:def export_compact(model_path): pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_img']) ModelExporter(pred_config).export_compact('/tmp/compact_graph.pb')
[ "Export trained model to use it as a frozen and pruned inference graph in\n mobile applications. " ]
Please provide a description of the function:def apply(model_path): pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_img']) pred = OfflinePredictor(pred_config) img = cv2.imread('lena.png') prediction = pred([img])[0] cv2.imwrite('applied_default.jpg', prediction[0])
[ "Run inference from a training model checkpoint. " ]
Please provide a description of the function:def apply_inference_graph(model_path): pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['prediction_img_bytes']) pred = OfflinePredictor(pred_config) buf = open('lena.png', 'rb').read() prediction = pred([buf])[0] with open('applied_inference_graph.png', 'wb') as f: f.write(prediction[0])
[ "Run inference from a different graph, which receives encoded images buffers. " ]
Please provide a description of the function:def apply_compact(graph_path): with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: # Note, we just load the graph and do *not* need to initialize anything. with tf.gfile.GFile(graph_path, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def) input_img = sess.graph.get_tensor_by_name('import/input_img:0') prediction_img = sess.graph.get_tensor_by_name('import/prediction_img:0') prediction = sess.run(prediction_img, {input_img: cv2.imread('lena.png')[None, ...]}) cv2.imwrite('applied_compact.png', prediction[0])
[ "Run the pruned and frozen inference graph. " ]
Please provide a description of the function:def BatchNorm(inputs, training=None, momentum=0.9, epsilon=1e-5, center=True, scale=True, gamma_initializer=tf.ones_initializer(), data_format='channels_last', internal_update=False): data_format = get_data_format(data_format, keras_mode=False) shape = inputs.get_shape().as_list() ndims = len(shape) assert ndims in [2, 4] if ndims == 2: data_format = 'NHWC' if data_format == 'NCHW': n_out = shape[1] else: n_out = shape[-1] # channel assert n_out is not None, "Input to BatchNorm cannot have unknown channels!" beta, gamma, moving_mean, moving_var = get_bn_variables(n_out, scale, center, gamma_initializer) ctx = get_current_tower_context() use_local_stat = training if use_local_stat is None: use_local_stat = ctx.is_training use_local_stat = bool(use_local_stat) if use_local_stat: if ndims == 2: inputs = tf.reshape(inputs, [-1, 1, 1, n_out]) # fused_bn only takes 4D input # fused_bn has error using NCHW? (see #190) xn, batch_mean, batch_var = tf.nn.fused_batch_norm( inputs, gamma, beta, epsilon=epsilon, is_training=True, data_format=data_format) if ndims == 2: xn = tf.squeeze(xn, [1, 2]) else: if ctx.is_training: assert get_tf_version_tuple() >= (1, 4), \ "Fine tuning a BatchNorm model with fixed statistics is only " \ "supported after https://github.com/tensorflow/tensorflow/pull/12580 " if ctx.is_main_training_tower: # only warn in first tower logger.warn("[BatchNorm] Using moving_mean/moving_variance in training.") # Using moving_mean/moving_variance in training, which means we # loaded a pre-trained BN and only fine-tuning the affine part. xn, _, _ = tf.nn.fused_batch_norm( inputs, gamma, beta, mean=moving_mean, variance=moving_var, epsilon=epsilon, data_format=data_format, is_training=False) else: if ndims == 4: xn, _, _ = tf.nn.fused_batch_norm( inputs, gamma, beta, mean=moving_mean, variance=moving_var, epsilon=epsilon, data_format=data_format, is_training=False) else: xn = tf.nn.batch_normalization( inputs, moving_mean, moving_var, beta, gamma, epsilon) # maintain EMA only on one GPU is OK, even in replicated mode. # because training time doesn't use EMA if ctx.is_main_training_tower: add_model_variable(moving_mean) add_model_variable(moving_var) if ctx.is_main_training_tower and use_local_stat: ret = update_bn_ema(xn, batch_mean, batch_var, moving_mean, moving_var, momentum, internal_update) else: ret = tf.identity(xn, name='output') vh = ret.variables = VariableHolder(mean=moving_mean, variance=moving_var) if scale: vh.gamma = gamma if center: vh.beta = beta return ret
[ "\n Mostly equivalent to `tf.layers.batch_normalization`, but difference in\n the following:\n 1. Accepts `data_format` rather than `axis`. For 2D input, this argument will be ignored.\n 2. Default value for `momentum` and `epsilon` is different.\n 3. Default value for `training` is automatically obtained from `TowerContext`.\n 4. Support the `internal_update` option.\n Args:\n internal_update (bool): if False, add EMA update ops to\n `tf.GraphKeys.UPDATE_OPS`. If True, update EMA inside the layer\n by control dependencies.\n Variable Names:\n * ``beta``: the bias term. Will be zero-inited by default.\n * ``gamma``: the scale term. Will be one-inited by default. Input will be transformed by ``x * gamma + beta``.\n * ``mean/EMA``: the moving average of mean.\n * ``variance/EMA``: the moving average of variance.\n Note:\n 1. About multi-GPU training: moving averages across GPUs are not aggregated.\n Batch statistics are computed independently. This is consistent with most frameworks.\n 2. Combinations of ``training`` and ``ctx.is_training``:\n * ``training == ctx.is_training``: standard BN, EMA are\n maintained during training and used during inference. This is\n the default.\n * ``training and not ctx.is_training``: still use batch statistics in inference.\n * ``not training and ctx.is_training``: use EMA to normalize in\n training. This is useful when you load a pre-trained BN and\n don't want to fine tune the EMA. EMA will not be updated in\n this case.\n " ]
Please provide a description of the function:def SelectComponent(ds, idxs): return MapData(ds, lambda dp: [dp[i] for i in idxs])
[ "\n Select / reorder components from datapoints.\n\n Args:\n ds (DataFlow): input DataFlow.\n idxs (list[int]): a list of component indices.\n\n Example:\n\n .. code-block:: none\n\n original df produces: [c1, c2, c3]\n idxs: [2,1]\n this df: [c3, c2]\n " ]
Please provide a description of the function:def _analyze_input_data(self, entry, k, depth=1, max_depth=3, max_list=3): class _elementInfo(object): def __init__(self, el, pos, depth=0, max_list=3): self.shape = "" self.type = type(el).__name__ self.dtype = "" self.range = "" self.sub_elements = [] self.ident = " " * (depth * 2) self.pos = pos numpy_scalar_types = list(itertools.chain(*np.sctypes.values())) if isinstance(el, (int, float, bool)): self.range = " with value {}".format(el) elif type(el) is np.ndarray: self.shape = " of shape {}".format(el.shape) self.dtype = ":{}".format(str(el.dtype)) self.range = " in range [{}, {}]".format(el.min(), el.max()) elif type(el) in numpy_scalar_types: self.range = " with value {}".format(el) elif isinstance(el, (list)): self.shape = " of len {}".format(len(el)) if depth < max_depth: for k, subel in enumerate(el): if k < max_list: self.sub_elements.append(_elementInfo(subel, k, depth + 1, max_list)) else: self.sub_elements.append(" " * ((depth + 1) * 2) + '...') break else: if len(el) > 0: self.sub_elements.append(" " * ((depth + 1) * 2) + ' ...') def __str__(self): strings = [] vals = (self.ident, self.pos, self.type, self.dtype, self.shape, self.range) strings.append("{}{}: {}{}{}{}".format(*vals)) for k, el in enumerate(self.sub_elements): strings.append(str(el)) return "\n".join(strings) return str(_elementInfo(entry, k, depth, max_list))
[ "\n Gather useful debug information from a datapoint.\n\n Args:\n entry: the datapoint component\n k (int): index of this component in current datapoint\n depth (int, optional): recursion depth\n max_depth, max_list: same as in :meth:`__init__`.\n\n Returns:\n string: debug message\n " ]
Please provide a description of the function:def feed(self, count, total=1): self._tot += total self._cnt += count
[ "\n Args:\n cnt(int): the count of some event of interest.\n tot(int): the total number of events.\n " ]
Please provide a description of the function:def feed(self, pred, label): assert pred.shape == label.shape, "{} != {}".format(pred.shape, label.shape) self.nr_pos += (label == 1).sum() self.nr_neg += (label == 0).sum() self.nr_pred_pos += (pred == 1).sum() self.nr_pred_neg += (pred == 0).sum() self.corr_pos += ((pred == 1) & (pred == label)).sum() self.corr_neg += ((pred == 0) & (pred == label)).sum()
[ "\n Args:\n pred (np.ndarray): binary array.\n label (np.ndarray): binary array of the same size.\n " ]
Please provide a description of the function:def apply_grad_processors(opt, gradprocs): assert isinstance(gradprocs, (list, tuple)), gradprocs for gp in gradprocs: assert isinstance(gp, GradientProcessor), gp class _ApplyGradientProcessor(ProxyOptimizer): def __init__(self, opt, gradprocs): self._gradprocs = gradprocs[:] super(_ApplyGradientProcessor, self).__init__(opt) def apply_gradients(self, grads_and_vars, global_step=None, name=None): g = self._apply(grads_and_vars) return self._opt.apply_gradients(g, global_step, name) def _apply(self, g): for proc in self._gradprocs: g = proc.process(g) return g return _ApplyGradientProcessor(opt, gradprocs)
[ "\n Wrapper around optimizers to apply gradient processors.\n\n Args:\n opt (tf.train.Optimizer):\n gradprocs (list[GradientProcessor]): gradient processors to add to the\n optimizer.\n\n Returns:\n a :class:`tf.train.Optimizer` instance which runs the gradient\n processors before updating the variables.\n " ]
Please provide a description of the function:def _paste_mask(box, mask, shape): # int() is floor # box fpcoor=0.0 -> intcoor=0.0 x0, y0 = list(map(int, box[:2] + 0.5)) # box fpcoor=h -> intcoor=h-1, inclusive x1, y1 = list(map(int, box[2:] - 0.5)) # inclusive x1 = max(x0, x1) # require at least 1x1 y1 = max(y0, y1) w = x1 + 1 - x0 h = y1 + 1 - y0 # rounding errors could happen here, because masks were not originally computed for this shape. # but it's hard to do better, because the network does not know the "original" scale mask = (cv2.resize(mask, (w, h)) > 0.5).astype('uint8') ret = np.zeros(shape, dtype='uint8') ret[y0:y1 + 1, x0:x1 + 1] = mask return ret
[ "\n Args:\n box: 4 float\n mask: MxM floats\n shape: h,w\n Returns:\n A uint8 binary image of hxw.\n " ]
Please provide a description of the function:def predict_image(img, model_func): orig_shape = img.shape[:2] resizer = CustomResize(cfg.PREPROC.TEST_SHORT_EDGE_SIZE, cfg.PREPROC.MAX_SIZE) resized_img = resizer.augment(img) scale = np.sqrt(resized_img.shape[0] * 1.0 / img.shape[0] * resized_img.shape[1] / img.shape[1]) boxes, probs, labels, *masks = model_func(resized_img) boxes = boxes / scale # boxes are already clipped inside the graph, but after the floating point scaling, this may not be true any more. boxes = clip_boxes(boxes, orig_shape) if masks: # has mask full_masks = [_paste_mask(box, mask, orig_shape) for box, mask in zip(boxes, masks[0])] masks = full_masks else: # fill with none masks = [None] * len(boxes) results = [DetectionResult(*args) for args in zip(boxes, probs, labels.tolist(), masks)] return results
[ "\n Run detection on one image, using the TF callable.\n This function should handle the preprocessing internally.\n\n Args:\n img: an image\n model_func: a callable from the TF model.\n It takes image and returns (boxes, probs, labels, [masks])\n\n Returns:\n [DetectionResult]\n " ]
Please provide a description of the function:def predict_dataflow(df, model_func, tqdm_bar=None): df.reset_state() all_results = [] with ExitStack() as stack: # tqdm is not quite thread-safe: https://github.com/tqdm/tqdm/issues/323 if tqdm_bar is None: tqdm_bar = stack.enter_context(get_tqdm(total=df.size())) for img, img_id in df: results = predict_image(img, model_func) for r in results: # int()/float() to make it json-serializable res = { 'image_id': img_id, 'category_id': int(r.class_id), 'bbox': [round(float(x), 4) for x in r.box], 'score': round(float(r.score), 4), } # also append segmentation to results if r.mask is not None: rle = cocomask.encode( np.array(r.mask[:, :, None], order='F'))[0] rle['counts'] = rle['counts'].decode('ascii') res['segmentation'] = rle all_results.append(res) tqdm_bar.update(1) return all_results
[ "\n Args:\n df: a DataFlow which produces (image, image_id)\n model_func: a callable from the TF model.\n It takes image and returns (boxes, probs, labels, [masks])\n tqdm_bar: a tqdm object to be shared among multiple evaluation instances. If None,\n will create a new one.\n\n Returns:\n list of dict, in the format used by\n `DetectionDataset.eval_or_save_inference_results`\n " ]
Please provide a description of the function:def multithread_predict_dataflow(dataflows, model_funcs): num_worker = len(model_funcs) assert len(dataflows) == num_worker if num_worker == 1: return predict_dataflow(dataflows[0], model_funcs[0]) kwargs = {'thread_name_prefix': 'EvalWorker'} if sys.version_info.minor >= 6 else {} with ThreadPoolExecutor(max_workers=num_worker, **kwargs) as executor, \ tqdm.tqdm(total=sum([df.size() for df in dataflows])) as pbar: futures = [] for dataflow, pred in zip(dataflows, model_funcs): futures.append(executor.submit(predict_dataflow, dataflow, pred, pbar)) all_results = list(itertools.chain(*[fut.result() for fut in futures])) return all_results
[ "\n Running multiple `predict_dataflow` in multiple threads, and aggregate the results.\n\n Args:\n dataflows: a list of DataFlow to be used in :func:`predict_dataflow`\n model_funcs: a list of callable to be used in :func:`predict_dataflow`\n\n Returns:\n list of dict, in the format used by\n `DetectionDataset.eval_or_save_inference_results`\n " ]
Please provide a description of the function:def batch_flatten(x): shape = x.get_shape().as_list()[1:] if None not in shape: return tf.reshape(x, [-1, int(np.prod(shape))]) return tf.reshape(x, tf.stack([tf.shape(x)[0], -1]))
[ "\n Flatten the tensor except the first dimension.\n " ]
Please provide a description of the function:def FullyConnected( inputs, units, activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None): if kernel_initializer is None: if get_tf_version_tuple() <= (1, 12): kernel_initializer = tf.contrib.layers.variance_scaling_initializer(2.0) else: kernel_initializer = tf.keras.initializers.VarianceScaling(2.0, distribution='untruncated_normal') inputs = batch_flatten(inputs) with rename_get_variable({'kernel': 'W', 'bias': 'b'}): layer = tf.layers.Dense( units=units, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, _reuse=tf.get_variable_scope().reuse) ret = layer.apply(inputs, scope=tf.get_variable_scope()) ret = tf.identity(ret, name='output') ret.variables = VariableHolder(W=layer.kernel) if use_bias: ret.variables.b = layer.bias return ret
[ "\n A wrapper around `tf.layers.Dense`.\n One difference to maintain backward-compatibility:\n Default weight initializer is variance_scaling_initializer(2.0).\n\n Variable Names:\n\n * ``W``: weights of shape [in_dim, out_dim]\n * ``b``: bias\n " ]
Please provide a description of the function:def _init_runtime(self): if self.idx != 0: from tensorpack.models.registry import disable_layer_logging disable_layer_logging() self.predictor = OfflinePredictor(self.config) if self.idx == 0: with self.predictor.graph.as_default(): describe_trainable_vars()
[ " Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll\n have workers that run on multiGPUs\n " ]
Please provide a description of the function:def fetch_batch(self): inp, f = self.queue.get() nr_input_var = len(inp) batched, futures = [[] for _ in range(nr_input_var)], [] for k in range(nr_input_var): batched[k].append(inp[k]) futures.append(f) while len(futures) < self.batch_size: try: inp, f = self.queue.get_nowait() for k in range(nr_input_var): batched[k].append(inp[k]) futures.append(f) except queue.Empty: break # do not wait for k in range(nr_input_var): batched[k] = np.asarray(batched[k]) return batched, futures
[ " Fetch a batch of data without waiting" ]
Please provide a description of the function:def put_task(self, dp, callback=None): f = Future() if callback is not None: f.add_done_callback(callback) self.input_queue.put((dp, f)) return f
[ "\n Same as in :meth:`AsyncPredictorBase.put_task`.\n " ]
Please provide a description of the function:def loads_msgpack(buf): # Since 0.6, the default max size was set to 1MB. # We change it to approximately 1G. return msgpack.loads(buf, raw=False, max_bin_len=MAX_MSGPACK_LEN, max_array_len=MAX_MSGPACK_LEN, max_map_len=MAX_MSGPACK_LEN, max_str_len=MAX_MSGPACK_LEN)
[ "\n Args:\n buf: the output of `dumps`.\n " ]
Please provide a description of the function:def BatchNorm(inputs, axis=None, training=None, momentum=0.9, epsilon=1e-5, center=True, scale=True, beta_initializer=tf.zeros_initializer(), gamma_initializer=tf.ones_initializer(), virtual_batch_size=None, data_format='channels_last', internal_update=False, sync_statistics=None): # parse shapes data_format = get_data_format(data_format, keras_mode=False) shape = inputs.get_shape().as_list() ndims = len(shape) assert ndims in [2, 4], ndims if sync_statistics is not None: sync_statistics = sync_statistics.lower() assert sync_statistics in [None, 'nccl', 'horovod'], sync_statistics if axis is None: if ndims == 2: axis = 1 else: axis = 1 if data_format == 'NCHW' else 3 assert axis in [1, 3], axis num_chan = shape[axis] # parse training/ctx ctx = get_current_tower_context() if training is None: training = ctx.is_training training = bool(training) TF_version = get_tf_version_tuple() freeze_bn_backward = not training and ctx.is_training if freeze_bn_backward: assert TF_version >= (1, 4), \ "Fine tuning a BatchNorm model with fixed statistics needs TF>=1.4!" if ctx.is_main_training_tower: # only warn in first tower logger.warn("[BatchNorm] Using moving_mean/moving_variance in training.") # Using moving_mean/moving_variance in training, which means we # loaded a pre-trained BN and only fine-tuning the affine part. if sync_statistics is None or not (training and ctx.is_training): coll_bk = backup_collection([tf.GraphKeys.UPDATE_OPS]) with rename_get_variable( {'moving_mean': 'mean/EMA', 'moving_variance': 'variance/EMA'}): tf_args = dict( axis=axis, momentum=momentum, epsilon=epsilon, center=center, scale=scale, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, # https://github.com/tensorflow/tensorflow/issues/10857#issuecomment-410185429 fused=(ndims == 4 and axis in [1, 3] and not freeze_bn_backward), _reuse=tf.get_variable_scope().reuse) if TF_version >= (1, 5): tf_args['virtual_batch_size'] = virtual_batch_size else: assert virtual_batch_size is None, "Feature not supported in this version of TF!" use_fp16 = inputs.dtype == tf.float16 if use_fp16: # non-fused does not support fp16; fused does not support all layouts. # we made our best guess here tf_args['fused'] = True layer = tf.layers.BatchNormalization(**tf_args) xn = layer.apply(inputs, training=training, scope=tf.get_variable_scope()) # maintain EMA only on one GPU is OK, even in replicated mode. # because during training, EMA isn't used if ctx.is_main_training_tower: for v in layer.non_trainable_variables: if isinstance(v, tf.Variable): tf.add_to_collection(tf.GraphKeys.MODEL_VARIABLES, v) if not ctx.is_main_training_tower or internal_update: restore_collection(coll_bk) if training and internal_update: assert layer.updates with tf.control_dependencies(layer.updates): ret = tf.identity(xn, name='output') else: ret = tf.identity(xn, name='output') vh = ret.variables = VariableHolder( moving_mean=layer.moving_mean, mean=layer.moving_mean, # for backward-compatibility moving_variance=layer.moving_variance, variance=layer.moving_variance) # for backward-compatibility if scale: vh.gamma = layer.gamma if center: vh.beta = layer.beta else: red_axis = [0] if ndims == 2 else ([0, 2, 3] if axis == 1 else [0, 1, 2]) new_shape = None # don't need to reshape unless ... if ndims == 4 and axis == 1: new_shape = [1, num_chan, 1, 1] batch_mean = tf.reduce_mean(inputs, axis=red_axis) batch_mean_square = tf.reduce_mean(tf.square(inputs), axis=red_axis) if sync_statistics == 'nccl': num_dev = ctx.total if num_dev == 1: logger.warn("BatchNorm(sync_statistics='nccl') is used with only one tower!") else: assert six.PY2 or TF_version >= (1, 10), \ "Cross-GPU BatchNorm is only supported in TF>=1.10 ." \ "Upgrade TF or apply this patch manually: https://github.com/tensorflow/tensorflow/pull/20360" if TF_version <= (1, 12): try: from tensorflow.contrib.nccl.python.ops.nccl_ops import _validate_and_load_nccl_so except Exception: pass else: _validate_and_load_nccl_so() from tensorflow.contrib.nccl.ops import gen_nccl_ops else: from tensorflow.python.ops import gen_nccl_ops shared_name = re.sub('tower[0-9]+/', '', tf.get_variable_scope().name) batch_mean = gen_nccl_ops.nccl_all_reduce( input=batch_mean, reduction='sum', num_devices=num_dev, shared_name=shared_name + '_NCCL_mean') * (1.0 / num_dev) batch_mean_square = gen_nccl_ops.nccl_all_reduce( input=batch_mean_square, reduction='sum', num_devices=num_dev, shared_name=shared_name + '_NCCL_mean_square') * (1.0 / num_dev) elif sync_statistics == 'horovod': # Require https://github.com/uber/horovod/pull/331 import horovod.tensorflow as hvd if hvd.size() == 1: logger.warn("BatchNorm(sync_statistics='horovod') is used with only one process!") else: import horovod hvd_version = tuple(map(int, horovod.__version__.split('.'))) assert hvd_version >= (0, 13, 6), "sync_statistics=horovod needs horovod>=0.13.6 !" batch_mean = hvd.allreduce(batch_mean, average=True) batch_mean_square = hvd.allreduce(batch_mean_square, average=True) batch_var = batch_mean_square - tf.square(batch_mean) batch_mean_vec = batch_mean batch_var_vec = batch_var beta, gamma, moving_mean, moving_var = get_bn_variables( num_chan, scale, center, beta_initializer, gamma_initializer) if new_shape is not None: batch_mean = tf.reshape(batch_mean, new_shape) batch_var = tf.reshape(batch_var, new_shape) # Using fused_batch_norm(is_training=False) is actually slightly faster, # but hopefully this call will be JITed in the future. xn = tf.nn.batch_normalization( inputs, batch_mean, batch_var, tf.reshape(beta, new_shape), tf.reshape(gamma, new_shape), epsilon) else: xn = tf.nn.batch_normalization( inputs, batch_mean, batch_var, beta, gamma, epsilon) if ctx.is_main_training_tower: ret = update_bn_ema( xn, batch_mean_vec, batch_var_vec, moving_mean, moving_var, momentum) else: ret = tf.identity(xn, name='output') vh = ret.variables = VariableHolder( moving_mean=moving_mean, mean=moving_mean, # for backward-compatibility moving_variance=moving_var, variance=moving_var) # for backward-compatibility if scale: vh.gamma = gamma if center: vh.beta = beta return ret
[ "\n Almost equivalent to `tf.layers.batch_normalization`, but different (and more powerful)\n in the following:\n\n 1. Accepts an alternative `data_format` option when `axis` is None. For 2D input, this argument will be ignored.\n 2. Default value for `momentum` and `epsilon` is different.\n 3. Default value for `training` is automatically obtained from tensorpack's `TowerContext`, but can be overwritten.\n 4. Support the `internal_update` option, which cover more use cases than the standard collection-based update.\n 5. Support the `sync_statistics` option, which is very useful in small-batch models.\n\n Args:\n internal_update (bool): if False, add EMA update ops to\n `tf.GraphKeys.UPDATE_OPS`. If True, update EMA inside the layer by control dependencies.\n They are very similar in speed, but `internal_update=True` is recommended and can be helpful when:\n\n 1. BatchNorm is used inside dynamic control flow.\n The collection-based update does not support dynamic control flows.\n 2. BatchNorm layer is sometimes unused (e.g., when you have two networks to train alternatively).\n Putting all update ops into a single collection will waste a lot of compute.\n\n Corresponding TF issue: https://github.com/tensorflow/tensorflow/issues/14699\n sync_statistics (str or None): one of None, \"nccl\", or \"horovod\".\n\n By default (None), it uses statistics of the input tensor to normalize during training.\n This is the standard way BatchNorm was implemented in most frameworks.\n\n When set to \"nccl\", this layer must be used under tensorpack's multi-GPU trainers.\n It uses the aggregated statistics of the whole batch (across all GPUs) to normalize.\n\n When set to \"horovod\", this layer must be used under tensorpack's :class:`HorovodTrainer`.\n It uses the aggregated statistics of the whole batch (across all MPI ranks) to normalize.\n Note that on single machine this is significantly slower than the \"nccl\" implementation.\n\n When enabled, per-GPU E[x] and E[x^2] among all GPUs are averaged to compute\n global mean & variance. Therefore each GPU needs to have the same batch size.\n\n The synchronization is based on the current variable scope + the name of the layer\n (`BatchNorm('name', input)`). Therefore, you need to make sure that:\n\n 1. The BatchNorm layer on different GPUs needs to have the same name, so that\n statistics can be synchronized. If names do not match, this layer will hang.\n 2. Different BatchNorm layers in one tower cannot share the same name.\n 3. A BatchNorm layer needs to be executed for the same number of times by all GPUs.\n If different GPUs execute one BatchNorm layer for different number of times\n (e.g., if some GPUs do not execute it), this layer may hang.\n\n This option only has effect when `training == get_current_tower_context().training == True`.\n\n This option is also known as \"Cross-GPU BatchNorm\" as mentioned in:\n `MegDet: A Large Mini-Batch Object Detector <https://arxiv.org/abs/1711.07240>`_.\n Corresponding TF issue: https://github.com/tensorflow/tensorflow/issues/18222.\n\n When `sync_statistics` is enabled, `internal_update` will be set to True automatically.\n This is to avoid running `UPDATE_OPS`, which requires synchronization.\n\n Variable Names:\n\n * ``beta``: the bias term. Will be zero-inited by default.\n * ``gamma``: the scale term. Will be one-inited by default.\n * ``mean/EMA``: the moving average of mean.\n * ``variance/EMA``: the moving average of variance.\n\n Note:\n Combinations of ``training`` and ``ctx.is_training``:\n\n * ``training == ctx.is_training``: standard BN, EMA are maintained during training\n and used during inference. This is the default.\n * ``training and not ctx.is_training``: still use batch statistics in inference.\n * ``not training and ctx.is_training``: use EMA to normalize in\n training. This is useful when you load a pre-trained BN and\n don't want to fine tune the EMA. EMA will not be updated in\n this case.\n " ]
Please provide a description of the function:def BatchRenorm(x, rmax, dmax, momentum=0.9, epsilon=1e-5, center=True, scale=True, gamma_initializer=None, data_format='channels_last'): shape = x.get_shape().as_list() ndims = len(shape) assert ndims in [2, 4] if ndims == 2: data_format = 'channels_first' ctx = get_current_tower_context() coll_bk = backup_collection([tf.GraphKeys.UPDATE_OPS]) layer = tf.layers.BatchNormalization( axis=1 if data_format == 'channels_first' else 3, momentum=momentum, epsilon=epsilon, center=center, scale=scale, renorm=True, renorm_clipping={ 'rmin': 1.0 / rmax, 'rmax': rmax, 'dmax': dmax}, renorm_momentum=0.99, gamma_initializer=gamma_initializer, fused=False, _reuse=tf.get_variable_scope().reuse) xn = layer.apply(x, training=ctx.is_training, scope=tf.get_variable_scope()) if ctx.is_main_training_tower: for v in layer.non_trainable_variables: if isinstance(v, tf.Variable): tf.add_to_collection(tf.GraphKeys.MODEL_VARIABLES, v) else: # only run UPDATE_OPS in the first tower restore_collection(coll_bk) if ndims == 2: xn = tf.squeeze(xn, [1, 2]) ret = tf.identity(xn, name='output') # TODO not sure whether to add moving_mean/moving_var to VH now vh = ret.variables = VariableHolder() if scale: vh.gamma = layer.gamma if center: vh.beta = layer.beta return ret
[ "\n Batch Renormalization layer, as described in the paper:\n `Batch Renormalization: Towards Reducing Minibatch Dependence in Batch-Normalized Models\n <https://arxiv.org/abs/1702.03275>`_.\n This implementation is a wrapper around `tf.layers.batch_normalization`.\n\n Args:\n x (tf.Tensor): a NHWC or NC tensor.\n rmax, dmax (tf.Tensor): a scalar tensor, the maximum allowed corrections.\n decay (float): decay rate of moving average.\n epsilon (float): epsilon to avoid divide-by-zero.\n use_scale, use_bias (bool): whether to use the extra affine transformation or not.\n\n Returns:\n tf.Tensor: a tensor named ``output`` with the same shape of x.\n\n Variable Names:\n\n * ``beta``: the bias term.\n * ``gamma``: the scale term. Input will be transformed by ``x * gamma + beta``.\n * ``moving_mean, renorm_mean, renorm_mean_weight``: See TF documentation.\n * ``moving_variance, renorm_stddev, renorm_stddev_weight``: See TF documentation.\n " ]
Please provide a description of the function:def generator(self, z): nf = 64 l = FullyConnected('fc0', z, nf * 8 * 4 * 4, activation=tf.identity) l = tf.reshape(l, [-1, 4, 4, nf * 8]) l = BNReLU(l) with argscope(Conv2DTranspose, activation=BNReLU, kernel_size=4, strides=2): l = Conv2DTranspose('deconv1', l, nf * 4) l = Conv2DTranspose('deconv2', l, nf * 2) l = Conv2DTranspose('deconv3', l, nf) l = Conv2DTranspose('deconv4', l, 3, activation=tf.identity) l = tf.tanh(l, name='gen') return l
[ " return an image generated from z" ]
Please provide a description of the function:def discriminator(self, imgs): nf = 64 with argscope(Conv2D, kernel_size=4, strides=2): l = (LinearWrap(imgs) .Conv2D('conv0', nf, activation=tf.nn.leaky_relu) .Conv2D('conv1', nf * 2) .BatchNorm('bn1') .tf.nn.leaky_relu() .Conv2D('conv2', nf * 4) .BatchNorm('bn2') .tf.nn.leaky_relu() .Conv2D('conv3', nf * 8) .BatchNorm('bn3') .tf.nn.leaky_relu() .FullyConnected('fct', 1)()) return l
[ " return a (b, 1) logits" ]
Please provide a description of the function:def area(boxes): x_min, y_min, x_max, y_max = tf.split(boxes, 4, axis=1) return tf.squeeze((y_max - y_min) * (x_max - x_min), [1])
[ "\n Args:\n boxes: nx4 floatbox\n\n Returns:\n n\n " ]
Please provide a description of the function:def pairwise_intersection(boxlist1, boxlist2): x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=1) x_min2, y_min2, x_max2, y_max2 = tf.split(boxlist2, 4, axis=1) all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2)) all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2)) intersect_heights = tf.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin) all_pairs_min_xmax = tf.minimum(x_max1, tf.transpose(x_max2)) all_pairs_max_xmin = tf.maximum(x_min1, tf.transpose(x_min2)) intersect_widths = tf.maximum(0.0, all_pairs_min_xmax - all_pairs_max_xmin) return intersect_heights * intersect_widths
[ "Compute pairwise intersection areas between boxes.\n\n Args:\n boxlist1: Nx4 floatbox\n boxlist2: Mx4\n\n Returns:\n a tensor with shape [N, M] representing pairwise intersections\n " ]
Please provide a description of the function:def pairwise_iou(boxlist1, boxlist2): intersections = pairwise_intersection(boxlist1, boxlist2) areas1 = area(boxlist1) areas2 = area(boxlist2) unions = ( tf.expand_dims(areas1, 1) + tf.expand_dims(areas2, 0) - intersections) return tf.where( tf.equal(intersections, 0.0), tf.zeros_like(intersections), tf.truediv(intersections, unions))
[ "Computes pairwise intersection-over-union between box collections.\n\n Args:\n boxlist1: Nx4 floatbox\n boxlist2: Mx4\n\n Returns:\n a tensor with shape [N, M] representing pairwise iou scores.\n " ]
Please provide a description of the function:def sample(path, start, length): # initialize vocabulary and sequence length param.seq_len = 1 ds = CharRNNData(param.corpus, 100000) pred = OfflinePredictor(PredictConfig( model=Model(), session_init=SaverRestore(path), input_names=['input', 'c0', 'h0', 'c1', 'h1'], output_names=['prob', 'last_state'])) # feed the starting sentence initial = np.zeros((1, param.rnn_size)) for c in start[:-1]: x = np.array([[ds.char2idx[c]]], dtype='int32') _, state = pred(x, initial, initial, initial, initial) def pick(prob): t = np.cumsum(prob) s = np.sum(prob) return(int(np.searchsorted(t, np.random.rand(1) * s))) # generate more ret = start c = start[-1] for k in range(length): x = np.array([[ds.char2idx[c]]], dtype='int32') prob, state = pred(x, state[0, 0], state[0, 1], state[1, 0], state[1, 1]) c = ds.chars[pick(prob[0])] ret += c print(ret)
[ "\n :param path: path to the model\n :param start: a `str`. the starting characters\n :param length: a `int`. the length of text to generate\n " ]
Please provide a description of the function:def Maxout(x, num_unit): input_shape = x.get_shape().as_list() ndim = len(input_shape) assert ndim == 4 or ndim == 2 ch = input_shape[-1] assert ch is not None and ch % num_unit == 0 if ndim == 4: x = tf.reshape(x, [-1, input_shape[1], input_shape[2], ch / num_unit, num_unit]) else: x = tf.reshape(x, [-1, ch / num_unit, num_unit]) return tf.reduce_max(x, ndim, name='output')
[ "\n Maxout as in the paper `Maxout Networks <http://arxiv.org/abs/1302.4389>`_.\n\n Args:\n x (tf.Tensor): a NHWC or NC tensor. Channel has to be known.\n num_unit (int): a int. Must be divisible by C.\n\n Returns:\n tf.Tensor: of shape NHW(C/num_unit) named ``output``.\n " ]
Please provide a description of the function:def PReLU(x, init=0.001, name='output'): init = tfv1.constant_initializer(init) alpha = tfv1.get_variable('alpha', [], initializer=init) x = ((1 + alpha) * x + (1 - alpha) * tf.abs(x)) ret = tf.multiply(x, 0.5, name=name) ret.variables = VariableHolder(alpha=alpha) return ret
[ "\n Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing\n Human-Level Performance on ImageNet Classification\n <http://arxiv.org/abs/1502.01852>`_.\n\n Args:\n x (tf.Tensor): input\n init (float): initial value for the learnable slope.\n name (str): name of the output.\n\n Variable Names:\n\n * ``alpha``: learnable slope.\n " ]
Please provide a description of the function:def BNReLU(x, name=None): x = BatchNorm('bn', x) x = tf.nn.relu(x, name=name) return x
[ "\n A shorthand of BatchNormalization + ReLU.\n " ]
Please provide a description of the function:def GroupNorm(x, group=32, gamma_initializer=tf.constant_initializer(1.)): shape = x.get_shape().as_list() ndims = len(shape) assert ndims == 4, shape chan = shape[1] assert chan % group == 0, chan group_size = chan // group orig_shape = tf.shape(x) h, w = orig_shape[2], orig_shape[3] x = tf.reshape(x, tf.stack([-1, group, group_size, h, w])) mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True) new_shape = [1, group, group_size, 1, 1] beta = tf.get_variable('beta', [chan], initializer=tf.constant_initializer()) beta = tf.reshape(beta, new_shape) gamma = tf.get_variable('gamma', [chan], initializer=gamma_initializer) gamma = tf.reshape(gamma, new_shape) out = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-5, name='output') return tf.reshape(out, orig_shape, name='output')
[ "\n More code that reproduces the paper can be found at https://github.com/ppwwyyxx/GroupNorm-reproduce/.\n " ]
Please provide a description of the function:def backbone_scope(freeze): def nonlin(x): x = get_norm()(x) return tf.nn.relu(x) with argscope([Conv2D, MaxPooling, BatchNorm], data_format='channels_first'), \ argscope(Conv2D, use_bias=False, activation=nonlin, kernel_initializer=tf.variance_scaling_initializer( scale=2.0, mode='fan_out')), \ ExitStack() as stack: if cfg.BACKBONE.NORM in ['FreezeBN', 'SyncBN']: if freeze or cfg.BACKBONE.NORM == 'FreezeBN': stack.enter_context(argscope(BatchNorm, training=False)) else: stack.enter_context(argscope( BatchNorm, sync_statistics='nccl' if cfg.TRAINER == 'replicated' else 'horovod')) if freeze: stack.enter_context(freeze_variables(stop_gradient=False, skip_collection=True)) else: # the layers are not completely freezed, but we may want to only freeze the affine if cfg.BACKBONE.FREEZE_AFFINE: stack.enter_context(custom_getter_scope(freeze_affine_getter)) yield
[ "\n Args:\n freeze (bool): whether to freeze all the variables under the scope\n " ]
Please provide a description of the function:def extract_images(filename): with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2051: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, filename)) num_images = _read32(bytestream) rows = _read32(bytestream) cols = _read32(bytestream) buf = bytestream.read(rows * cols * num_images) data = numpy.frombuffer(buf, dtype=numpy.uint8) data = data.reshape(num_images, rows, cols, 1) data = data.astype('float32') / 255.0 return data
[ "Extract the images into a 4D uint8 numpy array [index, y, x, depth]." ]
Please provide a description of the function:def extract_labels(filename): with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, filename)) num_items = _read32(bytestream) buf = bytestream.read(num_items) labels = numpy.frombuffer(buf, dtype=numpy.uint8) return labels
[ "Extract the labels into a 1D uint8 numpy array [index]." ]
Please provide a description of the function:def create_dummy_class(klass, dependency): assert not building_rtfd() class _DummyMetaClass(type): # throw error on class attribute access def __getattr__(_, __): raise AttributeError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass)) @six.add_metaclass(_DummyMetaClass) class _Dummy(object): # throw error on constructor def __init__(self, *args, **kwargs): raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass)) return _Dummy
[ "\n When a dependency of a class is not available, create a dummy class which throws ImportError when used.\n\n Args:\n klass (str): name of the class.\n dependency (str): name of the dependency.\n\n Returns:\n class: a class object\n " ]
Please provide a description of the function:def create_dummy_func(func, dependency): assert not building_rtfd() if isinstance(dependency, (list, tuple)): dependency = ','.join(dependency) def _dummy(*args, **kwargs): raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, func)) return _dummy
[ "\n When a dependency of a function is not available, create a dummy function which throws ImportError when used.\n\n Args:\n func (str): name of the function.\n dependency (str or list[str]): name(s) of the dependency.\n\n Returns:\n function: a function object\n " ]
Please provide a description of the function:def log_deprecated(name="", text="", eos=""): assert name or text if eos: eos = "after " + datetime(*map(int, eos.split("-"))).strftime("%d %b") if name: if eos: warn_msg = "%s will be deprecated %s. %s" % (name, eos, text) else: warn_msg = "%s was deprecated. %s" % (name, text) else: warn_msg = text if eos: warn_msg += " Legacy period ends %s" % eos logger.warn("[Deprecated] " + warn_msg)
[ "\n Log deprecation warning.\n\n Args:\n name (str): name of the deprecated item.\n text (str, optional): information about the deprecation.\n eos (str, optional): end of service date such as \"YYYY-MM-DD\".\n " ]
Please provide a description of the function:def deprecated(text="", eos=""): def get_location(): import inspect frame = inspect.currentframe() if frame: callstack = inspect.getouterframes(frame)[-1] return '%s:%i' % (callstack[1], callstack[2]) else: stack = inspect.stack(0) entry = stack[2] return '%s:%i' % (entry[1], entry[2]) def deprecated_inner(func): @functools.wraps(func) def new_func(*args, **kwargs): name = "{} [{}]".format(func.__name__, get_location()) log_deprecated(name, text, eos) return func(*args, **kwargs) return new_func return deprecated_inner
[ "\n Args:\n text, eos: same as :func:`log_deprecated`.\n\n Returns:\n a decorator which deprecates the function.\n\n Example:\n .. code-block:: python\n\n @deprecated(\"Explanation of what to do instead.\", \"2017-11-4\")\n def foo(...):\n pass\n " ]
Please provide a description of the function:def refill_queue(self): self.thread.pause() # pause enqueue opt = tfv1.RunOptions() opt.timeout_in_ms = 2000 # 2s sess = tfv1.get_default_session() # dequeue until empty try: while True: sess.run(self._dequeue_op, options=opt) except tf.errors.DeadlineExceededError: pass # reset dataflow, start thread self.thread.reinitialize_dataflow() self.thread.resume()
[ "\n Clear the queue, then call dataflow.__iter__() again and fill into the queue.\n " ]
Please provide a description of the function:def _create_ema_callback(self): with self.cached_name_scope(): # in TF there is no API to get queue capacity, so we can only summary the size size = tf.cast(self.queue.size(), tf.float32, name='queue_size') size_ema_op = add_moving_summary(size, collection=None, decay=0.5)[0].op ret = RunOp( lambda: size_ema_op, run_before=False, run_as_trigger=False, run_step=True) ret.name_scope = "InputSource/EMA" return ret
[ "\n Create a hook-only callback which maintain EMA of the queue size.\n Also tf.summary.scalar the EMA.\n " ]
Please provide a description of the function:def _setup(self, inputs): logger.info("Setting up the queue for CPU prefetching ...") self.input_placehdrs = [build_or_reuse_placeholder(v) for v in inputs] assert len(self.input_placehdrs) > 0, \ "BatchQueueInput has to be used with some input signature!" # prepare placeholders without the first dimension placehdrs_nobatch = [] for p in self.input_placehdrs: placehdrs_nobatch.append(tfv1.placeholder( dtype=p.dtype, shape=p.get_shape().as_list()[1:], name=get_op_tensor_name(p.name)[0] + '-nobatch')) # dequeue_many requires fully-defined shapes shape_err = "Use of BatchQueueInput requires inputs to have fully-defined " "shapes except for the batch dimension" shapes = [] for p in placehdrs_nobatch: assert p.get_shape().is_fully_defined(), shape_err shapes.append(p.get_shape()) with self.cached_name_scope(): if self.queue is None: self.queue = tf.FIFOQueue( 3000, [x.dtype for x in self.input_placehdrs], shapes=shapes, name='input_queue') for shp in self.queue.shapes: assert shp.is_fully_defined(), shape_err self.thread = EnqueueThread(self.queue, self._inf_ds, placehdrs_nobatch)
[]
Please provide a description of the function:def dataflow_to_dataset(df, types): # TODO theoretically it can support dict assert isinstance(df, DataFlow), df assert isinstance(types, (list, tuple)), types df = MapData(df, lambda dp: tuple(dp)) df.reset_state() ds = tf.data.Dataset.from_generator( df.get_data, tuple(types)) return ds
[ "\n Wrap a dataflow to tf.data.Dataset.\n This function will also reset the dataflow.\n\n If the dataflow itself is finite, the returned dataset is also finite.\n Therefore, if used for training, you'll need to add `.repeat()` on the returned\n dataset.\n\n Args:\n df (DataFlow): a dataflow which produces lists\n types([tf.DType]): list of types\n\n Returns:\n (tf.data.Dataset)\n " ]
Please provide a description of the function:def get_predictor(self, n): l = len(self.predictors) if n >= l: logger.warn("n > #towers, will assign predictor to GPU by round-robin") return [self.predictors[k % l] for k in range(n)]
[ "\n Returns:\n OnlinePredictor: the nth predictor on the nth tower.\n " ]
Please provide a description of the function:def intersection(boxes1, boxes2): [y_min1, x_min1, y_max1, x_max1] = np.split(boxes1, 4, axis=1) [y_min2, x_min2, y_max2, x_max2] = np.split(boxes2, 4, axis=1) all_pairs_min_ymax = np.minimum(y_max1, np.transpose(y_max2)) all_pairs_max_ymin = np.maximum(y_min1, np.transpose(y_min2)) intersect_heights = np.maximum( np.zeros(all_pairs_max_ymin.shape, dtype='f4'), all_pairs_min_ymax - all_pairs_max_ymin) all_pairs_min_xmax = np.minimum(x_max1, np.transpose(x_max2)) all_pairs_max_xmin = np.maximum(x_min1, np.transpose(x_min2)) intersect_widths = np.maximum( np.zeros(all_pairs_max_xmin.shape, dtype='f4'), all_pairs_min_xmax - all_pairs_max_xmin) return intersect_heights * intersect_widths
[ "Compute pairwise intersection areas between boxes.\n\n Args:\n boxes1: a numpy array with shape [N, 4] holding N boxes\n boxes2: a numpy array with shape [M, 4] holding M boxes\n\n Returns:\n a numpy array with shape [N*M] representing pairwise intersection area\n " ]
Please provide a description of the function:def iou(boxes1, boxes2): intersect = intersection(boxes1, boxes2) area1 = area(boxes1) area2 = area(boxes2) union = np.expand_dims(area1, axis=1) + np.expand_dims( area2, axis=0) - intersect return intersect / union
[ "Computes pairwise intersection-over-union between box collections.\n\n Args:\n boxes1: a numpy array with shape [N, 4] holding N boxes.\n boxes2: a numpy array with shape [M, 4] holding M boxes.\n\n Returns:\n a numpy array with shape [N, M] representing pairwise iou scores.\n " ]
Please provide a description of the function:def ioa(boxes1, boxes2): intersect = intersection(boxes1, boxes2) inv_areas = np.expand_dims(1.0 / area(boxes2), axis=0) return intersect * inv_areas
[ "Computes pairwise intersection-over-area between box collections.\n\n Intersection-over-area (ioa) between two boxes box1 and box2 is defined as\n their intersection area over box2's area. Note that ioa is not symmetric,\n that is, IOA(box1, box2) != IOA(box2, box1).\n\n Args:\n boxes1: a numpy array with shape [N, 4] holding N boxes.\n boxes2: a numpy array with shape [M, 4] holding N boxes.\n\n Returns:\n a numpy array with shape [N, M] representing pairwise ioa scores.\n " ]
Please provide a description of the function:def maybe_download(url, work_directory): filename = url.split("/")[-1] filepath = os.path.join(work_directory, filename) if not os.path.exists(filepath): logger.info("Downloading to {}...".format(filepath)) download(url, work_directory) return filepath
[ "Download the data from Marlin's website, unless it's already here." ]
Please provide a description of the function:def get_synset_1000(self): fname = os.path.join(self.dir, 'synsets.txt') assert os.path.isfile(fname) lines = [x.strip() for x in open(fname).readlines()] return dict(enumerate(lines))
[ "\n Returns:\n dict: {cls_number: synset_id}\n " ]
Please provide a description of the function:def get_image_list(self, name, dir_structure='original'): assert name in ['train', 'val', 'test'] assert dir_structure in ['original', 'train'] add_label_to_fname = (name != 'train' and dir_structure != 'original') if add_label_to_fname: synset = self.get_synset_1000() fname = os.path.join(self.dir, name + '.txt') assert os.path.isfile(fname), fname with open(fname) as f: ret = [] for line in f.readlines(): name, cls = line.strip().split() cls = int(cls) if add_label_to_fname: name = os.path.join(synset[cls], name) ret.append((name.strip(), cls)) assert len(ret), fname return ret
[ "\n Args:\n name (str): 'train' or 'val' or 'test'\n dir_structure (str): same as in :meth:`ILSVRC12.__init__()`.\n Returns:\n list: list of (image filename, label)\n " ]
Please provide a description of the function:def get_per_pixel_mean(self, size=None): if self.caffepb is None: self.caffepb = get_caffe_pb() obj = self.caffepb.BlobProto() mean_file = os.path.join(self.dir, 'imagenet_mean.binaryproto') with open(mean_file, 'rb') as f: obj.ParseFromString(f.read()) arr = np.array(obj.data).reshape((3, 256, 256)).astype('float32') arr = np.transpose(arr, [1, 2, 0]) if size is not None: arr = cv2.resize(arr, size[::-1]) return arr
[ "\n Args:\n size (tuple): image size in (h, w). Defaults to (256, 256).\n Returns:\n np.ndarray: per-pixel mean of shape (h, w, 3 (BGR)) in range [0, 255].\n " ]
Please provide a description of the function:def guess_dir_structure(dir): subdir = os.listdir(dir)[0] # find a subdir starting with 'n' if subdir.startswith('n') and \ os.path.isdir(os.path.join(dir, subdir)): dir_structure = 'train' else: dir_structure = 'original' logger.info( "[ILSVRC12] Assuming directory {} has '{}' structure.".format( dir, dir_structure)) return dir_structure
[ "\n Return the directory structure of \"dir\".\n\n Args:\n dir(str): something like '/path/to/imagenet/val'\n\n Returns:\n either 'train' or 'original'\n " ]
Please provide a description of the function:def print_coco_metrics(self, json_file): from pycocotools.cocoeval import COCOeval ret = {} cocoDt = self.coco.loadRes(json_file) cocoEval = COCOeval(self.coco, cocoDt, 'bbox') cocoEval.evaluate() cocoEval.accumulate() cocoEval.summarize() fields = ['IoU=0.5:0.95', 'IoU=0.5', 'IoU=0.75', 'small', 'medium', 'large'] for k in range(6): ret['mAP(bbox)/' + fields[k]] = cocoEval.stats[k] json_obj = json.load(open(json_file)) if len(json_obj) > 0 and 'segmentation' in json_obj[0]: cocoEval = COCOeval(self.coco, cocoDt, 'segm') cocoEval.evaluate() cocoEval.accumulate() cocoEval.summarize() for k in range(6): ret['mAP(segm)/' + fields[k]] = cocoEval.stats[k] return ret
[ "\n Args:\n json_file (str): path to the results json file in coco format\n Returns:\n dict: the evaluation metrics\n " ]
Please provide a description of the function:def load(self, add_gt=True, add_mask=False): if add_mask: assert add_gt with timed_operation('Load Groundtruth Boxes for {}'.format(self.name)): img_ids = self.coco.getImgIds() img_ids.sort() # list of dict, each has keys: height,width,id,file_name imgs = self.coco.loadImgs(img_ids) for img in tqdm.tqdm(imgs): img['image_id'] = img.pop('id') self._use_absolute_file_name(img) if add_gt: self._add_detection_gt(img, add_mask) return imgs
[ "\n Args:\n add_gt: whether to add ground truth bounding box annotations to the dicts\n add_mask: whether to also add ground truth mask\n\n Returns:\n a list of dict, each has keys including:\n 'image_id', 'file_name',\n and (if add_gt is True) 'boxes', 'class', 'is_crowd', and optionally\n 'segmentation'.\n " ]
Please provide a description of the function:def _use_absolute_file_name(self, img): img['file_name'] = os.path.join( self._imgdir, img['file_name']) assert os.path.isfile(img['file_name']), img['file_name']
[ "\n Change relative filename to abosolute file name.\n " ]
Please provide a description of the function:def _add_detection_gt(self, img, add_mask): # ann_ids = self.coco.getAnnIds(imgIds=img['image_id']) # objs = self.coco.loadAnns(ann_ids) objs = self.coco.imgToAnns[img['image_id']] # equivalent but faster than the above two lines # clean-up boxes valid_objs = [] width = img.pop('width') height = img.pop('height') for objid, obj in enumerate(objs): if obj.get('ignore', 0) == 1: continue x1, y1, w, h = obj['bbox'] # bbox is originally in float # x1/y1 means upper-left corner and w/h means true w/h. This can be verified by segmentation pixels. # But we do make an assumption here that (0.0, 0.0) is upper-left corner of the first pixel x1 = np.clip(float(x1), 0, width) y1 = np.clip(float(y1), 0, height) w = np.clip(float(x1 + w), 0, width) - x1 h = np.clip(float(y1 + h), 0, height) - y1 # Require non-zero seg area and more than 1x1 box size if obj['area'] > 1 and w > 0 and h > 0 and w * h >= 4: obj['bbox'] = [x1, y1, x1 + w, y1 + h] valid_objs.append(obj) if add_mask: segs = obj['segmentation'] if not isinstance(segs, list): assert obj['iscrowd'] == 1 obj['segmentation'] = None else: valid_segs = [np.asarray(p).reshape(-1, 2).astype('float32') for p in segs if len(p) >= 6] if len(valid_segs) == 0: logger.error("Object {} in image {} has no valid polygons!".format(objid, img['file_name'])) elif len(valid_segs) < len(segs): logger.warn("Object {} in image {} has invalid polygons!".format(objid, img['file_name'])) obj['segmentation'] = valid_segs # all geometrically-valid boxes are returned boxes = np.asarray([obj['bbox'] for obj in valid_objs], dtype='float32') # (n, 4) cls = np.asarray([ self.COCO_id_to_category_id[obj['category_id']] for obj in valid_objs], dtype='int32') # (n,) is_crowd = np.asarray([obj['iscrowd'] for obj in valid_objs], dtype='int8') # add the keys img['boxes'] = boxes # nx4 img['class'] = cls # n, always >0 img['is_crowd'] = is_crowd # n, if add_mask: # also required to be float32 img['segmentation'] = [ obj['segmentation'] for obj in valid_objs]
[ "\n Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection.\n If add_mask is True, also add 'segmentation' in coco poly format.\n " ]
Please provide a description of the function:def load_many(basedir, names, add_gt=True, add_mask=False): if not isinstance(names, (list, tuple)): names = [names] ret = [] for n in names: coco = COCODetection(basedir, n) ret.extend(coco.load(add_gt, add_mask=add_mask)) return ret
[ "\n Load and merges several instance files together.\n\n Returns the same format as :meth:`COCODetection.load`.\n " ]
Please provide a description of the function:def load_training_roidbs(self, names): return COCODetection.load_many( cfg.DATA.BASEDIR, names, add_gt=True, add_mask=cfg.MODE_MASK)
[ "\n Args:\n names (list[str]): name of the training datasets, e.g. ['train2014', 'valminusminival2014']\n\n Returns:\n roidbs (list[dict]):\n\n Produce \"roidbs\" as a list of dict, each dict corresponds to one image with k>=0 instances.\n and the following keys are expected for training:\n\n file_name: str, full path to the image\n boxes: numpy array of kx4 floats, each row is [x1, y1, x2, y2]\n class: numpy array of k integers, in the range of [1, #categories], NOT [0, #categories)\n is_crowd: k booleans. Use k False if you don't know what it means.\n segmentation: k lists of numpy arrays (one for each instance).\n Each list of numpy arrays corresponds to the mask for one instance.\n Each numpy array in the list is a polygon of shape Nx2,\n because one mask can be represented by N polygons.\n\n If your segmentation annotations are originally masks rather than polygons,\n either convert it, or the augmentation will need to be changed or skipped accordingly.\n\n Include this field only if training Mask R-CNN.\n " ]
Please provide a description of the function:def load_inference_roidbs(self, name): return COCODetection.load_many(cfg.DATA.BASEDIR, name, add_gt=False)
[ "\n Args:\n name (str): name of one inference dataset, e.g. 'minival2014'\n\n Returns:\n roidbs (list[dict]):\n\n Each dict corresponds to one image to run inference on. The\n following keys in the dict are expected:\n\n file_name (str): full path to the image\n image_id (str): an id for the image. The inference results will be stored with this id.\n " ]
Please provide a description of the function:def eval_or_save_inference_results(self, results, dataset, output=None): continuous_id_to_COCO_id = {v: k for k, v in COCODetection.COCO_id_to_category_id.items()} for res in results: # convert to COCO's incontinuous category id res['category_id'] = continuous_id_to_COCO_id[res['category_id']] # COCO expects results in xywh format box = res['bbox'] box[2] -= box[0] box[3] -= box[1] res['bbox'] = [round(float(x), 3) for x in box] assert output is not None, "COCO evaluation requires an output file!" with open(output, 'w') as f: json.dump(results, f) if len(results): # sometimes may crash if the results are empty? return COCODetection(cfg.DATA.BASEDIR, dataset).print_coco_metrics(output) else: return {}
[ "\n Args:\n results (list[dict]): the inference results as dicts.\n Each dict corresponds to one __instance__. It contains the following keys:\n\n image_id (str): the id that matches `load_inference_roidbs`.\n category_id (int): the category prediction, in range [1, #category]\n bbox (list[float]): x1, y1, x2, y2\n score (float):\n segmentation: the segmentation mask in COCO's rle format.\n\n dataset (str): the name of the dataset to evaluate.\n output (str): the output file to optionally save the results to.\n\n Returns:\n dict: the evaluation results.\n " ]
Please provide a description of the function:def timed_operation(msg, log_start=False): assert len(msg) if log_start: logger.info('Start {} ...'.format(msg)) start = timer() yield msg = msg[0].upper() + msg[1:] logger.info('{} finished, time:{:.4f} sec.'.format( msg, timer() - start))
[ "\n Surround a context with a timer.\n\n Args:\n msg(str): the log to print.\n log_start(bool): whether to print also at the beginning.\n\n Example:\n .. code-block:: python\n\n with timed_operation('Good Stuff'):\n time.sleep(1)\n\n Will print:\n\n .. code-block:: python\n\n Good stuff finished, time:1sec.\n " ]
Please provide a description of the function:def total_timer(msg): start = timer() yield t = timer() - start _TOTAL_TIMER_DATA[msg].feed(t)
[ " A context which add the time spent inside to TotalTimer. " ]
Please provide a description of the function:def print_total_timer(): if len(_TOTAL_TIMER_DATA) == 0: return for k, v in six.iteritems(_TOTAL_TIMER_DATA): logger.info("Total Time: {} -> {:.2f} sec, {} times, {:.3g} sec/time".format( k, v.sum, v.count, v.average))
[ "\n Print the content of the TotalTimer, if it's not empty. This function will automatically get\n called when program exits.\n " ]
Please provide a description of the function:def reset_state(self): super(AugmentorList, self).reset_state() for a in self.augmentors: a.reset_state()
[ " Will reset state of each augmentor " ]
Please provide a description of the function:def ensure_proc_terminate(proc): if isinstance(proc, list): for p in proc: ensure_proc_terminate(p) return def stop_proc_by_weak_ref(ref): proc = ref() if proc is None: return if not proc.is_alive(): return proc.terminate() proc.join() assert isinstance(proc, mp.Process) atexit.register(stop_proc_by_weak_ref, weakref.ref(proc))
[ "\n Make sure processes terminate when main process exit.\n\n Args:\n proc (multiprocessing.Process or list)\n " ]
Please provide a description of the function:def enable_death_signal(_warn=True): if platform.system() != 'Linux': return try: import prctl # pip install python-prctl except ImportError: if _warn: log_once('"import prctl" failed! Install python-prctl so that processes can be cleaned with guarantee.', 'warn') return else: assert hasattr(prctl, 'set_pdeathsig'), \ "prctl.set_pdeathsig does not exist! Note that you need to install 'python-prctl' instead of 'prctl'." # is SIGHUP a good choice? prctl.set_pdeathsig(signal.SIGHUP)
[ "\n Set the \"death signal\" of the current process, so that\n the current process will be cleaned with guarantee\n in case the parent dies accidentally.\n " ]
Please provide a description of the function:def mask_sigint(): if is_main_thread(): sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) yield True signal.signal(signal.SIGINT, sigint_handler) else: yield False
[ "\n Returns:\n If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True.\n Otherwise yield False.\n " ]
Please provide a description of the function:def start_proc_mask_signal(proc): if not isinstance(proc, list): proc = [proc] with mask_sigint(): for p in proc: if isinstance(p, mp.Process): if sys.version_info < (3, 4) or mp.get_start_method() == 'fork': log_once( "Starting a process with 'fork' method is not safe and may consume unnecessary extra memory." " Use 'forkserver' method (available after Py3.4) instead if you run into any issues. " "See https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods", 'warn') # noqa p.start()
[ "\n Start process(es) with SIGINT ignored.\n\n Args:\n proc: (mp.Process or list)\n\n Note:\n The signal mask is only applied when called from main thread.\n " ]
Please provide a description of the function:def subproc_call(cmd, timeout=None): try: output = subprocess.check_output( cmd, stderr=subprocess.STDOUT, shell=True, timeout=timeout) return output, 0 except subprocess.TimeoutExpired as e: logger.warn("Command '{}' timeout!".format(cmd)) logger.warn(e.output.decode('utf-8')) return e.output, -1 except subprocess.CalledProcessError as e: logger.warn("Command '{}' failed, return code={}".format(cmd, e.returncode)) logger.warn(e.output.decode('utf-8')) return e.output, e.returncode except Exception: logger.warn("Command '{}' failed to run.".format(cmd)) return "", -2
[ "\n Execute a command with timeout, and return STDOUT and STDERR\n\n Args:\n cmd(str): the command to execute.\n timeout(float): timeout in seconds.\n\n Returns:\n output(bytes), retcode(int). If timeout, retcode is -1.\n " ]
Please provide a description of the function:def queue_put_stoppable(self, q, obj): while not self.stopped(): try: q.put(obj, timeout=5) break except queue.Full: pass
[ " Put obj to queue, but will give up when the thread is stopped" ]
Please provide a description of the function:def queue_get_stoppable(self, q): while not self.stopped(): try: return q.get(timeout=5) except queue.Empty: pass
[ " Take obj from queue, but will give up when the thread is stopped" ]
Please provide a description of the function:def put(self, rank, val): idx = bisect.bisect(self.ranks, rank) self.ranks.insert(idx, rank) self.data.insert(idx, val)
[ "\n Args:\n rank(int): rank of th element. All elements must have different ranks.\n val: an object\n " ]
Please provide a description of the function:def visualize_conv_weights(filters, name): with tf.name_scope('visualize_w_' + name): filters = tf.transpose(filters, (3, 2, 0, 1)) # [h, w, cin, cout] -> [cout, cin, h, w] filters = tf.unstack(filters) # --> cout * [cin, h, w] filters = tf.concat(filters, 1) # --> [cin, cout * h, w] filters = tf.unstack(filters) # --> cin * [cout * h, w] filters = tf.concat(filters, 1) # --> [cout * h, cin * w] filters = tf.expand_dims(filters, 0) filters = tf.expand_dims(filters, -1) tf.summary.image('visualize_w_' + name, filters)
[ "Visualize use weights in convolution filters.\n\n Args:\n filters: tensor containing the weights [H,W,Cin,Cout]\n name: label for tensorboard\n\n Returns:\n image of all weight\n " ]