code
stringlengths
17
6.64M
class MethodAveragePrecision(Enum): '\n Class representing if the coordinates are relative to the\n image size or are absolute values.\n\n Developed by: Rafael Padilla\n Last modification: Apr 28 2018\n ' EveryPointInterpolation = 1 ElevenPointInterpolation = 2
class CoordinatesType(Enum): '\n Class representing if the coordinates are relative to the\n image size or are absolute values.\n\n Developed by: Rafael Padilla\n Last modification: Apr 28 2018\n ' Relative = 1 Absolute = 2
class BBType(Enum): '\n Class representing if the bounding box is groundtruth or not.\n\n Developed by: Rafael Padilla\n Last modification: May 24 2018\n ' GroundTruth = 1 Detected = 2
class BBFormat(Enum): '\n Class representing the format of a bounding box.\n It can be (X,Y,width,height) => XYWH\n or (X1,Y1,X2,Y2) => XYX2Y2\n\n Developed by: Rafael Padilla\n Last modification: May 24 2018\n ' XYWH = 1 XYX2Y2 = 2
def convertToRelativeValues(size, box): dw = (1.0 / size[0]) dh = (1.0 / size[1]) cx = ((box[1] + box[0]) / 2.0) cy = ((box[3] + box[2]) / 2.0) w = (box[1] - box[0]) h = (box[3] - box[2]) x = (cx * dw) y = (cy * dh) w = (w * dw) h = (h * dh) return (x, y, w, h)
def convertToAbsoluteValues(size, box): xIn = round(((((2 * float(box[0])) - float(box[2])) * size[0]) / 2)) yIn = round(((((2 * float(box[1])) - float(box[3])) * size[1]) / 2)) xEnd = (xIn + round((float(box[2]) * size[0]))) yEnd = (yIn + round((float(box[3]) * size[1]))) if (xIn < 0): xI...
def add_bb_into_image(image, bb, color=(255, 0, 0), thickness=2, label=None): r = int(color[0]) g = int(color[1]) b = int(color[2]) font = cv2.FONT_HERSHEY_SIMPLEX fontScale = 0.5 fontThickness = 1 (x1, y1, x2, y2) = bb.getAbsoluteBoundingBox(BBFormat.XYX2Y2) x1 = int(x1) y1 = int(...
def ValidateFormats(argFormat, argName, errors): if (argFormat == 'xywh'): return BBFormat.XYWH elif (argFormat == 'xyrb'): return BBFormat.XYX2Y2 elif (argFormat is None): return BBFormat.XYWH else: errors.append(("argument %s: invalid value. It must be either 'xywh' o...
def ValidateMandatoryArgs(arg, argName, errors): if (arg is None): errors.append(('argument %s: required argument' % argName)) else: return True
def ValidateImageSize(arg, argName, argInformed, errors): errorMsg = ('argument %s: required argument if %s is relative' % (argName, argInformed)) ret = None if (arg is None): errors.append(errorMsg) else: arg = arg.replace('(', '').replace(')', '') args = arg.split(',') ...
def ValidateCoordinatesTypes(arg, argName, errors): if (arg == 'abs'): return CoordinatesType.Absolute elif (arg == 'rel'): return CoordinatesType.Relative elif (arg is None): return CoordinatesType.Absolute errors.append(("argument %s: invalid value. It must be either 'rel' or...
def ValidatePaths(arg, nameArg, errors): if (arg is None): errors.append(('argument %s: invalid directory' % nameArg)) elif ((os.path.isdir(arg) is False) and (os.path.isdir(os.path.join(currentPath, arg)) is False)): errors.append(("argument %s: directory does not exist '%s'" % (nameArg, arg)...
def getBoundingBoxes(directory, isGT, bbFormat, coordType, allBoundingBoxes=None, allClasses=None, imgSize=(0, 0)): 'Read txt files containing bounding boxes (ground truth and detections).' if (allBoundingBoxes is None): allBoundingBoxes = BoundingBoxes() if (allClasses is None): allClasse...
class DatasetCatalog(object): DATA_DIR = 'data' DATASETS = {'jhmdb_train': {'video_root': 'jhmdb/videos', 'ann_file': 'jhmdb/annotations/jhmdb_train_gt_min.json', 'box_file': '', 'eval_file_paths': {'labelmap_file': ''}, 'object_file': 'jhmdb/annotations/train_object_detection.json', 'keypoints_file': 'jhmdb/...
def build_dataset(cfg, dataset_list, transforms, dataset_catalog, is_train=True, object_transforms=None): '\n Arguments:\n cfg: config object for the experiment.\n dataset_list (list[str]): Contains the names of the datasets, i.e.,\n ava_video_train_v2.2, ava_video_val_v2.2, etc..\n ...
def make_data_sampler(dataset, shuffle, distributed): if distributed: return samplers.DistributedSampler(dataset, shuffle=shuffle) if shuffle: sampler = torch.utils.data.sampler.RandomSampler(dataset) else: sampler = torch.utils.data.sampler.SequentialSampler(dataset) return sa...
def _quantize(x, bins): bins = copy.copy(bins) bins = sorted(bins) quantized = list(map((lambda y: bisect.bisect_right(bins, y)), x)) return quantized
def _compute_aspect_ratios(dataset): aspect_ratios = [] for i in range(len(dataset)): video_info = dataset.get_video_info(i) aspect_ratio = (float(video_info['height']) / float(video_info['width'])) aspect_ratios.append(aspect_ratio) return aspect_ratios
def make_batch_data_sampler(dataset, sampler, aspect_grouping, videos_per_batch, num_iters=None, start_iter=0, drop_last=False): if aspect_grouping: if (not isinstance(aspect_grouping, (list, tuple))): aspect_grouping = [aspect_grouping] aspect_ratios = _compute_aspect_ratios(dataset) ...
def make_data_loader(cfg, is_train=True, is_distributed=False, start_iter=0): num_gpus = get_world_size() if is_train: videos_per_batch = cfg.SOLVER.VIDEOS_PER_BATCH assert ((videos_per_batch % num_gpus) == 0), 'SOLVER.VIDEOS_PER_BATCH ({}) must be divisible by the number ' 'of GPUs ({...
class ConcatDataset(_ConcatDataset): '\n Same as torch.utils.dataset.dataset.ConcatDataset, but exposes an extra\n method for querying the sizes of the image\n ' def get_idxs(self, idx): dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx) if (dataset_idx == 0): ...
def evaluate(dataset, predictions, output_folder, **kwargs): 'evaluate dataset using different methods based on dataset type.\n Args:\n dataset: Dataset object\n predictions(list[BoxList]): each item in the list represents the\n prediction results for one image.\n output_folder:...
def jhmdb_evaluation(dataset, predictions, output_folder, **_): logger = logging.getLogger('hit.inference') logger.info('performing jhmdb evaluation.') return save_jhmdb_results(dataset=dataset, predictions=predictions, output_folder=output_folder, logger=logger)
def _validate_label_map(label_map): 'Checks if a label map is valid.\n\n Args:\n label_map: StringIntLabelMap to validate.\n\n Raises:\n ValueError: if label map is invalid.\n ' for item in label_map.item: if (item.id < 1): raise ValueError('Label map ids should be >= 1.')
def create_category_index(categories): "Creates dictionary of COCO compatible categories keyed by category id.\n\n Args:\n categories: a list of dicts, each of which has the following keys:\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing ...
def get_max_label_map_index(label_map): 'Get maximum index in label map.\n\n Args:\n label_map: a StringIntLabelMapProto\n\n Returns:\n an integer\n ' return max([item.id for item in label_map.item])
def convert_label_map_to_categories(label_map, max_num_classes, use_display_name=True): "Loads label map proto and returns categories list compatible with eval.\n\n This function loads a label map and returns a list of dicts, each of which\n has the following keys:\n 'id': (required) an integer id uniquely i...
def load_labelmap(path): 'Loads label map proto.\n\n Args:\n path: path to StringIntLabelMap proto text file.\n Returns:\n a StringIntLabelMapProto\n ' with open(path, 'r') as fid: label_map_string = fid.read() label_map = string_int_label_map_pb2.StringIntLabelMap() try: ...
def get_label_map_dict(label_map_path, use_display_name=False): "Reads a label map and returns a dictionary of label names to id.\n\n Args:\n label_map_path: path to label_map.\n use_display_name: whether to use the label map items' display names as keys.\n\n Returns:\n A dictionary mapping label names...
def create_category_index_from_labelmap(label_map_path): "Reads a label map and returns a category index.\n\n Args:\n label_map_path: Path to `StringIntLabelMap` proto text file.\n\n Returns:\n A category index, which is a dictionary that maps integer ids to dicts\n containing categories, e.g.\n {1:...
def create_class_agnostic_category_index(): 'Creates a category index with a single `object` class.' return {1: {'id': 1, 'name': 'object'}}
def compute_precision_recall(scores, labels, num_gt): 'Compute precision and recall.\n\n Args:\n scores: A float numpy array representing detection score\n labels: A boolean numpy array representing true/false positive labels\n num_gt: Number of ground truth instances\n\n Raises:\n ValueError: if th...
def compute_average_precision(precision, recall): 'Compute Average Precision according to the definition in VOCdevkit.\n\n Precision is modified to ensure that it does not decrease as recall\n decrease.\n\n Args:\n precision: A float [N, 1] numpy array of precisions\n recall: A float [N, 1] numpy array o...
def compute_cor_loc(num_gt_imgs_per_class, num_images_correctly_detected_per_class): 'Compute CorLoc according to the definition in the following paper.\n\n https://www.robots.ox.ac.uk/~vgg/rg/papers/deselaers-eccv10.pdf\n\n Returns nans if there are no ground truth images for a class.\n\n Args:\n num_gt_im...
class BoxMaskList(np_box_list.BoxList): 'Convenience wrapper for BoxList with masks.\n\n BoxMaskList extends the np_box_list.BoxList to contain masks as well.\n In particular, its constructor receives both boxes and masks. Note that the\n masks correspond to the full image.\n ' def __init__(self, box_dat...
def area(masks): 'Computes area of masks.\n\n Args:\n masks: Numpy array with shape [N, height, width] holding N masks. Masks\n values are of type np.uint8 and values are in {0,1}.\n\n Returns:\n a numpy array with shape [N*1] representing mask areas.\n\n Raises:\n ValueError: If masks.dtype is n...
def intersection(masks1, masks2): 'Compute pairwise intersection areas between masks.\n\n Args:\n masks1: a numpy array with shape [N, height, width] holding N masks. Masks\n values are of type np.uint8 and values are in {0,1}.\n masks2: a numpy array with shape [M, height, width] holding M masks. Mas...
def iou(masks1, masks2): 'Computes pairwise intersection-over-union between mask collections.\n\n Args:\n masks1: a numpy array with shape [N, height, width] holding N masks. Masks\n values are of type np.uint8 and values are in {0,1}.\n masks2: a numpy array with shape [M, height, width] holding N ma...
def ioa(masks1, masks2): "Computes pairwise intersection-over-area between box collections.\n\n Intersection-over-area (ioa) between two masks, mask1 and mask2 is defined as\n their intersection area over mask2's area. Note that ioa is not symmetric,\n that is, IOA(mask1, mask2) != IOA(mask2, mask1).\n\n Args...
class DetectionEvaluator(object): 'Interface for object detection evalution classes.\n\n Example usage of the Evaluator:\n ------------------------------\n evaluator = DetectionEvaluator(categories)\n\n # Detections and groundtruth for image 1.\n evaluator.add_single_groundtruth_image_info(...)\n evaluator....
class ObjectDetectionEvaluator(DetectionEvaluator): 'A class to evaluate detections.' def __init__(self, categories, matching_iou_threshold=0.5, evaluate_corlocs=False, metric_prefix=None, use_weighted_mean_ap=False, evaluate_masks=False): "Constructor.\n\n Args:\n categories: A list of dicts...
class PascalDetectionEvaluator(ObjectDetectionEvaluator): 'A class to evaluate detections using PASCAL metrics.' def __init__(self, categories, matching_iou_threshold=0.5): super(PascalDetectionEvaluator, self).__init__(categories, matching_iou_threshold=matching_iou_threshold, evaluate_corlocs=False...
class WeightedPascalDetectionEvaluator(ObjectDetectionEvaluator): 'A class to evaluate detections using weighted PASCAL metrics.\n\n Weighted PASCAL metrics computes the mean average precision as the average\n precision given the scores and tp_fp_labels of all classes. In comparison,\n PASCAL metrics computes ...
class PascalInstanceSegmentationEvaluator(ObjectDetectionEvaluator): 'A class to evaluate instance masks using PASCAL metrics.' def __init__(self, categories, matching_iou_threshold=0.5): super(PascalInstanceSegmentationEvaluator, self).__init__(categories, matching_iou_threshold=matching_iou_thresho...
class WeightedPascalInstanceSegmentationEvaluator(ObjectDetectionEvaluator): 'A class to evaluate instance masks using weighted PASCAL metrics.\n\n Weighted PASCAL metrics computes the mean average precision as the average\n precision given the scores and tp_fp_labels of all classes. In comparison,\n PASCAL me...
class OpenImagesDetectionEvaluator(ObjectDetectionEvaluator): 'A class to evaluate detections using Open Images V2 metrics.\n\n Open Images V2 introduce group_of type of bounding boxes and this metric\n handles those boxes appropriately.\n ' def __init__(self, categories, matching_iou_threshold=0.5, e...
class ObjectDetectionEvaluation(object): 'Internal implementation of Pascal object detection metrics.' def __init__(self, num_groundtruth_classes, matching_iou_threshold=0.5, nms_iou_threshold=1.0, nms_max_output_boxes=10000, use_weighted_mean_ap=False, label_id_offset=0): if (num_groundtruth_classes...
class InputDataFields(object): 'Names for the input tensors.\n\n Holds the standard dataset field names to use for identifying input tensors. This\n should be used by the decoder to identify keys for the returned tensor_dict\n containing input tensors. And it should be used by the model to identify the\n tens...
class DetectionResultFields(object): 'Naming conventions for storing the output of the detector.\n\n Attributes:\n source_id: source of the original image.\n key: unique key corresponding to image.\n detection_boxes: coordinates of the detection boxes in the image.\n detection_scores: detection score...
class BoxListFields(object): 'Naming conventions for BoxLists.\n\n Attributes:\n boxes: bounding box coordinates.\n classes: classes per bounding box.\n scores: scores per bounding box.\n weights: sample weights per bounding box.\n objectness: objectness score per bounding box.\n masks: masks p...
class TfExampleFields(object): 'TF-example proto feature names for object detection.\n\n Holds the standard feature names to load from an Example proto for object\n detection.\n\n Attributes:\n image_encoded: JPEG encoded string\n image_format: image format, e.g. "JPEG"\n filename: filename\n chann...
class NpInfoDict(object): def __init__(self, info_dict, key_type=None, value_type=None): keys = sorted(list(info_dict.keys())) self.key_arr = np.array(keys, dtype=key_type) self.val_arr = np.array([info_dict[k] for k in keys], dtype=value_type) self._key_idx_map = {k: i for (i, k)...
class NpBoxDict(object): def __init__(self, id_to_box_dict, key_list=None, value_types=[]): (value_fields, value_types) = list(zip(*value_types)) assert ('bbox' in value_fields) if (key_list is None): key_list = sorted(list(id_to_box_dict.keys())) self.length = len(key...
class DatasetEngine(data.Dataset): def __init__(self, video_root, ann_file, remove_clips_without_annotations, frame_span, box_file=None, eval_file_paths={}, box_thresh=0.0, action_thresh=0.0, transforms=None, object_file=None, object_transforms=None, keypoints_file=None): print('loading annotations into ...
class DistributedSampler(Sampler): 'Sampler that restricts dataset loading to a subset of the dataset.\n It is especially useful in conjunction with\n :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each\n process can pass a DistributedSampler instance as a DataLoader sampler,\n and ...
class GroupedBatchSampler(BatchSampler): '\n Wraps another sampler to yield a mini-batch of indices.\n It enforces that elements from the same group should appear in groups of batch_size.\n It also tries to provide mini-batches which follows an ordering which is\n as close as possible to the ordering ...
class IterationBasedBatchSampler(BatchSampler): '\n Wraps a BatchSampler, resampling from it until\n a specified number of iterations have been sampled\n ' def __init__(self, batch_sampler, num_iterations, start_iter=0): self.batch_sampler = batch_sampler self.num_iterations = num_it...
def build_transforms(cfg, is_train=True): if is_train: min_size = cfg.INPUT.MIN_SIZE_TRAIN max_size = cfg.INPUT.MAX_SIZE_TRAIN color_jitter = cfg.INPUT.COLOR_JITTER flip_prob = 0.5 slow_jitter = cfg.INPUT.SLOW_JITTER else: min_size = cfg.INPUT.MIN_SIZE_TEST ...
def build_object_transforms(cfg, is_train=True): if is_train: flip_prob = 0.5 else: flip_prob = 0 transform = OT.Compose([OT.Resize(), OT.PickTop(cfg.MODEL.HIT_STRUCTURE.MAX_OBJECT), OT.RandomHorizontalFlip(flip_prob)]) return transform
def compute_on_dataset_1stage(model, data_loader, device): cpu_device = torch.device('cpu') results_dict = {} if (get_world_size() == 1): extra_args = {} else: rank = get_rank() extra_args = dict(desc='rank {}'.format(rank)) for batch in tqdm(data_loader, **extra_args): ...
def compute_on_dataset_2stage(model, data_loader, device, logger): cpu_device = torch.device('cpu') num_devices = get_world_size() dataset = data_loader.dataset if (num_devices == 1): extra_args = {} else: rank = get_rank() extra_args = dict(desc='rank {}'.format(rank)) ...
def compute_on_dataset(model, data_loader, device, logger, mem_active): model.eval() if mem_active: results_dict = compute_on_dataset_2stage(model, data_loader, device, logger) else: results_dict = compute_on_dataset_1stage(model, data_loader, device) return results_dict
def _accumulate_predictions_from_multiple_gpus(predictions_per_gpu): all_predictions = gather(predictions_per_gpu) if (not is_main_process()): return predictions = {} for p in all_predictions: predictions.update(p) video_ids = list(sorted(predictions.keys())) if (len(video_ids)...
def inference(model, data_loader, dataset_name, mem_active=False, output_folder=None): device = torch.device('cuda') num_devices = get_world_size() logger = logging.getLogger('hit.inference') dataset = data_loader.dataset logger.info('Start evaluation on {} dataset({} videos).'.format(dataset_name...
def do_train(model, data_loader, optimizer, scheduler, checkpointer, device, checkpoint_period, arguments, tblogger, val_period, dataset_names_val, data_loaders_val, distributed, mem_active): logger = logging.getLogger('hit.trainer') logger.info('Start training') meters = MetricLogger(delimiter=' ') ...
def val_in_train(model, dataset_names_val, data_loaders_val, tblogger, iteration, distributed, mem_active): if distributed: model_val = model.module else: model_val = model for (dataset_name, data_loader_val) in zip(dataset_names_val, data_loaders_val): eval_res = inference(model_v...
class _FrozenBatchNorm(nn.Module): def __init__(self, num_features, eps=1e-05, affine=True, track_running_stats=True): super(_FrozenBatchNorm, self).__init__() self.num_features = num_features self.eps = eps self.affine = affine self.track_running_stats = track_running_sta...
class FrozenBatchNorm1d(_FrozenBatchNorm): def _check_input_dim(self, input): if ((input.dim() != 2) and (input.dim() != 3)): raise ValueError('expected 2D or 3D input (got {}D input)'.format(input.dim()))
class FrozenBatchNorm2d(_FrozenBatchNorm): def _check_input_dim(self, input): if (input.dim() != 4): raise ValueError('expected 4D input (got {}D input)'.format(input.dim()))
class FrozenBatchNorm3d(_FrozenBatchNorm): def _check_input_dim(self, input): if (input.dim() != 5): raise ValueError('expected 5D input (got {}D input)'.format(input.dim()))
class _ROIAlign3d(Function): @staticmethod def forward(ctx, input, roi, output_size, spatial_scale, sampling_ratio): ctx.save_for_backward(roi) ctx.output_size = _pair(output_size) ctx.spatial_scale = spatial_scale ctx.sampling_ratio = sampling_ratio ctx.input_shape = ...
class ROIAlign3d(nn.Module): def __init__(self, output_size, spatial_scale, sampling_ratio): super(ROIAlign3d, self).__init__() self.output_size = output_size self.spatial_scale = spatial_scale self.sampling_ratio = sampling_ratio def forward(self, input, rois): retur...
class _ROIPool3d(Function): @staticmethod def forward(ctx, input, roi, output_size, spatial_scale): ctx.output_size = _pair(output_size) ctx.spatial_scale = spatial_scale ctx.input_shape = input.size() (output, argmax) = _C.roi_pool_3d_forward(input, roi, spatial_scale, output...
class ROIPool3d(nn.Module): def __init__(self, output_size, spatial_scale): super(ROIPool3d, self).__init__() self.output_size = output_size self.spatial_scale = spatial_scale def forward(self, input, rois): return roi_pool_3d(input, rois, self.output_size, self.spatial_scale...
class _SigmoidFocalLoss(Function): @staticmethod def forward(ctx, logits, targets, gamma, alpha): ctx.save_for_backward(logits, targets) ctx.gamma = gamma ctx.alpha = alpha losses = _C.sigmoid_focalloss_forward(logits, targets, gamma, alpha) return losses @staticm...
def sigmoid_focal_loss(logits, targets, gamma, alpha, reduction='mean'): assert (reduction in ['none', 'mean', 'sum']), 'Unsupported reduction type "{}"'.format(reduction) logits = logits.float() targets = targets.float() ret = _SigmoidFocalLoss.apply(logits, targets, gamma, alpha) if (reduction !...
class SigmoidFocalLoss(nn.Module): def __init__(self, gamma, alpha, reduction='mean'): super(SigmoidFocalLoss, self).__init__() self.gamma = gamma self.alpha = alpha self.reduction = reduction def forward(self, logits, targets): loss = sigmoid_focal_loss(logits, targe...
class _SoftmaxFocalLoss(Function): @staticmethod def forward(ctx, logits, targets, gamma, alpha): ctx.gamma = gamma ctx.alpha = alpha (losses, P) = _C.softmax_focalloss_forward(logits, targets, gamma, alpha) ctx.save_for_backward(logits, targets, P) return losses ...
def softmax_focal_loss(logits, targets, gamma, alpha, reduction='mean'): assert (reduction in ['none', 'mean', 'sum']), 'Unsupported reduction type "{}"'.format(reduction) logits = logits.float() targets = targets.int() ret = _SoftmaxFocalLoss.apply(logits, targets, gamma, alpha) if (reduction != ...
class SoftmaxFocalLoss(nn.Module): def __init__(self, gamma, alpha, reduction='mean'): super(SoftmaxFocalLoss, self).__init__() self.gamma = gamma self.alpha = alpha self.reduction = reduction def forward(self, logits, targets): loss = softmax_focal_loss(logits, targe...
@registry.BACKBONES.register('Slowfast-Resnet50') @registry.BACKBONES.register('BERT') @registry.BACKBONES.register('Slowfast-Resnet101') def build_slowfast_resnet_backbone(cfg): model = slowfast.SlowFast(cfg) return model
@registry.BACKBONES.register('I3D-Resnet50') @registry.BACKBONES.register('I3D-Resnet101') @registry.BACKBONES.register('I3D-Resnet50-Sparse') @registry.BACKBONES.register('I3D-Resnet101-Sparse') def build_i3d_resnet_backbone(cfg): model = i3d.I3D(cfg) return model
def build_backbone(cfg): assert (cfg.MODEL.BACKBONE.CONV_BODY in registry.BACKBONES), 'cfg.MODEL.BACKBONE.CONV_BODY: {} are not registered in registry'.format(cfg.MODEL.BACKBONE.CONV_BODY) return registry.BACKBONES[cfg.MODEL.BACKBONE.CONV_BODY](cfg)
def get_model_cfg(cfg): backbone_strs = cfg.MODEL.BACKBONE.CONV_BODY.split('-')[1:] error_msg = 'Model backbone {} is not supported.'.format(cfg.MODEL.BACKBONE.CONV_BODY) use_temp_convs_1 = [2] temp_strides_1 = [2] max_pool_stride_1 = 2 use_temp_convs_2 = [1, 1, 1] temp_strides_2 = [1, 1, ...
class I3D(nn.Module): def __init__(self, cfg): super(I3D, self).__init__() self.cfg = cfg.clone() (block_config, use_temp_convs_set, temp_strides_set, pool_strides_set) = get_model_cfg(cfg) conv3_nonlocal = cfg.MODEL.BACKBONE.I3D.CONV3_NONLOCAL conv4_nonlocal = cfg.MODEL.B...
def get_slow_model_cfg(cfg): backbone_strs = cfg.MODEL.BACKBONE.CONV_BODY.split('-')[1:] error_msg = 'Model backbone {} is not supported.'.format(cfg.MODEL.BACKBONE.CONV_BODY) use_temp_convs_1 = [0] temp_strides_1 = [1] max_pool_stride_1 = 1 use_temp_convs_2 = [0, 0, 0] temp_strides_2 = [1...
def get_fast_model_cfg(cfg): backbone_strs = cfg.MODEL.BACKBONE.CONV_BODY.split('-')[1:] error_msg = 'Model backbone {} is not supported.'.format(cfg.MODEL.BACKBONE.CONV_BODY) use_temp_convs_1 = [2] temp_strides_1 = [1] max_pool_stride_1 = 1 use_temp_convs_2 = [1, 1, 1] temp_strides_2 = [1...
class LateralBlock(nn.Module): def __init__(self, conv_dim, alpha): super(LateralBlock, self).__init__() self.conv = nn.Conv3d(conv_dim, (conv_dim * 2), kernel_size=(5, 1, 1), stride=(alpha, 1, 1), padding=(2, 0, 0), bias=True) nn.init.kaiming_normal_(self.conv.weight) nn.init.con...
class FastPath(nn.Module): def __init__(self, cfg): super(FastPath, self).__init__() self.cfg = cfg.clone() (block_config, use_temp_convs_set, temp_strides_set, pool_strides_set) = get_fast_model_cfg(cfg) conv3_nonlocal = cfg.MODEL.BACKBONE.SLOWFAST.FAST.CONV3_NONLOCAL con...
class SlowPath(nn.Module): def __init__(self, cfg): super(SlowPath, self).__init__() self.cfg = cfg.clone() (block_config, use_temp_convs_set, temp_strides_set, pool_strides_set) = get_slow_model_cfg(cfg) conv3_nonlocal = cfg.MODEL.BACKBONE.SLOWFAST.SLOW.CONV3_NONLOCAL con...
class SlowFast(nn.Module): def __init__(self, cfg): super(SlowFast, self).__init__() self.cfg = cfg.clone() if cfg.MODEL.BACKBONE.SLOWFAST.SLOW.ACTIVE: self.slow = SlowPath(cfg) if cfg.MODEL.BACKBONE.SLOWFAST.FAST.ACTIVE: self.fast = FastPath(cfg) i...
class Conv3dBN(nn.Module): def __init__(self, cfg, dim_in, dim_out, kernels, stride, padding, dilation=1, init_weight=None): super(Conv3dBN, self).__init__() self.conv = nn.Conv3d(dim_in, dim_out, kernels, stride=stride, padding=padding, dilation=dilation, bias=False) nn.init.kaiming_norm...
class Bottleneck(nn.Module): def __init__(self, cfg, dim_in, dim_out, dim_inner, stride, dilation=1, use_temp_conv=1, temp_stride=1): super(Bottleneck, self).__init__() self.conv1 = Conv3dBN(cfg, dim_in, dim_inner, ((1 + (use_temp_conv * 2)), 1, 1), stride=(temp_stride, 1, 1), padding=(use_temp_c...
class ResBlock(nn.Module): def __init__(self, cfg, dim_in, dim_out, dim_inner, stride, dilation=1, use_temp_conv=0, temp_stride=1, need_shortcut=False): super(ResBlock, self).__init__() self.btnk = Bottleneck(cfg, dim_in, dim_out, dim_inner=dim_inner, stride=stride, dilation=dilation, use_temp_co...
class ResNLBlock(nn.Module): def __init__(self, cfg, dim_in, dim_out, stride, num_blocks, dim_inner, use_temp_convs, temp_strides, dilation=1, nonlocal_mod=1000, group_nonlocal=False, lateral=False): super(ResNLBlock, self).__init__() self.blocks = [] for idx in range(num_blocks): ...
class ActionDetector(nn.Module): def __init__(self, cfg): super(ActionDetector, self).__init__() self.backbone = build_backbone(cfg) self.roi_heads = build_3d_roi_heads(cfg, self.backbone.dim_out) def forward(self, slow_video, fast_video, boxes, objects=None, keypoints=None, extras={...
def build_detection_model(cfg): return ActionDetector(cfg)
class NLBlock(nn.Module): def __init__(self, dim_in, dim_out, dim_inner, nl_cfg, group=False): super(NLBlock, self).__init__() self.nl_cfg = nl_cfg.clone() self.group = group self.group_size = 4 init_std = nl_cfg.CONV_INIT_STD bias = (not nl_cfg.NO_BIAS) po...
class Pooler3d(nn.Module): def __init__(self, output_size, scale, sampling_ratio=None, pooler_type='align3d'): super(Pooler3d, self).__init__() if (pooler_type == 'align3d'): assert (sampling_ratio is not None), 'Sampling ratio should be specified for 3d roi align.' self.p...
def make_3d_pooler(head_cfg): resolution = head_cfg.POOLER_RESOLUTION scale = head_cfg.POOLER_SCALE sampling_ratio = head_cfg.POOLER_SAMPLING_RATIO pooler_type = head_cfg.POOLER_TYPE pooler = Pooler3d(output_size=(resolution, resolution), scale=scale, sampling_ratio=sampling_ratio, pooler_type=poo...