response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Save a checkpoint. Args: model (model): model to save the weight to the checkpoint. optimizer (optim): optimizer to save the historical state. epoch (int): current number of epoch of the model. cfg (CfgNode): configs to save.
def save_checkpoint(path_to_job, model, optimizer, epoch, cfg): """ Save a checkpoint. Args: model (model): model to save the weight to the checkpoint. optimizer (optim): optimizer to save the historical state. epoch (int): current number of epoch of the model. cfg (CfgNode): configs to save. """ # Save checkpoints only from the master process. if not du.is_master_proc(cfg.NUM_GPUS * cfg.NUM_SHARDS): return # Ensure that the checkpoint dir exists. PathManager.mkdirs(get_checkpoint_dir(path_to_job)) # Omit the DDP wrapper in the multi-gpu setting. sd = model.module.state_dict() if cfg.NUM_GPUS > 1 else model.state_dict() normalized_sd = sub_to_normal_bn(sd) # Record the state. checkpoint = { "epoch": epoch, "model_state": normalized_sd, "optimizer_state": optimizer.state_dict(), "cfg": cfg.dump(), } # Write the checkpoint. path_to_checkpoint = get_path_to_checkpoint(path_to_job, epoch + 1) with PathManager.open(path_to_checkpoint, "wb") as f: torch.save(checkpoint, f) return path_to_checkpoint
Inflate 2D model weights in state_dict_2d to the 3D model weights in state_dict_3d. The details can be found in: Joao Carreira, and Andrew Zisserman. "Quo vadis, action recognition? a new model and the kinetics dataset." Args: state_dict_2d (OrderedDict): a dict of parameters from a 2D model. state_dict_3d (OrderedDict): a dict of parameters from a 3D model. Returns: state_dict_inflated (OrderedDict): a dict of inflated parameters.
def inflate_weight(state_dict_2d, state_dict_3d): """ Inflate 2D model weights in state_dict_2d to the 3D model weights in state_dict_3d. The details can be found in: Joao Carreira, and Andrew Zisserman. "Quo vadis, action recognition? a new model and the kinetics dataset." Args: state_dict_2d (OrderedDict): a dict of parameters from a 2D model. state_dict_3d (OrderedDict): a dict of parameters from a 3D model. Returns: state_dict_inflated (OrderedDict): a dict of inflated parameters. """ state_dict_inflated = OrderedDict() #print(state_dict_2d.keys()) #print('----') #print(state_dict_3d.keys()) for k, v2d in state_dict_2d.items(): assert k in state_dict_3d.keys() v3d = state_dict_3d[k] # Inflate the weight of 2D conv to 3D conv. if len(v2d.shape) == 4 and len(v3d.shape) == 5: logger.info( "Inflate {}: {} -> {}: {}".format(k, v2d.shape, k, v3d.shape) ) # Dimension need to be match. try: assert v2d.shape[-2:] == v3d.shape[-2:] assert v2d.shape[:2] == v3d.shape[:2] v3d = ( v2d.unsqueeze(2).repeat(1, 1, v3d.shape[2], 1, 1) / v3d.shape[2] ) except: ### my modification temp = ( v2d.unsqueeze(2).repeat(1, 1, v3d.shape[2], 1, 1) / v3d.shape[2] ) v3d = torch.zeros(v3d.shape) v3d[:,:v2d.shape[1],:,:,:] = temp #################### elif v2d.shape == v3d.shape: v3d = v2d else: logger.info( "Unexpected {}: {} -|> {}: {}".format( k, v2d.shape, k, v3d.shape ) ) state_dict_inflated[k] = v3d.clone() return state_dict_inflated
Load the checkpoint from the given file. If inflation is True, inflate the 2D Conv weights from the checkpoint to 3D Conv. Args: path_to_checkpoint (string): path to the checkpoint to load. model (model): model to load the weights from the checkpoint. data_parallel (bool): if true, model is wrapped by torch.nn.parallel.DistributedDataParallel. optimizer (optim): optimizer to load the historical state. inflation (bool): if True, inflate the weights from the checkpoint. convert_from_caffe2 (bool): if True, load the model from caffe2 and convert it to pytorch. epoch_reset (bool): if True, reset #train iterations from the checkpoint. clear_name_pattern (string): if given, this (sub)string will be cleared from a layer name if it can be matched. Returns: (int): the number of training epoch of the checkpoint.
def load_checkpoint( path_to_checkpoint, model, data_parallel=True, optimizer=None, inflation=False, convert_from_caffe2=False, epoch_reset=False, clear_name_pattern=(), ): """ Load the checkpoint from the given file. If inflation is True, inflate the 2D Conv weights from the checkpoint to 3D Conv. Args: path_to_checkpoint (string): path to the checkpoint to load. model (model): model to load the weights from the checkpoint. data_parallel (bool): if true, model is wrapped by torch.nn.parallel.DistributedDataParallel. optimizer (optim): optimizer to load the historical state. inflation (bool): if True, inflate the weights from the checkpoint. convert_from_caffe2 (bool): if True, load the model from caffe2 and convert it to pytorch. epoch_reset (bool): if True, reset #train iterations from the checkpoint. clear_name_pattern (string): if given, this (sub)string will be cleared from a layer name if it can be matched. Returns: (int): the number of training epoch of the checkpoint. """ assert PathManager.exists( path_to_checkpoint ), "Checkpoint '{}' not found".format(path_to_checkpoint) logger.info("Loading network weights from {}.".format(path_to_checkpoint)) # Account for the DDP wrapper in the multi-gpu setting. try: ms = model.module if data_parallel else model except: ms = model if convert_from_caffe2: with PathManager.open(path_to_checkpoint, "rb") as f: caffe2_checkpoint = pickle.load(f, encoding="latin1") state_dict = OrderedDict() name_convert_func = get_name_convert_func() for key in caffe2_checkpoint["blobs"].keys(): converted_key = name_convert_func(key) converted_key = c2_normal_to_sub_bn(converted_key, ms.state_dict()) if converted_key in ms.state_dict(): c2_blob_shape = caffe2_checkpoint["blobs"][key].shape model_blob_shape = ms.state_dict()[converted_key].shape # expand shape dims if they differ (eg for converting linear to conv params) if len(c2_blob_shape) < len(model_blob_shape): c2_blob_shape += (1,) * ( len(model_blob_shape) - len(c2_blob_shape) ) caffe2_checkpoint["blobs"][key] = np.reshape( caffe2_checkpoint["blobs"][key], c2_blob_shape ) # Load BN stats to Sub-BN. if ( len(model_blob_shape) == 1 and len(c2_blob_shape) == 1 and model_blob_shape[0] > c2_blob_shape[0] and model_blob_shape[0] % c2_blob_shape[0] == 0 ): caffe2_checkpoint["blobs"][key] = np.concatenate( [caffe2_checkpoint["blobs"][key]] * (model_blob_shape[0] // c2_blob_shape[0]) ) c2_blob_shape = caffe2_checkpoint["blobs"][key].shape if c2_blob_shape == tuple(model_blob_shape): state_dict[converted_key] = torch.tensor( caffe2_checkpoint["blobs"][key] ).clone() logger.info( "{}: {} => {}: {}".format( key, c2_blob_shape, converted_key, tuple(model_blob_shape), ) ) else: logger.warn( "!! {}: {} does not match {}: {}".format( key, c2_blob_shape, converted_key, tuple(model_blob_shape), ) ) else: if not any( prefix in key for prefix in ["momentum", "lr", "model_iter"] ): logger.warn( "!! {}: can not be converted, got {}".format( key, converted_key ) ) diff = set(ms.state_dict()) - set(state_dict) diff = {d for d in diff if "num_batches_tracked" not in d} if len(diff) > 0: logger.warn("Not loaded {}".format(diff)) ms.load_state_dict(state_dict, strict=False) epoch = -1 else: # Load the checkpoint on CPU to avoid GPU mem spike. with PathManager.open(path_to_checkpoint, "rb") as f: checkpoint = torch.load(f, map_location="cpu") try: # if True: model_state_dict_3d = ( model.module.state_dict() if data_parallel else model.state_dict() ) checkpoint["model_state"] = normal_to_sub_bn( checkpoint["model_state"], model_state_dict_3d ) except: model_state_dict_3d = model.state_dict() checkpoint["model_state"] = normal_to_sub_bn( checkpoint["model_state"], model_state_dict_3d ) # except: ####### checkpoint from DEIT # print(checkpoint.keys()) # model_state_dict_3d = model.state_dict() # checkpoint["model_state"] = normal_to_sub_bn( ## checkpoint["model"], model_state_dict_3d # checkpoint, model_state_dict_3d # ) # keys = checkpoint['model_state'].keys() # checkpoint['new_model_state'] = {} # for key in keys: # new_key = 'model.'+key # checkpoint['new_model_state'][new_key] = checkpoint['model_state'][key] # checkpoint['model_state'] = checkpoint['new_model_state'] # del checkpoint['new_model_state'] # # ############ if inflation: # Try to inflate the model. inflated_model_dict = inflate_weight( checkpoint["model_state"], model_state_dict_3d ) ms.load_state_dict(inflated_model_dict, strict=False) else: if clear_name_pattern: for item in clear_name_pattern: model_state_dict_new = OrderedDict() for k in checkpoint["model_state"]: if item in k: k_re = k.replace(item, "") model_state_dict_new[k_re] = checkpoint[ "model_state" ][k] logger.info("renaming: {} -> {}".format(k, k_re)) else: model_state_dict_new[k] = checkpoint["model_state"][ k ] checkpoint["model_state"] = model_state_dict_new pre_train_dict = checkpoint["model_state"] model_dict = ms.state_dict() ############ if 'model.time_embed' in pre_train_dict: k = 'model.time_embed' v = pre_train_dict[k] v = v[0,:,:].unsqueeze(0).transpose(1,2) new_v = F.interpolate(v, size=(model_dict[k].size(1)), mode='nearest') pre_train_dict[k] = new_v.transpose(1,2) ################### # Match pre-trained weights that have same shape as current model. pre_train_dict_match = { k: v for k, v in pre_train_dict.items() if k in model_dict and v.size() == model_dict[k].size() } # print(pre_train_dict.keys()) # print('-------------') # print(model_dict.keys()) # print(pre_train_dict_match) # print(xy) # Weights that do not have match from the pre-trained model. not_load_layers = [ k for k in model_dict.keys() if k not in pre_train_dict_match.keys() ] # Log weights that are not loaded with the pre-trained weights. if not_load_layers: for k in not_load_layers: logger.info("Network weights {} not loaded.".format(k)) # Load pre-trained weights. ms.load_state_dict(pre_train_dict_match, strict=False) epoch = -1 # Load the optimizer state (commonly not done when fine-tuning) if "epoch" in checkpoint.keys() and not epoch_reset: epoch = checkpoint["epoch"] if optimizer: optimizer.load_state_dict(checkpoint["optimizer_state"]) else: epoch = -1 return epoch
Convert the Sub-BN paprameters to normal BN parameters in a state dict. There are two copies of BN layers in a Sub-BN implementation: `bn.bn` and `bn.split_bn`. `bn.split_bn` is used during training and "compute_precise_bn". Before saving or evaluation, its stats are copied to `bn.bn`. We rename `bn.bn` to `bn` and store it to be consistent with normal BN layers. Args: sd (OrderedDict): a dict of parameters whitch might contain Sub-BN parameters. Returns: new_sd (OrderedDict): a dict with Sub-BN parameters reshaped to normal parameters.
def sub_to_normal_bn(sd): """ Convert the Sub-BN paprameters to normal BN parameters in a state dict. There are two copies of BN layers in a Sub-BN implementation: `bn.bn` and `bn.split_bn`. `bn.split_bn` is used during training and "compute_precise_bn". Before saving or evaluation, its stats are copied to `bn.bn`. We rename `bn.bn` to `bn` and store it to be consistent with normal BN layers. Args: sd (OrderedDict): a dict of parameters whitch might contain Sub-BN parameters. Returns: new_sd (OrderedDict): a dict with Sub-BN parameters reshaped to normal parameters. """ new_sd = copy.deepcopy(sd) modifications = [ ("bn.bn.running_mean", "bn.running_mean"), ("bn.bn.running_var", "bn.running_var"), ("bn.split_bn.num_batches_tracked", "bn.num_batches_tracked"), ] to_remove = ["bn.bn.", ".split_bn."] for key in sd: for before, after in modifications: if key.endswith(before): new_key = key.split(before)[0] + after new_sd[new_key] = new_sd.pop(key) for rm in to_remove: if rm in key and key in new_sd: del new_sd[key] for key in new_sd: if key.endswith("bn.weight") or key.endswith("bn.bias"): if len(new_sd[key].size()) == 4: assert all(d == 1 for d in new_sd[key].size()[1:]) new_sd[key] = new_sd[key][:, 0, 0, 0] return new_sd
Convert BN parameters to Sub-BN parameters if model contains Sub-BNs. Args: key (OrderedDict): source dict of parameters. mdoel_key (OrderedDict): target dict of parameters. Returns: new_sd (OrderedDict): converted dict of parameters.
def c2_normal_to_sub_bn(key, model_keys): """ Convert BN parameters to Sub-BN parameters if model contains Sub-BNs. Args: key (OrderedDict): source dict of parameters. mdoel_key (OrderedDict): target dict of parameters. Returns: new_sd (OrderedDict): converted dict of parameters. """ if "bn.running_" in key: if key in model_keys: return key new_key = key.replace("bn.running_", "bn.split_bn.running_") if new_key in model_keys: return new_key else: return key
Convert BN parameters to Sub-BN parameters if model contains Sub-BNs. Args: checkpoint_sd (OrderedDict): source dict of parameters. model_sd (OrderedDict): target dict of parameters. Returns: new_sd (OrderedDict): converted dict of parameters.
def normal_to_sub_bn(checkpoint_sd, model_sd): """ Convert BN parameters to Sub-BN parameters if model contains Sub-BNs. Args: checkpoint_sd (OrderedDict): source dict of parameters. model_sd (OrderedDict): target dict of parameters. Returns: new_sd (OrderedDict): converted dict of parameters. """ for key in model_sd: if key not in checkpoint_sd: if "bn.split_bn." in key: load_key = key.replace("bn.split_bn.", "bn.") bn_key = key.replace("bn.split_bn.", "bn.bn.") checkpoint_sd[key] = checkpoint_sd.pop(load_key) checkpoint_sd[bn_key] = checkpoint_sd[key] for key in model_sd: if key in checkpoint_sd: model_blob_shape = model_sd[key].shape c2_blob_shape = checkpoint_sd[key].shape if ( len(model_blob_shape) == 1 and len(c2_blob_shape) == 1 and model_blob_shape[0] > c2_blob_shape[0] and model_blob_shape[0] % c2_blob_shape[0] == 0 ): before_shape = checkpoint_sd[key].shape checkpoint_sd[key] = torch.cat( [checkpoint_sd[key]] * (model_blob_shape[0] // c2_blob_shape[0]) ) logger.info( "{} {} -> {}".format( key, before_shape, checkpoint_sd[key].shape ) ) return checkpoint_sd
Loading checkpoint logic for testing.
def load_test_checkpoint(cfg, model): """ Loading checkpoint logic for testing. """ # Load a checkpoint to test if applicable. if cfg.TEST.CHECKPOINT_FILE_PATH != "": # If no checkpoint found in MODEL_VIS.CHECKPOINT_FILE_PATH or in the current # checkpoint folder, try to load checkpoint from # TEST.CHECKPOINT_FILE_PATH and test it. load_checkpoint( cfg.TEST.CHECKPOINT_FILE_PATH, model, cfg.NUM_GPUS > 1, None, inflation=False, convert_from_caffe2=cfg.TEST.CHECKPOINT_TYPE == "caffe2", ) elif has_checkpoint(cfg.OUTPUT_DIR): last_checkpoint = get_last_checkpoint(cfg.OUTPUT_DIR) load_checkpoint(last_checkpoint, model, cfg.NUM_GPUS > 1) elif cfg.TRAIN.CHECKPOINT_FILE_PATH != "": # If no checkpoint found in TEST.CHECKPOINT_FILE_PATH or in the current # checkpoint folder, try to load checkpoint from # TRAIN.CHECKPOINT_FILE_PATH and test it. load_checkpoint( cfg.TRAIN.CHECKPOINT_FILE_PATH, model, cfg.NUM_GPUS > 1, None, inflation=False, convert_from_caffe2=cfg.TRAIN.CHECKPOINT_TYPE == "caffe2", ) else: logger.info( "Unknown way of loading checkpoint. Using with random initialization, only for debugging." )
Loading checkpoint logic for training.
def load_train_checkpoint(cfg, model, optimizer): """ Loading checkpoint logic for training. """ if cfg.TRAIN.AUTO_RESUME and has_checkpoint(cfg.OUTPUT_DIR): last_checkpoint = get_last_checkpoint(cfg.OUTPUT_DIR) logger.info("Load from last checkpoint, {}.".format(last_checkpoint)) checkpoint_epoch = load_checkpoint( last_checkpoint, model, cfg.NUM_GPUS > 1, optimizer ) start_epoch = checkpoint_epoch + 1 elif cfg.TRAIN.CHECKPOINT_FILE_PATH != "": logger.info("Load from given checkpoint file.") checkpoint_epoch = load_checkpoint( cfg.TRAIN.CHECKPOINT_FILE_PATH, model, cfg.NUM_GPUS > 1, optimizer, inflation=cfg.TRAIN.CHECKPOINT_INFLATE, convert_from_caffe2=cfg.TRAIN.CHECKPOINT_TYPE == "caffe2", epoch_reset=cfg.TRAIN.CHECKPOINT_EPOCH_RESET, clear_name_pattern=cfg.TRAIN.CHECKPOINT_CLEAR_NAME_PATTERN, ) start_epoch = checkpoint_epoch + 1 else: start_epoch = 0 return start_epoch
All gathers the provided tensors from all processes across machines. Args: tensors (list): tensors to perform all gather across all processes in all machines.
def all_gather(tensors): """ All gathers the provided tensors from all processes across machines. Args: tensors (list): tensors to perform all gather across all processes in all machines. """ gather_list = [] output_tensor = [] world_size = dist.get_world_size() for tensor in tensors: tensor_placeholder = [ torch.ones_like(tensor) for _ in range(world_size) ] dist.all_gather(tensor_placeholder, tensor, async_op=False) gather_list.append(tensor_placeholder) for gathered_tensor in gather_list: output_tensor.append(torch.cat(gathered_tensor, dim=0)) return output_tensor
All reduce the provided tensors from all processes across machines. Args: tensors (list): tensors to perform all reduce across all processes in all machines. average (bool): scales the reduced tensor by the number of overall processes across all machines.
def all_reduce(tensors, average=True): """ All reduce the provided tensors from all processes across machines. Args: tensors (list): tensors to perform all reduce across all processes in all machines. average (bool): scales the reduced tensor by the number of overall processes across all machines. """ for tensor in tensors: dist.all_reduce(tensor, async_op=False) if average: world_size = dist.get_world_size() for tensor in tensors: tensor.mul_(1.0 / world_size) return tensors
Initializes the default process group. Args: local_rank (int): the rank on the current local machine. local_world_size (int): the world size (number of processes running) on the current local machine. shard_id (int): the shard index (machine rank) of the current machine. num_shards (int): number of shards for distributed training. init_method (string): supporting three different methods for initializing process groups: "file": use shared file system to initialize the groups across different processes. "tcp": use tcp address to initialize the groups across different dist_backend (string): backend to use for distributed training. Options includes gloo, mpi and nccl, the details can be found here: https://pytorch.org/docs/stable/distributed.html
def init_process_group( local_rank, local_world_size, shard_id, num_shards, init_method, dist_backend="nccl", ): """ Initializes the default process group. Args: local_rank (int): the rank on the current local machine. local_world_size (int): the world size (number of processes running) on the current local machine. shard_id (int): the shard index (machine rank) of the current machine. num_shards (int): number of shards for distributed training. init_method (string): supporting three different methods for initializing process groups: "file": use shared file system to initialize the groups across different processes. "tcp": use tcp address to initialize the groups across different dist_backend (string): backend to use for distributed training. Options includes gloo, mpi and nccl, the details can be found here: https://pytorch.org/docs/stable/distributed.html """ # Sets the GPU to use. torch.cuda.set_device(local_rank) # Initialize the process group. proc_rank = local_rank + shard_id * local_world_size world_size = local_world_size * num_shards dist.init_process_group( backend=dist_backend, init_method=init_method, world_size=world_size, rank=proc_rank, )
Determines if the current process is the master process.
def is_master_proc(num_gpus=8): """ Determines if the current process is the master process. """ if torch.distributed.is_initialized(): return dist.get_rank() % num_gpus == 0 else: return True
Determines if the current process is the root process.
def is_root_proc(): """ Determines if the current process is the root process. """ if torch.distributed.is_initialized(): return dist.get_rank() == 0 else: return True
Get the size of the world.
def get_world_size(): """ Get the size of the world. """ if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size()
Get the rank of the current process.
def get_rank(): """ Get the rank of the current process. """ if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 return dist.get_rank()
Helper function to synchronize (barrier) among all processes when using distributed training
def synchronize(): """ Helper function to synchronize (barrier) among all processes when using distributed training """ if not dist.is_available(): return if not dist.is_initialized(): return world_size = dist.get_world_size() if world_size == 1: return dist.barrier()
Return a process group based on gloo backend, containing all the ranks The result is cached. Returns: (group): pytorch dist group.
def _get_global_gloo_group(): """ Return a process group based on gloo backend, containing all the ranks The result is cached. Returns: (group): pytorch dist group. """ if dist.get_backend() == "nccl": return dist.new_group(backend="gloo") else: return dist.group.WORLD
Seriialize the tensor to ByteTensor. Note that only `gloo` and `nccl` backend is supported. Args: data (data): data to be serialized. group (group): pytorch dist group. Returns: tensor (ByteTensor): tensor that serialized.
def _serialize_to_tensor(data, group): """ Seriialize the tensor to ByteTensor. Note that only `gloo` and `nccl` backend is supported. Args: data (data): data to be serialized. group (group): pytorch dist group. Returns: tensor (ByteTensor): tensor that serialized. """ backend = dist.get_backend(group) assert backend in ["gloo", "nccl"] device = torch.device("cpu" if backend == "gloo" else "cuda") buffer = pickle.dumps(data) if len(buffer) > 1024 ** 3: logger = logging.getLogger(__name__) logger.warning( "Rank {} trying to all-gather {:.2f} GB of data on device {}".format( get_rank(), len(buffer) / (1024 ** 3), device ) ) storage = torch.ByteStorage.from_buffer(buffer) tensor = torch.ByteTensor(storage).to(device=device) return tensor
Padding all the tensors from different GPUs to the largest ones. Args: tensor (tensor): tensor to pad. group (group): pytorch dist group. Returns: list[int]: size of the tensor, on each rank Tensor: padded tensor that has the max size
def _pad_to_largest_tensor(tensor, group): """ Padding all the tensors from different GPUs to the largest ones. Args: tensor (tensor): tensor to pad. group (group): pytorch dist group. Returns: list[int]: size of the tensor, on each rank Tensor: padded tensor that has the max size """ world_size = dist.get_world_size(group=group) assert ( world_size >= 1 ), "comm.gather/all_gather must be called from ranks within the given group!" local_size = torch.tensor( [tensor.numel()], dtype=torch.int64, device=tensor.device ) size_list = [ torch.zeros([1], dtype=torch.int64, device=tensor.device) for _ in range(world_size) ] dist.all_gather(size_list, local_size, group=group) size_list = [int(size.item()) for size in size_list] max_size = max(size_list) # we pad the tensor because torch all_gather does not support # gathering tensors of different shapes if local_size != max_size: padding = torch.zeros( (max_size - local_size,), dtype=torch.uint8, device=tensor.device ) tensor = torch.cat((tensor, padding), dim=0) return size_list, tensor
Run all_gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: list of data gathered from each rank
def all_gather_unaligned(data, group=None): """ Run all_gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: list of data gathered from each rank """ if get_world_size() == 1: return [data] if group is None: group = _get_global_gloo_group() if dist.get_world_size(group) == 1: return [data] tensor = _serialize_to_tensor(data, group) size_list, tensor = _pad_to_largest_tensor(tensor, group) max_size = max(size_list) # receiving Tensor from all ranks tensor_list = [ torch.empty((max_size,), dtype=torch.uint8, device=tensor.device) for _ in size_list ] dist.all_gather(tensor_list, tensor, group=group) data_list = [] for size, tensor in zip(size_list, tensor_list): buffer = tensor.cpu().numpy().tobytes()[:size] data_list.append(pickle.loads(buffer)) return data_list
Initialize variables needed for distributed training.
def init_distributed_training(cfg): """ Initialize variables needed for distributed training. """ if cfg.NUM_GPUS <= 1: return num_gpus_per_machine = cfg.NUM_GPUS num_machines = dist.get_world_size() // num_gpus_per_machine for i in range(num_machines): ranks_on_i = list( range(i * num_gpus_per_machine, (i + 1) * num_gpus_per_machine) ) pg = dist.new_group(ranks_on_i) if i == cfg.SHARD_ID: global _LOCAL_PROCESS_GROUP _LOCAL_PROCESS_GROUP = pg
Returns: The size of the per-machine process group, i.e. the number of processes per machine.
def get_local_size() -> int: """ Returns: The size of the per-machine process group, i.e. the number of processes per machine. """ if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size(group=_LOCAL_PROCESS_GROUP)
Returns: The rank of the current process within the local (per-machine) process group.
def get_local_rank() -> int: """ Returns: The rank of the current process within the local (per-machine) process group. """ if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 assert _LOCAL_PROCESS_GROUP is not None return dist.get_rank(group=_LOCAL_PROCESS_GROUP)
Suppresses printing from the current process.
def _suppress_print(): """ Suppresses printing from the current process. """ def print_pass(*objects, sep=" ", end="\n", file=sys.stdout, flush=False): pass builtins.print = print_pass
Sets up the logging for multiple processes. Only enable the logging for the master process, and suppress logging for the non-master processes.
def setup_logging(output_dir=None): """ Sets up the logging for multiple processes. Only enable the logging for the master process, and suppress logging for the non-master processes. """ # Set up logging format. _FORMAT = "[%(levelname)s: %(filename)s: %(lineno)4d]: %(message)s" if du.is_master_proc(): # Enable logging for the master process. logging.root.handlers = [] else: # Suppress logging for non-master processes. _suppress_print() logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.propagate = False plain_formatter = logging.Formatter( "[%(asctime)s][%(levelname)s] %(filename)s: %(lineno)3d: %(message)s", datefmt="%m/%d %H:%M:%S", ) if du.is_master_proc(): ch = logging.StreamHandler(stream=sys.stdout) ch.setLevel(logging.DEBUG) ch.setFormatter(plain_formatter) logger.addHandler(ch) if output_dir is not None and du.is_master_proc(du.get_world_size()): filename = os.path.join(output_dir, "stdout.log") fh = logging.StreamHandler(_cached_log_stream(filename)) fh.setLevel(logging.DEBUG) fh.setFormatter(plain_formatter) logger.addHandler(fh)
Retrieve the logger with the specified name or, if name is None, return a logger which is the root logger of the hierarchy. Args: name (string): name of the logger.
def get_logger(name): """ Retrieve the logger with the specified name or, if name is None, return a logger which is the root logger of the hierarchy. Args: name (string): name of the logger. """ return logging.getLogger(name)
Logs json stats. Args: stats (dict): a dictionary of statistical information to log.
def log_json_stats(stats): """ Logs json stats. Args: stats (dict): a dictionary of statistical information to log. """ stats = { k: decimal.Decimal("{:.5f}".format(v)) if isinstance(v, float) else v for k, v in stats.items() } json_stats = simplejson.dumps(stats, sort_keys=True, use_decimal=True) logger = get_logger(__name__) logger.info("json_stats: {:s}".format(json_stats))
Retrieve the learning rate of the current epoch with the option to perform warm up in the beginning of the training stage. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py cur_epoch (float): the number of epoch of the current training stage.
def get_lr_at_epoch(cfg, cur_epoch): """ Retrieve the learning rate of the current epoch with the option to perform warm up in the beginning of the training stage. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py cur_epoch (float): the number of epoch of the current training stage. """ lr = get_lr_func(cfg.SOLVER.LR_POLICY)(cfg, cur_epoch) # Perform warm up. if cur_epoch < cfg.SOLVER.WARMUP_EPOCHS: lr_start = cfg.SOLVER.WARMUP_START_LR lr_end = get_lr_func(cfg.SOLVER.LR_POLICY)( cfg, cfg.SOLVER.WARMUP_EPOCHS ) alpha = (lr_end - lr_start) / cfg.SOLVER.WARMUP_EPOCHS lr = cur_epoch * alpha + lr_start return lr
Retrieve the learning rate to specified values at specified epoch with the cosine learning rate schedule. Details can be found in: Ilya Loshchilov, and Frank Hutter SGDR: Stochastic Gradient Descent With Warm Restarts. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py cur_epoch (float): the number of epoch of the current training stage.
def lr_func_cosine(cfg, cur_epoch): """ Retrieve the learning rate to specified values at specified epoch with the cosine learning rate schedule. Details can be found in: Ilya Loshchilov, and Frank Hutter SGDR: Stochastic Gradient Descent With Warm Restarts. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py cur_epoch (float): the number of epoch of the current training stage. """ assert cfg.SOLVER.COSINE_END_LR < cfg.SOLVER.BASE_LR return ( cfg.SOLVER.COSINE_END_LR + (cfg.SOLVER.BASE_LR - cfg.SOLVER.COSINE_END_LR) * (math.cos(math.pi * cur_epoch / cfg.SOLVER.MAX_EPOCH) + 1.0) * 0.5 )
Retrieve the learning rate to specified values at specified epoch with the steps with relative learning rate schedule. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py cur_epoch (float): the number of epoch of the current training stage.
def lr_func_steps_with_relative_lrs(cfg, cur_epoch): """ Retrieve the learning rate to specified values at specified epoch with the steps with relative learning rate schedule. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py cur_epoch (float): the number of epoch of the current training stage. """ ind = get_step_index(cfg, cur_epoch) return cfg.SOLVER.LRS[ind] * cfg.SOLVER.BASE_LR
Retrieves the lr step index for the given epoch. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py cur_epoch (float): the number of epoch of the current training stage.
def get_step_index(cfg, cur_epoch): """ Retrieves the lr step index for the given epoch. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py cur_epoch (float): the number of epoch of the current training stage. """ steps = cfg.SOLVER.STEPS + [cfg.SOLVER.MAX_EPOCH] for ind, step in enumerate(steps): # NoQA if cur_epoch < step: break return ind - 1
Given the configs, retrieve the specified lr policy function. Args: lr_policy (string): the learning rate policy to use for the job.
def get_lr_func(lr_policy): """ Given the configs, retrieve the specified lr policy function. Args: lr_policy (string): the learning rate policy to use for the job. """ policy = "lr_func_" + lr_policy if policy not in globals(): raise NotImplementedError("Unknown LR policy: {}".format(lr_policy)) else: return globals()[policy]
Compute mAP for multi-label case. Args: preds (numpy tensor): num_examples x num_classes. labels (numpy tensor): num_examples x num_classes. Returns: mean_ap (int): final mAP score.
def get_map(preds, labels): """ Compute mAP for multi-label case. Args: preds (numpy tensor): num_examples x num_classes. labels (numpy tensor): num_examples x num_classes. Returns: mean_ap (int): final mAP score. """ logger.info("Getting mAP for {} examples".format(preds.shape[0])) preds = preds[:, ~(np.all(labels == 0, axis=0))] labels = labels[:, ~(np.all(labels == 0, axis=0))] aps = [0] try: aps = average_precision_score(labels, preds, average=None) except ValueError: print( "Average precision requires a sufficient number of samples \ in a batch which are missing in this sample." ) mean_ap = np.mean(aps) return mean_ap
Given the predictions, labels, and a list of top-k values, compute the number of correct predictions for each top-k value. Args: preds (array): array of predictions. Dimension is batchsize N x ClassNum. labels (array): array of labels. Dimension is batchsize N. ks (list): list of top-k values. For example, ks = [1, 5] correspods to top-1 and top-5. Returns: topks_correct (list): list of numbers, where the `i`-th entry corresponds to the number of top-`ks[i]` correct predictions.
def topks_correct(preds, labels, ks): """ Given the predictions, labels, and a list of top-k values, compute the number of correct predictions for each top-k value. Args: preds (array): array of predictions. Dimension is batchsize N x ClassNum. labels (array): array of labels. Dimension is batchsize N. ks (list): list of top-k values. For example, ks = [1, 5] correspods to top-1 and top-5. Returns: topks_correct (list): list of numbers, where the `i`-th entry corresponds to the number of top-`ks[i]` correct predictions. """ assert preds.size(0) == labels.size( 0 ), "Batch dim of predictions and labels must match" # Find the top max_k predictions for each sample _top_max_k_vals, top_max_k_inds = torch.topk( preds, max(ks), dim=1, largest=True, sorted=True ) # (batch_size, max_k) -> (max_k, batch_size). top_max_k_inds = top_max_k_inds.t() # (batch_size, ) -> (max_k, batch_size). rep_max_k_labels = labels.view(1, -1).expand_as(top_max_k_inds) # (i, j) = 1 if top i-th prediction for the j-th sample is correct. top_max_k_correct = top_max_k_inds.eq(rep_max_k_labels) # Compute the number of topk correct predictions for each k. topks_correct = [top_max_k_correct[:k, :].float().sum() for k in ks] return topks_correct
Computes the top-k error for each k. Args: preds (array): array of predictions. Dimension is N. labels (array): array of labels. Dimension is N. ks (list): list of ks to calculate the top accuracies.
def topk_errors(preds, labels, ks): """ Computes the top-k error for each k. Args: preds (array): array of predictions. Dimension is N. labels (array): array of labels. Dimension is N. ks (list): list of ks to calculate the top accuracies. """ num_topks_correct = topks_correct(preds, labels, ks) return [(1.0 - x / preds.size(0)) * 100.0 for x in num_topks_correct]
Computes the top-k accuracy for each k. Args: preds (array): array of predictions. Dimension is N. labels (array): array of labels. Dimension is N. ks (list): list of ks to calculate the top accuracies.
def topk_accuracies(preds, labels, ks): """ Computes the top-k accuracy for each k. Args: preds (array): array of predictions. Dimension is N. labels (array): array of labels. Dimension is N. ks (list): list of ks to calculate the top accuracies. """ num_topks_correct = topks_correct(preds, labels, ks) return [(x / preds.size(0)) * 100.0 for x in num_topks_correct]
Args: preds: tuple(torch.FloatTensor), each tensor should be of shape [batch_size, class_count], class_count can vary on a per task basis, i.e. outputs[i].shape[1] can be different to outputs[j].shape[j]. labels: tuple(torch.LongTensor), each tensor should be of shape [batch_size] ks: tuple(int), compute accuracy at top-k for the values of k specified in this parameter. Returns: tuple(float), same length at topk with the corresponding accuracy@k in.
def multitask_topks_correct(preds, labels, ks=(1,)): """ Args: preds: tuple(torch.FloatTensor), each tensor should be of shape [batch_size, class_count], class_count can vary on a per task basis, i.e. outputs[i].shape[1] can be different to outputs[j].shape[j]. labels: tuple(torch.LongTensor), each tensor should be of shape [batch_size] ks: tuple(int), compute accuracy at top-k for the values of k specified in this parameter. Returns: tuple(float), same length at topk with the corresponding accuracy@k in. """ max_k = int(np.max(ks)) task_count = len(preds) batch_size = labels[0].size(0) all_correct = torch.zeros(max_k, batch_size).type(torch.ByteTensor) if torch.cuda.is_available(): all_correct = all_correct.cuda() for output, label in zip(preds, labels): _, max_k_idx = output.topk(max_k, dim=1, largest=True, sorted=True) # Flip batch_size, class_count as .view doesn't work on non-contiguous max_k_idx = max_k_idx.t() correct_for_task = max_k_idx.eq(label.view(1, -1).expand_as(max_k_idx)) all_correct.add_(correct_for_task) multitask_topks_correct = [ torch.ge(all_correct[:k].float().sum(0), task_count).float().sum(0) for k in ks ] return multitask_topks_correct
Determine whether the loss is NaN (not a number). Args: loss (loss): loss to check whether is NaN.
def check_nan_losses(loss): """ Determine whether the loss is NaN (not a number). Args: loss (loss): loss to check whether is NaN. """ if math.isnan(loss): raise RuntimeError("ERROR: Got NaN losses {}".format(datetime.now()))
Compute the number of parameters. Args: model (model): model to count the number of parameters.
def params_count(model, ignore_bn=False): """ Compute the number of parameters. Args: model (model): model to count the number of parameters. """ if not ignore_bn: return np.sum([p.numel() for p in model.parameters()]).item() else: count = 0 for m in model.modules(): if not isinstance(m, nn.BatchNorm3d): for p in m.parameters(recurse=False): count += p.numel() return count
Compute the GPU memory usage for the current device (GB).
def gpu_mem_usage(): """ Compute the GPU memory usage for the current device (GB). """ if torch.cuda.is_available(): mem_usage_bytes = torch.cuda.max_memory_allocated() else: mem_usage_bytes = 0 return mem_usage_bytes / 1024 ** 3
Compute the system memory (RAM) usage for the current device (GB). Returns: usage (float): used memory (GB). total (float): total memory (GB).
def cpu_mem_usage(): """ Compute the system memory (RAM) usage for the current device (GB). Returns: usage (float): used memory (GB). total (float): total memory (GB). """ vram = psutil.virtual_memory() usage = (vram.total - vram.available) / 1024 ** 3 total = vram.total / 1024 ** 3 return usage, total
Return a dummy input for model analysis with batch size 1. The input is used for analyzing the model (counting flops and activations etc.). Args: cfg (CfgNode): configs. Details can be found in lib/config/defaults.py use_train_input (bool): if True, return the input for training. Otherwise, return the input for testing. Returns: inputs: the input for model analysis.
def _get_model_analysis_input(cfg, use_train_input): """ Return a dummy input for model analysis with batch size 1. The input is used for analyzing the model (counting flops and activations etc.). Args: cfg (CfgNode): configs. Details can be found in lib/config/defaults.py use_train_input (bool): if True, return the input for training. Otherwise, return the input for testing. Returns: inputs: the input for model analysis. """ rgb_dimension = 3 if use_train_input: input_tensors = torch.rand( rgb_dimension, cfg.DATA.NUM_FRAMES, cfg.DATA.TRAIN_CROP_SIZE, cfg.DATA.TRAIN_CROP_SIZE, ) else: input_tensors = torch.rand( rgb_dimension, cfg.DATA.NUM_FRAMES, cfg.DATA.TEST_CROP_SIZE, cfg.DATA.TEST_CROP_SIZE, ) if not cfg.MODEL.ARCH in ['resformer', 'vit']: model_inputs = pack_pathway_output(cfg, input_tensors) for i in range(len(model_inputs)): model_inputs[i] = model_inputs[i].unsqueeze(0) if cfg.NUM_GPUS: model_inputs[i] = model_inputs[i].cuda(non_blocking=True) else: model_inputs = input_tensors.cuda(non_blocking=True).unsqueeze(0) # If detection is enabled, count flops for one proposal. if cfg.DETECTION.ENABLE: bbox = torch.tensor([[0, 0, 1.0, 0, 1.0]]) if cfg.NUM_GPUS: bbox = bbox.cuda() inputs = (model_inputs, bbox) else: inputs = (model_inputs,) return inputs
Compute statistics for the current model given the config. Args: model (model): model to perform analysis. cfg (CfgNode): configs. Details can be found in lib/config/defaults.py mode (str): Options include `flop` or `activation`. Compute either flop (gflops) or activation count (mega). use_train_input (bool): if True, compute statistics for training. Otherwise, compute statistics for testing. Returns: float: the total number of count of the given model.
def get_model_stats(model, cfg, mode, use_train_input): """ Compute statistics for the current model given the config. Args: model (model): model to perform analysis. cfg (CfgNode): configs. Details can be found in lib/config/defaults.py mode (str): Options include `flop` or `activation`. Compute either flop (gflops) or activation count (mega). use_train_input (bool): if True, compute statistics for training. Otherwise, compute statistics for testing. Returns: float: the total number of count of the given model. """ assert mode in [ "flop", "activation", ], "'{}' not supported for model analysis".format(mode) if mode == "flop": model_stats_fun = flop_count elif mode == "activation": model_stats_fun = activation_count # Set model to evaluation mode for analysis. # Evaluation mode can avoid getting stuck with sync batchnorm. model_mode = model.training model.eval() inputs = _get_model_analysis_input(cfg, use_train_input) count_dict, *_ = model_stats_fun(model, inputs) count = sum(count_dict.values()) model.train(model_mode) return count
Log info, includes number of parameters, gpu usage, gflops and activation count. The model info is computed when the model is in validation mode. Args: model (model): model to log the info. cfg (CfgNode): configs. Details can be found in lib/config/defaults.py use_train_input (bool): if True, log info for training. Otherwise, log info for testing.
def log_model_info(model, cfg, use_train_input=True): """ Log info, includes number of parameters, gpu usage, gflops and activation count. The model info is computed when the model is in validation mode. Args: model (model): model to log the info. cfg (CfgNode): configs. Details can be found in lib/config/defaults.py use_train_input (bool): if True, log info for training. Otherwise, log info for testing. """ logger.info("Model:\n{}".format(model)) logger.info("Params: {:,}".format(params_count(model))) logger.info("Mem: {:,} MB".format(gpu_mem_usage())) logger.info( "Flops: {:,} G".format( get_model_stats(model, cfg, "flop", use_train_input) ) ) logger.info( "Activations: {:,} M".format( get_model_stats(model, cfg, "activation", use_train_input) ) ) logger.info("nvidia-smi") os.system("nvidia-smi")
Determine if the model should be evaluated at the current epoch. Args: cfg (CfgNode): configs. Details can be found in lib/config/defaults.py cur_epoch (int): current epoch. multigrid_schedule (List): schedule for multigrid training.
def is_eval_epoch(cfg, cur_epoch, multigrid_schedule): """ Determine if the model should be evaluated at the current epoch. Args: cfg (CfgNode): configs. Details can be found in lib/config/defaults.py cur_epoch (int): current epoch. multigrid_schedule (List): schedule for multigrid training. """ if cur_epoch + 1 == cfg.SOLVER.MAX_EPOCH: return True if multigrid_schedule is not None: prev_epoch = 0 for s in multigrid_schedule: if cur_epoch < s[-1]: period = max( (s[-1] - prev_epoch) // cfg.MULTIGRID.EVAL_FREQ + 1, 1 ) return (s[-1] - 1 - cur_epoch) % period == 0 prev_epoch = s[-1] return (cur_epoch + 1) % cfg.TRAIN.EVAL_PERIOD == 0
Plot the input tensor with the optional bounding box and save it to disk. Args: tensor (tensor): a tensor with shape of `NxCxHxW`. bboxes (tuple): bounding boxes with format of [[x, y, h, w]]. texts (tuple): a tuple of string to plot. path (str): path to the image to save to.
def plot_input(tensor, bboxes=(), texts=(), path="./tmp_vis.png"): """ Plot the input tensor with the optional bounding box and save it to disk. Args: tensor (tensor): a tensor with shape of `NxCxHxW`. bboxes (tuple): bounding boxes with format of [[x, y, h, w]]. texts (tuple): a tuple of string to plot. path (str): path to the image to save to. """ tensor = tensor.float() tensor = tensor - tensor.min() tensor = tensor / tensor.max() f, ax = plt.subplots(nrows=1, ncols=tensor.shape[0], figsize=(50, 20)) for i in range(tensor.shape[0]): ax[i].axis("off") ax[i].imshow(tensor[i].permute(1, 2, 0)) # ax[1][0].axis('off') if bboxes is not None and len(bboxes) > i: for box in bboxes[i]: x1, y1, x2, y2 = box ax[i].vlines(x1, y1, y2, colors="g", linestyles="solid") ax[i].vlines(x2, y1, y2, colors="g", linestyles="solid") ax[i].hlines(y1, x1, x2, colors="g", linestyles="solid") ax[i].hlines(y2, x1, x2, colors="g", linestyles="solid") if texts is not None and len(texts) > i: ax[i].text(0, 0, texts[i]) f.savefig(path)
Set all the bn layers to eval mode. Args: model (model): model to set bn layers to eval mode.
def frozen_bn_stats(model): """ Set all the bn layers to eval mode. Args: model (model): model to set bn layers to eval mode. """ for m in model.modules(): if isinstance(m, nn.BatchNorm3d): m.eval()
Recursively find all SubBN modules and aggregate sub-BN stats. Args: module (nn.Module) Returns: count (int): number of SubBN module found.
def aggregate_sub_bn_stats(module): """ Recursively find all SubBN modules and aggregate sub-BN stats. Args: module (nn.Module) Returns: count (int): number of SubBN module found. """ count = 0 for child in module.children(): if isinstance(child, SubBatchNorm3d): child.aggregate_stats() count += 1 else: count += aggregate_sub_bn_stats(child) return count
Run 'func' on one or more GPUs, specified in cfg Args: cfg (CfgNode): configs. Details can be found in lib/config/defaults.py init_method (str): initialization method to launch the job with multiple devices. func (function): job to run on GPU(s) daemon (bool): The spawned processes’ daemon flag. If set to True, daemonic processes will be created
def launch_job(cfg, init_method, func, daemon=False): """ Run 'func' on one or more GPUs, specified in cfg Args: cfg (CfgNode): configs. Details can be found in lib/config/defaults.py init_method (str): initialization method to launch the job with multiple devices. func (function): job to run on GPU(s) daemon (bool): The spawned processes’ daemon flag. If set to True, daemonic processes will be created """ if cfg.NUM_GPUS > 1: torch.multiprocessing.spawn( mpu.run, nprocs=cfg.NUM_GPUS, args=( cfg.NUM_GPUS, func, init_method, cfg.SHARD_ID, cfg.NUM_SHARDS, cfg.DIST_BACKEND, cfg, ), daemon=daemon, ) else: func(cfg=cfg)
Read json file with entries {classname: index} and return an array of class names in order. If parent_path is provided, load and map all children to their ids. Args: path (str): path to class ids json file. File must be in the format {"class1": id1, "class2": id2, ...} parent_path (Optional[str]): path to parent-child json file. File must be in the format {"parent1": ["child1", "child2", ...], ...} subset_path (Optional[str]): path to text file containing a subset of class names, separated by newline characters. Returns: class_names (list of strs): list of class names. class_parents (dict): a dictionary where key is the name of the parent class and value is a list of ids of the children classes. subset_ids (list of ints): list of ids of the classes provided in the subset file.
def get_class_names(path, parent_path=None, subset_path=None): """ Read json file with entries {classname: index} and return an array of class names in order. If parent_path is provided, load and map all children to their ids. Args: path (str): path to class ids json file. File must be in the format {"class1": id1, "class2": id2, ...} parent_path (Optional[str]): path to parent-child json file. File must be in the format {"parent1": ["child1", "child2", ...], ...} subset_path (Optional[str]): path to text file containing a subset of class names, separated by newline characters. Returns: class_names (list of strs): list of class names. class_parents (dict): a dictionary where key is the name of the parent class and value is a list of ids of the children classes. subset_ids (list of ints): list of ids of the classes provided in the subset file. """ try: with PathManager.open(path, "r") as f: class2idx = json.load(f) except Exception as err: print("Fail to load file from {} with error {}".format(path, err)) return max_key = max(class2idx.values()) class_names = [None] * (max_key + 1) for k, i in class2idx.items(): class_names[i] = k class_parent = None if parent_path is not None and parent_path != "": try: with PathManager.open(parent_path, "r") as f: d_parent = json.load(f) except EnvironmentError as err: print( "Fail to load file from {} with error {}".format( parent_path, err ) ) return class_parent = {} for parent, children in d_parent.items(): indices = [ class2idx[c] for c in children if class2idx.get(c) is not None ] class_parent[parent] = indices subset_ids = None if subset_path is not None and subset_path != "": try: with PathManager.open(subset_path, "r") as f: subset = f.read().split("\n") subset_ids = [ class2idx[name] for name in subset if class2idx.get(name) is not None ] except EnvironmentError as err: print( "Fail to load file from {} with error {}".format( subset_path, err ) ) return return class_names, class_parent, subset_ids
Log schedule.
def print_schedule(schedule): """ Log schedule. """ logger.info("Long cycle index\tBase shape\tEpochs") for s in schedule: logger.info("{}\t{}\t{}".format(s[0], s[1], s[2]))
Given a schedule and epoch index, return the long cycle base shape. Args: schedule (configs): configs that contains training and multigrid specific hyperparameters. Details can be seen in slowfast/config/defaults.py. cur_epoch (int): current epoch index. Returns: shapes (list): A list describing the base shape in a long cycle: [batch size relative to default, number of frames, spatial dimension].
def get_current_long_cycle_shape(schedule, epoch): """ Given a schedule and epoch index, return the long cycle base shape. Args: schedule (configs): configs that contains training and multigrid specific hyperparameters. Details can be seen in slowfast/config/defaults.py. cur_epoch (int): current epoch index. Returns: shapes (list): A list describing the base shape in a long cycle: [batch size relative to default, number of frames, spatial dimension]. """ for s in schedule: if epoch < s[-1]: return s[1] return schedule[-1][1]
Runs a function from a child process. Args: local_rank (int): rank of the current process on the current machine. num_proc (int): number of processes per machine. func (function): function to execute on each of the process. init_method (string): method to initialize the distributed training. TCP initialization: equiring a network address reachable from all processes followed by the port. Shared file-system initialization: makes use of a file system that is shared and visible from all machines. The URL should start with file:// and contain a path to a non-existent file on a shared file system. shard_id (int): the rank of the current machine. num_shards (int): number of overall machines for the distributed training job. backend (string): three distributed backends ('nccl', 'gloo', 'mpi') are supports, each with different capabilities. Details can be found here: https://pytorch.org/docs/stable/distributed.html cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py output_queue (queue): can optionally be used to return values from the master process.
def run( local_rank, num_proc, func, init_method, shard_id, num_shards, backend, cfg, output_queue=None, ): """ Runs a function from a child process. Args: local_rank (int): rank of the current process on the current machine. num_proc (int): number of processes per machine. func (function): function to execute on each of the process. init_method (string): method to initialize the distributed training. TCP initialization: equiring a network address reachable from all processes followed by the port. Shared file-system initialization: makes use of a file system that is shared and visible from all machines. The URL should start with file:// and contain a path to a non-existent file on a shared file system. shard_id (int): the rank of the current machine. num_shards (int): number of overall machines for the distributed training job. backend (string): three distributed backends ('nccl', 'gloo', 'mpi') are supports, each with different capabilities. Details can be found here: https://pytorch.org/docs/stable/distributed.html cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py output_queue (queue): can optionally be used to return values from the master process. """ # Initialize the process group. world_size = num_proc * num_shards rank = shard_id * num_proc + local_rank try: torch.distributed.init_process_group( backend=backend, init_method=init_method, world_size=world_size, rank=rank, ) except Exception as e: raise e torch.cuda.set_device(local_rank) ret = func(cfg) if output_queue is not None and local_rank == 0: output_queue.put(ret)
Parse the following arguments for a default parser for PySlowFast users. Args: shard_id (int): shard id for the current machine. Starts from 0 to num_shards - 1. If single machine is used, then set shard id to 0. num_shards (int): number of shards using by the job. init_method (str): initialization method to launch the job with multiple devices. Options includes TCP or shared file-system for initialization. details can be find in https://pytorch.org/docs/stable/distributed.html#tcp-initialization cfg (str): path to the config file. opts (argument): provide addtional options from the command line, it overwrites the config loaded from file.
def parse_args(): """ Parse the following arguments for a default parser for PySlowFast users. Args: shard_id (int): shard id for the current machine. Starts from 0 to num_shards - 1. If single machine is used, then set shard id to 0. num_shards (int): number of shards using by the job. init_method (str): initialization method to launch the job with multiple devices. Options includes TCP or shared file-system for initialization. details can be find in https://pytorch.org/docs/stable/distributed.html#tcp-initialization cfg (str): path to the config file. opts (argument): provide addtional options from the command line, it overwrites the config loaded from file. """ parser = argparse.ArgumentParser( description="Provide SlowFast video training and testing pipeline." ) parser.add_argument( "--shard_id", help="The shard id of current node, Starts from 0 to num_shards - 1", default=0, type=int, ) parser.add_argument( "--num_shards", help="Number of shards using by the job", default=1, type=int, ) parser.add_argument( "--init_method", help="Initialization method, includes TCP or shared file-system", default="tcp://localhost:9999", type=str, ) parser.add_argument( "--cfg", dest="cfg_file", help="Path to the config file", default="configs/Kinetics/SLOWFAST_4x16_R50.yaml", type=str, ) parser.add_argument( "opts", help="See slowfast/config/defaults.py for all options", default=None, nargs=argparse.REMAINDER, ) if len(sys.argv) == 1: parser.print_help() return parser.parse_args()
Given the arguemnts, load and initialize the configs. Args: args (argument): arguments includes `shard_id`, `num_shards`, `init_method`, `cfg_file`, and `opts`.
def load_config(args): """ Given the arguemnts, load and initialize the configs. Args: args (argument): arguments includes `shard_id`, `num_shards`, `init_method`, `cfg_file`, and `opts`. """ # Setup cfg. cfg = get_cfg() # Load config from cfg. if args.cfg_file is not None: cfg.merge_from_file(args.cfg_file) # Load config from command line, overwrite config from opts. if args.opts is not None: cfg.merge_from_list(args.opts) # Inherit parameters from args. if hasattr(args, "num_shards") and hasattr(args, "shard_id"): cfg.NUM_SHARDS = args.num_shards cfg.SHARD_ID = args.shard_id if hasattr(args, "rng_seed"): cfg.RNG_SEED = args.rng_seed if hasattr(args, "output_dir"): cfg.OUTPUT_DIR = args.output_dir # Create the checkpoint dir. cu.make_checkpoint_dir(cfg.OUTPUT_DIR) return cfg
Performs ResNet style weight initialization. Args: fc_init_std (float): the expected standard deviation for fc layer. zero_init_final_bn (bool): if True, zero initialize the final bn for every bottleneck.
def init_weights(model, fc_init_std=0.01, zero_init_final_bn=True): """ Performs ResNet style weight initialization. Args: fc_init_std (float): the expected standard deviation for fc layer. zero_init_final_bn (bool): if True, zero initialize the final bn for every bottleneck. """ for m in model.modules(): if isinstance(m, nn.Conv3d): """ Follow the initialization method proposed in: {He, Kaiming, et al. "Delving deep into rectifiers: Surpassing human-level performance on imagenet classification." arXiv preprint arXiv:1502.01852 (2015)} """ c2_msra_fill(m) elif isinstance(m, nn.BatchNorm3d): if ( hasattr(m, "transform_final_bn") and m.transform_final_bn and zero_init_final_bn ): batchnorm_weight = 0.0 else: batchnorm_weight = 1.0 if m.weight is not None: m.weight.data.fill_(batchnorm_weight) if m.bias is not None: m.bias.data.zero_() if isinstance(m, nn.Linear): m.weight.data.normal_(mean=0.0, std=fc_init_std) if m.bias is not None: m.bias.data.zero_()
Checks if a label map is valid. Args: label_map: StringIntLabelMap to validate. Raises: ValueError: if label map is invalid.
def _validate_label_map(label_map): """Checks if a label map is valid. Args: label_map: StringIntLabelMap to validate. Raises: ValueError: if label map is invalid. """ for item in label_map.item: if item.id < 1: raise ValueError("Label map ids should be >= 1.")
Creates dictionary of COCO compatible categories keyed by category id. Args: categories: a list of dicts, each of which has the following keys: 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category name e.g., 'cat', 'dog', 'pizza'. Returns: category_index: a dict containing the same entries as categories, but keyed by the 'id' field of each category.
def create_category_index(categories): """Creates dictionary of COCO compatible categories keyed by category id. Args: categories: a list of dicts, each of which has the following keys: 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category name e.g., 'cat', 'dog', 'pizza'. Returns: category_index: a dict containing the same entries as categories, but keyed by the 'id' field of each category. """ category_index = {} for cat in categories: category_index[cat["id"]] = cat return category_index
Get maximum index in label map. Args: label_map: a StringIntLabelMapProto Returns: an integer
def get_max_label_map_index(label_map): """Get maximum index in label map. Args: label_map: a StringIntLabelMapProto Returns: an integer """ return max([item.id for item in label_map.item])
Loads label map proto and returns categories list compatible with eval. This function loads a label map and returns a list of dicts, each of which has the following keys: 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category name e.g., 'cat', 'dog', 'pizza'. We only allow class into the list if its id-label_id_offset is between 0 (inclusive) and max_num_classes (exclusive). If there are several items mapping to the same id in the label map, we will only keep the first one in the categories list. Args: label_map: a StringIntLabelMapProto or None. If None, a default categories list is created with max_num_classes categories. max_num_classes: maximum number of (consecutive) label indices to include. use_display_name: (boolean) choose whether to load 'display_name' field as category name. If False or if the display_name field does not exist, uses 'name' field as category names instead. Returns: categories: a list of dictionaries representing all possible categories.
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. This function loads a label map and returns a list of dicts, each of which has the following keys: 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category name e.g., 'cat', 'dog', 'pizza'. We only allow class into the list if its id-label_id_offset is between 0 (inclusive) and max_num_classes (exclusive). If there are several items mapping to the same id in the label map, we will only keep the first one in the categories list. Args: label_map: a StringIntLabelMapProto or None. If None, a default categories list is created with max_num_classes categories. max_num_classes: maximum number of (consecutive) label indices to include. use_display_name: (boolean) choose whether to load 'display_name' field as category name. If False or if the display_name field does not exist, uses 'name' field as category names instead. Returns: categories: a list of dictionaries representing all possible categories. """ categories = [] list_of_ids_already_added = [] if not label_map: label_id_offset = 1 for class_id in range(max_num_classes): categories.append( { "id": class_id + label_id_offset, "name": "category_{}".format(class_id + label_id_offset), } ) return categories for item in label_map.item: if not 0 < item.id <= max_num_classes: logging.info( "Ignore item %d since it falls outside of requested " "label range.", item.id, ) continue if use_display_name and item.HasField("display_name"): name = item.display_name else: name = item.name if item.id not in list_of_ids_already_added: list_of_ids_already_added.append(item.id) categories.append({"id": item.id, "name": name}) return categories
Loads label map proto. Args: path: path to StringIntLabelMap proto text file. Returns: a StringIntLabelMapProto
def load_labelmap(path): """Loads label map proto. Args: path: path to StringIntLabelMap proto text file. Returns: a StringIntLabelMapProto """ with open(path, "r") as fid: label_map_string = fid.read() label_map = string_int_label_map_pb2.StringIntLabelMap() try: text_format.Merge(label_map_string, label_map) except text_format.ParseError: label_map.ParseFromString(label_map_string) _validate_label_map(label_map) return label_map
Reads a label map and returns a dictionary of label names to id. Args: label_map_path: path to label_map. use_display_name: whether to use the label map items' display names as keys. Returns: A dictionary mapping label names to id.
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. Args: label_map_path: path to label_map. use_display_name: whether to use the label map items' display names as keys. Returns: A dictionary mapping label names to id. """ label_map = load_labelmap(label_map_path) label_map_dict = {} for item in label_map.item: if use_display_name: label_map_dict[item.display_name] = item.id else: label_map_dict[item.name] = item.id return label_map_dict
Reads a label map and returns a category index. Args: label_map_path: Path to `StringIntLabelMap` proto text file. Returns: A category index, which is a dictionary that maps integer ids to dicts containing categories, e.g. {1: {'id': 1, 'name': 'dog'}, 2: {'id': 2, 'name': 'cat'}, ...}
def create_category_index_from_labelmap(label_map_path): """Reads a label map and returns a category index. Args: label_map_path: Path to `StringIntLabelMap` proto text file. Returns: A category index, which is a dictionary that maps integer ids to dicts containing categories, e.g. {1: {'id': 1, 'name': 'dog'}, 2: {'id': 2, 'name': 'cat'}, ...} """ label_map = load_labelmap(label_map_path) max_num_classes = max(item.id for item in label_map.item) categories = convert_label_map_to_categories(label_map, max_num_classes) return create_category_index(categories)
Creates a category index with a single `object` class.
def create_class_agnostic_category_index(): """Creates a category index with a single `object` class.""" return {1: {"id": 1, "name": "object"}}
Compute precision and recall. Args: scores: A float numpy array representing detection score labels: A boolean numpy array representing true/false positive labels num_gt: Number of ground truth instances Raises: ValueError: if the input is not of the correct format Returns: precision: Fraction of positive instances over detected ones. This value is None if no ground truth labels are present. recall: Fraction of detected positive instance over all positive instances. This value is None if no ground truth labels are present.
def compute_precision_recall(scores, labels, num_gt): """Compute precision and recall. Args: scores: A float numpy array representing detection score labels: A boolean numpy array representing true/false positive labels num_gt: Number of ground truth instances Raises: ValueError: if the input is not of the correct format Returns: precision: Fraction of positive instances over detected ones. This value is None if no ground truth labels are present. recall: Fraction of detected positive instance over all positive instances. This value is None if no ground truth labels are present. """ if ( not isinstance(labels, np.ndarray) or labels.dtype != np.bool or len(labels.shape) != 1 ): raise ValueError("labels must be single dimension bool numpy array") if not isinstance(scores, np.ndarray) or len(scores.shape) != 1: raise ValueError("scores must be single dimension numpy array") if num_gt < np.sum(labels): raise ValueError( "Number of true positives must be smaller than num_gt." ) if len(scores) != len(labels): raise ValueError("scores and labels must be of the same size.") if num_gt == 0: return None, None sorted_indices = np.argsort(scores) sorted_indices = sorted_indices[::-1] labels = labels.astype(int) true_positive_labels = labels[sorted_indices] false_positive_labels = 1 - true_positive_labels cum_true_positives = np.cumsum(true_positive_labels) cum_false_positives = np.cumsum(false_positive_labels) precision = cum_true_positives.astype(float) / ( cum_true_positives + cum_false_positives ) recall = cum_true_positives.astype(float) / num_gt return precision, recall
Compute Average Precision according to the definition in VOCdevkit. Precision is modified to ensure that it does not decrease as recall decrease. Args: precision: A float [N, 1] numpy array of precisions recall: A float [N, 1] numpy array of recalls Raises: ValueError: if the input is not of the correct format Returns: average_precison: The area under the precision recall curve. NaN if precision and recall are None.
def compute_average_precision(precision, recall): """Compute Average Precision according to the definition in VOCdevkit. Precision is modified to ensure that it does not decrease as recall decrease. Args: precision: A float [N, 1] numpy array of precisions recall: A float [N, 1] numpy array of recalls Raises: ValueError: if the input is not of the correct format Returns: average_precison: The area under the precision recall curve. NaN if precision and recall are None. """ if precision is None: if recall is not None: raise ValueError("If precision is None, recall must also be None") return np.NAN if not isinstance(precision, np.ndarray) or not isinstance( recall, np.ndarray ): raise ValueError("precision and recall must be numpy array") if precision.dtype != np.float or recall.dtype != np.float: raise ValueError("input must be float numpy array.") if len(precision) != len(recall): raise ValueError("precision and recall must be of the same size.") if not precision.size: return 0.0 if np.amin(precision) < 0 or np.amax(precision) > 1: raise ValueError("Precision must be in the range of [0, 1].") if np.amin(recall) < 0 or np.amax(recall) > 1: raise ValueError("recall must be in the range of [0, 1].") if not all(recall[i] <= recall[i + 1] for i in range(len(recall) - 1)): raise ValueError("recall must be a non-decreasing array") recall = np.concatenate([[0], recall, [1]]) precision = np.concatenate([[0], precision, [0]]) # Preprocess precision to be a non-decreasing array for i in range(len(precision) - 2, -1, -1): precision[i] = np.maximum(precision[i], precision[i + 1]) indices = np.where(recall[1:] != recall[:-1])[0] + 1 average_precision = np.sum( (recall[indices] - recall[indices - 1]) * precision[indices] ) return average_precision
Compute CorLoc according to the definition in the following paper. https://www.robots.ox.ac.uk/~vgg/rg/papers/deselaers-eccv10.pdf Returns nans if there are no ground truth images for a class. Args: num_gt_imgs_per_class: 1D array, representing number of images containing at least one object instance of a particular class num_images_correctly_detected_per_class: 1D array, representing number of images that are correctly detected at least one object instance of a particular class Returns: corloc_per_class: A float numpy array represents the corloc score of each class
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. https://www.robots.ox.ac.uk/~vgg/rg/papers/deselaers-eccv10.pdf Returns nans if there are no ground truth images for a class. Args: num_gt_imgs_per_class: 1D array, representing number of images containing at least one object instance of a particular class num_images_correctly_detected_per_class: 1D array, representing number of images that are correctly detected at least one object instance of a particular class Returns: corloc_per_class: A float numpy array represents the corloc score of each class """ # Divide by zero expected for classes with no gt examples. with np.errstate(divide="ignore", invalid="ignore"): return np.where( num_gt_imgs_per_class == 0, np.nan, num_images_correctly_detected_per_class / num_gt_imgs_per_class, )
Computes area of boxes. Args: boxlist: BoxList holding N boxes Returns: a numpy array with shape [N*1] representing box areas
def area(boxlist): """Computes area of boxes. Args: boxlist: BoxList holding N boxes Returns: a numpy array with shape [N*1] representing box areas """ y_min, x_min, y_max, x_max = boxlist.get_coordinates() return (y_max - y_min) * (x_max - x_min)
Compute pairwise intersection areas between boxes. Args: boxlist1: BoxList holding N boxes boxlist2: BoxList holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area
def intersection(boxlist1, boxlist2): """Compute pairwise intersection areas between boxes. Args: boxlist1: BoxList holding N boxes boxlist2: BoxList holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area """ return np_box_ops.intersection(boxlist1.get(), boxlist2.get())
Computes pairwise intersection-over-union between box collections. Args: boxlist1: BoxList holding N boxes boxlist2: BoxList holding M boxes Returns: a numpy array with shape [N, M] representing pairwise iou scores.
def iou(boxlist1, boxlist2): """Computes pairwise intersection-over-union between box collections. Args: boxlist1: BoxList holding N boxes boxlist2: BoxList holding M boxes Returns: a numpy array with shape [N, M] representing pairwise iou scores. """ return np_box_ops.iou(boxlist1.get(), boxlist2.get())
Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxlist1: BoxList holding N boxes boxlist2: BoxList holding M boxes Returns: a numpy array with shape [N, M] representing pairwise ioa scores.
def ioa(boxlist1, boxlist2): """Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxlist1: BoxList holding N boxes boxlist2: BoxList holding M boxes Returns: a numpy array with shape [N, M] representing pairwise ioa scores. """ return np_box_ops.ioa(boxlist1.get(), boxlist2.get())
Gather boxes from BoxList according to indices and return new BoxList. By default, gather returns boxes corresponding to the input index list, as well as all additional fields stored in the boxlist (indexing into the first dimension). However one can optionally only gather from a subset of fields. Args: boxlist: BoxList holding N boxes indices: a 1-d numpy array of type int_ fields: (optional) list of fields to also gather from. If None (default), all fields are gathered from. Pass an empty fields list to only gather the box coordinates. Returns: subboxlist: a BoxList corresponding to the subset of the input BoxList specified by indices Raises: ValueError: if specified field is not contained in boxlist or if the indices are not of type int_
def gather(boxlist, indices, fields=None): """Gather boxes from BoxList according to indices and return new BoxList. By default, gather returns boxes corresponding to the input index list, as well as all additional fields stored in the boxlist (indexing into the first dimension). However one can optionally only gather from a subset of fields. Args: boxlist: BoxList holding N boxes indices: a 1-d numpy array of type int_ fields: (optional) list of fields to also gather from. If None (default), all fields are gathered from. Pass an empty fields list to only gather the box coordinates. Returns: subboxlist: a BoxList corresponding to the subset of the input BoxList specified by indices Raises: ValueError: if specified field is not contained in boxlist or if the indices are not of type int_ """ if indices.size: if np.amax(indices) >= boxlist.num_boxes() or np.amin(indices) < 0: raise ValueError("indices are out of valid range.") subboxlist = np_box_list.BoxList(boxlist.get()[indices, :]) if fields is None: fields = boxlist.get_extra_fields() for field in fields: extra_field_data = boxlist.get_field(field) subboxlist.add_field(field, extra_field_data[indices, ...]) return subboxlist
Sort boxes and associated fields according to a scalar field. A common use case is reordering the boxes according to descending scores. Args: boxlist: BoxList holding N boxes. field: A BoxList field for sorting and reordering the BoxList. order: (Optional) 'descend' or 'ascend'. Default is descend. Returns: sorted_boxlist: A sorted BoxList with the field in the specified order. Raises: ValueError: if specified field does not exist or is not of single dimension. ValueError: if the order is not either descend or ascend.
def sort_by_field(boxlist, field, order=SortOrder.DESCEND): """Sort boxes and associated fields according to a scalar field. A common use case is reordering the boxes according to descending scores. Args: boxlist: BoxList holding N boxes. field: A BoxList field for sorting and reordering the BoxList. order: (Optional) 'descend' or 'ascend'. Default is descend. Returns: sorted_boxlist: A sorted BoxList with the field in the specified order. Raises: ValueError: if specified field does not exist or is not of single dimension. ValueError: if the order is not either descend or ascend. """ if not boxlist.has_field(field): raise ValueError("Field " + field + " does not exist") if len(boxlist.get_field(field).shape) != 1: raise ValueError("Field " + field + "should be single dimension.") if order != SortOrder.DESCEND and order != SortOrder.ASCEND: raise ValueError("Invalid sort order") field_to_sort = boxlist.get_field(field) sorted_indices = np.argsort(field_to_sort) if order == SortOrder.DESCEND: sorted_indices = sorted_indices[::-1] return gather(boxlist, sorted_indices)
Non maximum suppression. This op greedily selects a subset of detection bounding boxes, pruning away boxes that have high IOU (intersection over union) overlap (> thresh) with already selected boxes. In each iteration, the detected bounding box with highest score in the available pool is selected. Args: boxlist: BoxList holding N boxes. Must contain a 'scores' field representing detection scores. All scores belong to the same class. max_output_size: maximum number of retained boxes iou_threshold: intersection over union threshold. score_threshold: minimum score threshold. Remove the boxes with scores less than this value. Default value is set to -10. A very low threshold to pass pretty much all the boxes, unless the user sets a different score threshold. Returns: a BoxList holding M boxes where M <= max_output_size Raises: ValueError: if 'scores' field does not exist ValueError: if threshold is not in [0, 1] ValueError: if max_output_size < 0
def non_max_suppression( boxlist, max_output_size=10000, iou_threshold=1.0, score_threshold=-10.0 ): """Non maximum suppression. This op greedily selects a subset of detection bounding boxes, pruning away boxes that have high IOU (intersection over union) overlap (> thresh) with already selected boxes. In each iteration, the detected bounding box with highest score in the available pool is selected. Args: boxlist: BoxList holding N boxes. Must contain a 'scores' field representing detection scores. All scores belong to the same class. max_output_size: maximum number of retained boxes iou_threshold: intersection over union threshold. score_threshold: minimum score threshold. Remove the boxes with scores less than this value. Default value is set to -10. A very low threshold to pass pretty much all the boxes, unless the user sets a different score threshold. Returns: a BoxList holding M boxes where M <= max_output_size Raises: ValueError: if 'scores' field does not exist ValueError: if threshold is not in [0, 1] ValueError: if max_output_size < 0 """ if not boxlist.has_field("scores"): raise ValueError("Field scores does not exist") if iou_threshold < 0.0 or iou_threshold > 1.0: raise ValueError("IOU threshold must be in [0, 1]") if max_output_size < 0: raise ValueError("max_output_size must be bigger than 0.") boxlist = filter_scores_greater_than(boxlist, score_threshold) if boxlist.num_boxes() == 0: return boxlist boxlist = sort_by_field(boxlist, "scores") # Prevent further computation if NMS is disabled. if iou_threshold == 1.0: if boxlist.num_boxes() > max_output_size: selected_indices = np.arange(max_output_size) return gather(boxlist, selected_indices) else: return boxlist boxes = boxlist.get() num_boxes = boxlist.num_boxes() # is_index_valid is True only for all remaining valid boxes, is_index_valid = np.full(num_boxes, 1, dtype=bool) selected_indices = [] num_output = 0 for i in range(num_boxes): if num_output < max_output_size: if is_index_valid[i]: num_output += 1 selected_indices.append(i) is_index_valid[i] = False valid_indices = np.where(is_index_valid)[0] if valid_indices.size == 0: break intersect_over_union = np_box_ops.iou( np.expand_dims(boxes[i, :], axis=0), boxes[valid_indices, :] ) intersect_over_union = np.squeeze(intersect_over_union, axis=0) is_index_valid[valid_indices] = np.logical_and( is_index_valid[valid_indices], intersect_over_union <= iou_threshold, ) return gather(boxlist, np.array(selected_indices))
Multi-class version of non maximum suppression. This op greedily selects a subset of detection bounding boxes, pruning away boxes that have high IOU (intersection over union) overlap (> thresh) with already selected boxes. It operates independently for each class for which scores are provided (via the scores field of the input box_list), pruning boxes with score less than a provided threshold prior to applying NMS. Args: boxlist: BoxList holding N boxes. Must contain a 'scores' field representing detection scores. This scores field is a tensor that can be 1 dimensional (in the case of a single class) or 2-dimensional, which which case we assume that it takes the shape [num_boxes, num_classes]. We further assume that this rank is known statically and that scores.shape[1] is also known (i.e., the number of classes is fixed and known at graph construction time). score_thresh: scalar threshold for score (low scoring boxes are removed). iou_thresh: scalar threshold for IOU (boxes that that high IOU overlap with previously selected boxes are removed). max_output_size: maximum number of retained boxes per class. Returns: a BoxList holding M boxes with a rank-1 scores field representing corresponding scores for each box with scores sorted in decreasing order and a rank-1 classes field representing a class label for each box. Raises: ValueError: if iou_thresh is not in [0, 1] or if input boxlist does not have a valid scores field.
def multi_class_non_max_suppression( boxlist, score_thresh, iou_thresh, max_output_size ): """Multi-class version of non maximum suppression. This op greedily selects a subset of detection bounding boxes, pruning away boxes that have high IOU (intersection over union) overlap (> thresh) with already selected boxes. It operates independently for each class for which scores are provided (via the scores field of the input box_list), pruning boxes with score less than a provided threshold prior to applying NMS. Args: boxlist: BoxList holding N boxes. Must contain a 'scores' field representing detection scores. This scores field is a tensor that can be 1 dimensional (in the case of a single class) or 2-dimensional, which which case we assume that it takes the shape [num_boxes, num_classes]. We further assume that this rank is known statically and that scores.shape[1] is also known (i.e., the number of classes is fixed and known at graph construction time). score_thresh: scalar threshold for score (low scoring boxes are removed). iou_thresh: scalar threshold for IOU (boxes that that high IOU overlap with previously selected boxes are removed). max_output_size: maximum number of retained boxes per class. Returns: a BoxList holding M boxes with a rank-1 scores field representing corresponding scores for each box with scores sorted in decreasing order and a rank-1 classes field representing a class label for each box. Raises: ValueError: if iou_thresh is not in [0, 1] or if input boxlist does not have a valid scores field. """ if not 0 <= iou_thresh <= 1.0: raise ValueError("thresh must be between 0 and 1") if not isinstance(boxlist, np_box_list.BoxList): raise ValueError("boxlist must be a BoxList") if not boxlist.has_field("scores"): raise ValueError("input boxlist must have 'scores' field") scores = boxlist.get_field("scores") if len(scores.shape) == 1: scores = np.reshape(scores, [-1, 1]) elif len(scores.shape) == 2: if scores.shape[1] is None: raise ValueError( "scores field must have statically defined second " "dimension" ) else: raise ValueError("scores field must be of rank 1 or 2") num_boxes = boxlist.num_boxes() num_scores = scores.shape[0] num_classes = scores.shape[1] if num_boxes != num_scores: raise ValueError("Incorrect scores field length: actual vs expected.") selected_boxes_list = [] for class_idx in range(num_classes): boxlist_and_class_scores = np_box_list.BoxList(boxlist.get()) class_scores = np.reshape(scores[0:num_scores, class_idx], [-1]) boxlist_and_class_scores.add_field("scores", class_scores) boxlist_filt = filter_scores_greater_than( boxlist_and_class_scores, score_thresh ) nms_result = non_max_suppression( boxlist_filt, max_output_size=max_output_size, iou_threshold=iou_thresh, score_threshold=score_thresh, ) nms_result.add_field( "classes", np.zeros_like(nms_result.get_field("scores")) + class_idx ) selected_boxes_list.append(nms_result) selected_boxes = concatenate(selected_boxes_list) sorted_boxes = sort_by_field(selected_boxes, "scores") return sorted_boxes
Scale box coordinates in x and y dimensions. Args: boxlist: BoxList holding N boxes y_scale: float x_scale: float Returns: boxlist: BoxList holding N boxes
def scale(boxlist, y_scale, x_scale): """Scale box coordinates in x and y dimensions. Args: boxlist: BoxList holding N boxes y_scale: float x_scale: float Returns: boxlist: BoxList holding N boxes """ y_min, x_min, y_max, x_max = np.array_split(boxlist.get(), 4, axis=1) y_min = y_scale * y_min y_max = y_scale * y_max x_min = x_scale * x_min x_max = x_scale * x_max scaled_boxlist = np_box_list.BoxList( np.hstack([y_min, x_min, y_max, x_max]) ) fields = boxlist.get_extra_fields() for field in fields: extra_field_data = boxlist.get_field(field) scaled_boxlist.add_field(field, extra_field_data) return scaled_boxlist
Clip bounding boxes to a window. This op clips input bounding boxes (represented by bounding box corners) to a window, optionally filtering out boxes that do not overlap at all with the window. Args: boxlist: BoxList holding M_in boxes window: a numpy array of shape [4] representing the [y_min, x_min, y_max, x_max] window to which the op should clip boxes. Returns: a BoxList holding M_out boxes where M_out <= M_in
def clip_to_window(boxlist, window): """Clip bounding boxes to a window. This op clips input bounding boxes (represented by bounding box corners) to a window, optionally filtering out boxes that do not overlap at all with the window. Args: boxlist: BoxList holding M_in boxes window: a numpy array of shape [4] representing the [y_min, x_min, y_max, x_max] window to which the op should clip boxes. Returns: a BoxList holding M_out boxes where M_out <= M_in """ y_min, x_min, y_max, x_max = np.array_split(boxlist.get(), 4, axis=1) win_y_min = window[0] win_x_min = window[1] win_y_max = window[2] win_x_max = window[3] y_min_clipped = np.fmax(np.fmin(y_min, win_y_max), win_y_min) y_max_clipped = np.fmax(np.fmin(y_max, win_y_max), win_y_min) x_min_clipped = np.fmax(np.fmin(x_min, win_x_max), win_x_min) x_max_clipped = np.fmax(np.fmin(x_max, win_x_max), win_x_min) clipped = np_box_list.BoxList( np.hstack([y_min_clipped, x_min_clipped, y_max_clipped, x_max_clipped]) ) clipped = _copy_extra_fields(clipped, boxlist) areas = area(clipped) nonzero_area_indices = np.reshape( np.nonzero(np.greater(areas, 0.0)), [-1] ).astype(np.int32) return gather(clipped, nonzero_area_indices)
Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2. For each box in boxlist1, we want its IOA to be more than minoverlap with at least one of the boxes in boxlist2. If it does not, we remove it. Args: boxlist1: BoxList holding N boxes. boxlist2: BoxList holding M boxes. minoverlap: Minimum required overlap between boxes, to count them as overlapping. Returns: A pruned boxlist with size [N', 4].
def prune_non_overlapping_boxes(boxlist1, boxlist2, minoverlap=0.0): """Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2. For each box in boxlist1, we want its IOA to be more than minoverlap with at least one of the boxes in boxlist2. If it does not, we remove it. Args: boxlist1: BoxList holding N boxes. boxlist2: BoxList holding M boxes. minoverlap: Minimum required overlap between boxes, to count them as overlapping. Returns: A pruned boxlist with size [N', 4]. """ intersection_over_area = ioa(boxlist2, boxlist1) # [M, N] tensor intersection_over_area = np.amax( intersection_over_area, axis=0 ) # [N] tensor keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap)) keep_inds = np.nonzero(keep_bool)[0] new_boxlist1 = gather(boxlist1, keep_inds) return new_boxlist1
Prunes bounding boxes that fall outside a given window. This function prunes bounding boxes that even partially fall outside the given window. See also ClipToWindow which only prunes bounding boxes that fall completely outside the window, and clips any bounding boxes that partially overflow. Args: boxlist: a BoxList holding M_in boxes. window: a numpy array of size 4, representing [ymin, xmin, ymax, xmax] of the window. Returns: pruned_corners: a tensor with shape [M_out, 4] where M_out <= M_in. valid_indices: a tensor with shape [M_out] indexing the valid bounding boxes in the input tensor.
def prune_outside_window(boxlist, window): """Prunes bounding boxes that fall outside a given window. This function prunes bounding boxes that even partially fall outside the given window. See also ClipToWindow which only prunes bounding boxes that fall completely outside the window, and clips any bounding boxes that partially overflow. Args: boxlist: a BoxList holding M_in boxes. window: a numpy array of size 4, representing [ymin, xmin, ymax, xmax] of the window. Returns: pruned_corners: a tensor with shape [M_out, 4] where M_out <= M_in. valid_indices: a tensor with shape [M_out] indexing the valid bounding boxes in the input tensor. """ y_min, x_min, y_max, x_max = np.array_split(boxlist.get(), 4, axis=1) win_y_min = window[0] win_x_min = window[1] win_y_max = window[2] win_x_max = window[3] coordinate_violations = np.hstack( [ np.less(y_min, win_y_min), np.less(x_min, win_x_min), np.greater(y_max, win_y_max), np.greater(x_max, win_x_max), ] ) valid_indices = np.reshape( np.where(np.logical_not(np.max(coordinate_violations, axis=1))), [-1] ) return gather(boxlist, valid_indices), valid_indices
Concatenate list of BoxLists. This op concatenates a list of input BoxLists into a larger BoxList. It also handles concatenation of BoxList fields as long as the field tensor shapes are equal except for the first dimension. Args: boxlists: list of BoxList objects fields: optional list of fields to also concatenate. By default, all fields from the first BoxList in the list are included in the concatenation. Returns: a BoxList with number of boxes equal to sum([boxlist.num_boxes() for boxlist in BoxList]) Raises: ValueError: if boxlists is invalid (i.e., is not a list, is empty, or contains non BoxList objects), or if requested fields are not contained in all boxlists
def concatenate(boxlists, fields=None): """Concatenate list of BoxLists. This op concatenates a list of input BoxLists into a larger BoxList. It also handles concatenation of BoxList fields as long as the field tensor shapes are equal except for the first dimension. Args: boxlists: list of BoxList objects fields: optional list of fields to also concatenate. By default, all fields from the first BoxList in the list are included in the concatenation. Returns: a BoxList with number of boxes equal to sum([boxlist.num_boxes() for boxlist in BoxList]) Raises: ValueError: if boxlists is invalid (i.e., is not a list, is empty, or contains non BoxList objects), or if requested fields are not contained in all boxlists """ if not isinstance(boxlists, list): raise ValueError("boxlists should be a list") if not boxlists: raise ValueError("boxlists should have nonzero length") for boxlist in boxlists: if not isinstance(boxlist, np_box_list.BoxList): raise ValueError( "all elements of boxlists should be BoxList objects" ) concatenated = np_box_list.BoxList( np.vstack([boxlist.get() for boxlist in boxlists]) ) if fields is None: fields = boxlists[0].get_extra_fields() for field in fields: first_field_shape = boxlists[0].get_field(field).shape first_field_shape = first_field_shape[1:] for boxlist in boxlists: if not boxlist.has_field(field): raise ValueError("boxlist must contain all requested fields") field_shape = boxlist.get_field(field).shape field_shape = field_shape[1:] if field_shape != first_field_shape: raise ValueError( "field %s must have same shape for all boxlists " "except for the 0th dimension." % field ) concatenated_field = np.concatenate( [boxlist.get_field(field) for boxlist in boxlists], axis=0 ) concatenated.add_field(field, concatenated_field) return concatenated
Filter to keep only boxes with score exceeding a given threshold. This op keeps the collection of boxes whose corresponding scores are greater than the input threshold. Args: boxlist: BoxList holding N boxes. Must contain a 'scores' field representing detection scores. thresh: scalar threshold Returns: a BoxList holding M boxes where M <= N Raises: ValueError: if boxlist not a BoxList object or if it does not have a scores field
def filter_scores_greater_than(boxlist, thresh): """Filter to keep only boxes with score exceeding a given threshold. This op keeps the collection of boxes whose corresponding scores are greater than the input threshold. Args: boxlist: BoxList holding N boxes. Must contain a 'scores' field representing detection scores. thresh: scalar threshold Returns: a BoxList holding M boxes where M <= N Raises: ValueError: if boxlist not a BoxList object or if it does not have a scores field """ if not isinstance(boxlist, np_box_list.BoxList): raise ValueError("boxlist must be a BoxList") if not boxlist.has_field("scores"): raise ValueError("input boxlist must have 'scores' field") scores = boxlist.get_field("scores") if len(scores.shape) > 2: raise ValueError("Scores should have rank 1 or 2") if len(scores.shape) == 2 and scores.shape[1] != 1: raise ValueError( "Scores should have rank 1 or have shape " "consistent with [None, 1]" ) high_score_indices = np.reshape( np.where(np.greater(scores, thresh)), [-1] ).astype(np.int32) return gather(boxlist, high_score_indices)
Change coordinate frame of the boxlist to be relative to window's frame. Given a window of the form [ymin, xmin, ymax, xmax], changes bounding box coordinates from boxlist to be relative to this window (e.g., the min corner maps to (0,0) and the max corner maps to (1,1)). An example use case is data augmentation: where we are given groundtruth boxes (boxlist) and would like to randomly crop the image to some window (window). In this case we need to change the coordinate frame of each groundtruth box to be relative to this new window. Args: boxlist: A BoxList object holding N boxes. window: a size 4 1-D numpy array. Returns: Returns a BoxList object with N boxes.
def change_coordinate_frame(boxlist, window): """Change coordinate frame of the boxlist to be relative to window's frame. Given a window of the form [ymin, xmin, ymax, xmax], changes bounding box coordinates from boxlist to be relative to this window (e.g., the min corner maps to (0,0) and the max corner maps to (1,1)). An example use case is data augmentation: where we are given groundtruth boxes (boxlist) and would like to randomly crop the image to some window (window). In this case we need to change the coordinate frame of each groundtruth box to be relative to this new window. Args: boxlist: A BoxList object holding N boxes. window: a size 4 1-D numpy array. Returns: Returns a BoxList object with N boxes. """ win_height = window[2] - window[0] win_width = window[3] - window[1] boxlist_new = scale( np_box_list.BoxList( boxlist.get() - [window[0], window[1], window[0], window[1]] ), 1.0 / win_height, 1.0 / win_width, ) _copy_extra_fields(boxlist_new, boxlist) return boxlist_new
Copies the extra fields of boxlist_to_copy_from to boxlist_to_copy_to. Args: boxlist_to_copy_to: BoxList to which extra fields are copied. boxlist_to_copy_from: BoxList from which fields are copied. Returns: boxlist_to_copy_to with extra fields.
def _copy_extra_fields(boxlist_to_copy_to, boxlist_to_copy_from): """Copies the extra fields of boxlist_to_copy_from to boxlist_to_copy_to. Args: boxlist_to_copy_to: BoxList to which extra fields are copied. boxlist_to_copy_from: BoxList from which fields are copied. Returns: boxlist_to_copy_to with extra fields. """ for field in boxlist_to_copy_from.get_extra_fields(): boxlist_to_copy_to.add_field( field, boxlist_to_copy_from.get_field(field) ) return boxlist_to_copy_to
Converts a BoxList containing 'masks' into a BoxMaskList. Args: boxlist: An np_box_list.BoxList object. Returns: An np_box_mask_list.BoxMaskList object. Raises: ValueError: If boxlist does not contain `masks` as a field.
def box_list_to_box_mask_list(boxlist): """Converts a BoxList containing 'masks' into a BoxMaskList. Args: boxlist: An np_box_list.BoxList object. Returns: An np_box_mask_list.BoxMaskList object. Raises: ValueError: If boxlist does not contain `masks` as a field. """ if not boxlist.has_field("masks"): raise ValueError("boxlist does not contain mask field.") box_mask_list = np_box_mask_list.BoxMaskList( box_data=boxlist.get(), mask_data=boxlist.get_field("masks") ) extra_fields = boxlist.get_extra_fields() for key in extra_fields: if key != "masks": box_mask_list.data[key] = boxlist.get_field(key) return box_mask_list
Computes area of masks. Args: box_mask_list: np_box_mask_list.BoxMaskList holding N boxes and masks Returns: a numpy array with shape [N*1] representing mask areas
def area(box_mask_list): """Computes area of masks. Args: box_mask_list: np_box_mask_list.BoxMaskList holding N boxes and masks Returns: a numpy array with shape [N*1] representing mask areas """ return np_mask_ops.area(box_mask_list.get_masks())
Compute pairwise intersection areas between masks. Args: box_mask_list1: BoxMaskList holding N boxes and masks box_mask_list2: BoxMaskList holding M boxes and masks Returns: a numpy array with shape [N*M] representing pairwise intersection area
def intersection(box_mask_list1, box_mask_list2): """Compute pairwise intersection areas between masks. Args: box_mask_list1: BoxMaskList holding N boxes and masks box_mask_list2: BoxMaskList holding M boxes and masks Returns: a numpy array with shape [N*M] representing pairwise intersection area """ return np_mask_ops.intersection( box_mask_list1.get_masks(), box_mask_list2.get_masks() )
Computes pairwise intersection-over-union between box and mask collections. Args: box_mask_list1: BoxMaskList holding N boxes and masks box_mask_list2: BoxMaskList holding M boxes and masks Returns: a numpy array with shape [N, M] representing pairwise iou scores.
def iou(box_mask_list1, box_mask_list2): """Computes pairwise intersection-over-union between box and mask collections. Args: box_mask_list1: BoxMaskList holding N boxes and masks box_mask_list2: BoxMaskList holding M boxes and masks Returns: a numpy array with shape [N, M] representing pairwise iou scores. """ return np_mask_ops.iou( box_mask_list1.get_masks(), box_mask_list2.get_masks() )
Computes pairwise intersection-over-area between box and mask collections. Intersection-over-area (ioa) between two masks mask1 and mask2 is defined as their intersection area over mask2's area. Note that ioa is not symmetric, that is, IOA(mask1, mask2) != IOA(mask2, mask1). Args: box_mask_list1: np_box_mask_list.BoxMaskList holding N boxes and masks box_mask_list2: np_box_mask_list.BoxMaskList holding M boxes and masks Returns: a numpy array with shape [N, M] representing pairwise ioa scores.
def ioa(box_mask_list1, box_mask_list2): """Computes pairwise intersection-over-area between box and mask collections. Intersection-over-area (ioa) between two masks mask1 and mask2 is defined as their intersection area over mask2's area. Note that ioa is not symmetric, that is, IOA(mask1, mask2) != IOA(mask2, mask1). Args: box_mask_list1: np_box_mask_list.BoxMaskList holding N boxes and masks box_mask_list2: np_box_mask_list.BoxMaskList holding M boxes and masks Returns: a numpy array with shape [N, M] representing pairwise ioa scores. """ return np_mask_ops.ioa( box_mask_list1.get_masks(), box_mask_list2.get_masks() )
Gather boxes from np_box_mask_list.BoxMaskList according to indices. By default, gather returns boxes corresponding to the input index list, as well as all additional fields stored in the box_mask_list (indexing into the first dimension). However one can optionally only gather from a subset of fields. Args: box_mask_list: np_box_mask_list.BoxMaskList holding N boxes indices: a 1-d numpy array of type int_ fields: (optional) list of fields to also gather from. If None (default), all fields are gathered from. Pass an empty fields list to only gather the box coordinates. Returns: subbox_mask_list: a np_box_mask_list.BoxMaskList corresponding to the subset of the input box_mask_list specified by indices Raises: ValueError: if specified field is not contained in box_mask_list or if the indices are not of type int_
def gather(box_mask_list, indices, fields=None): """Gather boxes from np_box_mask_list.BoxMaskList according to indices. By default, gather returns boxes corresponding to the input index list, as well as all additional fields stored in the box_mask_list (indexing into the first dimension). However one can optionally only gather from a subset of fields. Args: box_mask_list: np_box_mask_list.BoxMaskList holding N boxes indices: a 1-d numpy array of type int_ fields: (optional) list of fields to also gather from. If None (default), all fields are gathered from. Pass an empty fields list to only gather the box coordinates. Returns: subbox_mask_list: a np_box_mask_list.BoxMaskList corresponding to the subset of the input box_mask_list specified by indices Raises: ValueError: if specified field is not contained in box_mask_list or if the indices are not of type int_ """ if fields is not None: if "masks" not in fields: fields.append("masks") return box_list_to_box_mask_list( np_box_list_ops.gather( boxlist=box_mask_list, indices=indices, fields=fields ) )
Sort boxes and associated fields according to a scalar field. A common use case is reordering the boxes according to descending scores. Args: box_mask_list: BoxMaskList holding N boxes. field: A BoxMaskList field for sorting and reordering the BoxMaskList. order: (Optional) 'descend' or 'ascend'. Default is descend. Returns: sorted_box_mask_list: A sorted BoxMaskList with the field in the specified order.
def sort_by_field( box_mask_list, field, order=np_box_list_ops.SortOrder.DESCEND ): """Sort boxes and associated fields according to a scalar field. A common use case is reordering the boxes according to descending scores. Args: box_mask_list: BoxMaskList holding N boxes. field: A BoxMaskList field for sorting and reordering the BoxMaskList. order: (Optional) 'descend' or 'ascend'. Default is descend. Returns: sorted_box_mask_list: A sorted BoxMaskList with the field in the specified order. """ return box_list_to_box_mask_list( np_box_list_ops.sort_by_field( boxlist=box_mask_list, field=field, order=order ) )
Non maximum suppression. This op greedily selects a subset of detection bounding boxes, pruning away boxes that have high IOU (intersection over union) overlap (> thresh) with already selected boxes. In each iteration, the detected bounding box with highest score in the available pool is selected. Args: box_mask_list: np_box_mask_list.BoxMaskList holding N boxes. Must contain a 'scores' field representing detection scores. All scores belong to the same class. max_output_size: maximum number of retained boxes iou_threshold: intersection over union threshold. score_threshold: minimum score threshold. Remove the boxes with scores less than this value. Default value is set to -10. A very low threshold to pass pretty much all the boxes, unless the user sets a different score threshold. Returns: an np_box_mask_list.BoxMaskList holding M boxes where M <= max_output_size Raises: ValueError: if 'scores' field does not exist ValueError: if threshold is not in [0, 1] ValueError: if max_output_size < 0
def non_max_suppression( box_mask_list, max_output_size=10000, iou_threshold=1.0, score_threshold=-10.0, ): """Non maximum suppression. This op greedily selects a subset of detection bounding boxes, pruning away boxes that have high IOU (intersection over union) overlap (> thresh) with already selected boxes. In each iteration, the detected bounding box with highest score in the available pool is selected. Args: box_mask_list: np_box_mask_list.BoxMaskList holding N boxes. Must contain a 'scores' field representing detection scores. All scores belong to the same class. max_output_size: maximum number of retained boxes iou_threshold: intersection over union threshold. score_threshold: minimum score threshold. Remove the boxes with scores less than this value. Default value is set to -10. A very low threshold to pass pretty much all the boxes, unless the user sets a different score threshold. Returns: an np_box_mask_list.BoxMaskList holding M boxes where M <= max_output_size Raises: ValueError: if 'scores' field does not exist ValueError: if threshold is not in [0, 1] ValueError: if max_output_size < 0 """ if not box_mask_list.has_field("scores"): raise ValueError("Field scores does not exist") if iou_threshold < 0.0 or iou_threshold > 1.0: raise ValueError("IOU threshold must be in [0, 1]") if max_output_size < 0: raise ValueError("max_output_size must be bigger than 0.") box_mask_list = filter_scores_greater_than(box_mask_list, score_threshold) if box_mask_list.num_boxes() == 0: return box_mask_list box_mask_list = sort_by_field(box_mask_list, "scores") # Prevent further computation if NMS is disabled. if iou_threshold == 1.0: if box_mask_list.num_boxes() > max_output_size: selected_indices = np.arange(max_output_size) return gather(box_mask_list, selected_indices) else: return box_mask_list masks = box_mask_list.get_masks() num_masks = box_mask_list.num_boxes() # is_index_valid is True only for all remaining valid boxes, is_index_valid = np.full(num_masks, 1, dtype=bool) selected_indices = [] num_output = 0 for i in range(num_masks): if num_output < max_output_size: if is_index_valid[i]: num_output += 1 selected_indices.append(i) is_index_valid[i] = False valid_indices = np.where(is_index_valid)[0] if valid_indices.size == 0: break intersect_over_union = np_mask_ops.iou( np.expand_dims(masks[i], axis=0), masks[valid_indices] ) intersect_over_union = np.squeeze(intersect_over_union, axis=0) is_index_valid[valid_indices] = np.logical_and( is_index_valid[valid_indices], intersect_over_union <= iou_threshold, ) return gather(box_mask_list, np.array(selected_indices))
Multi-class version of non maximum suppression. This op greedily selects a subset of detection bounding boxes, pruning away boxes that have high IOU (intersection over union) overlap (> thresh) with already selected boxes. It operates independently for each class for which scores are provided (via the scores field of the input box_list), pruning boxes with score less than a provided threshold prior to applying NMS. Args: box_mask_list: np_box_mask_list.BoxMaskList holding N boxes. Must contain a 'scores' field representing detection scores. This scores field is a tensor that can be 1 dimensional (in the case of a single class) or 2-dimensional, in which case we assume that it takes the shape [num_boxes, num_classes]. We further assume that this rank is known statically and that scores.shape[1] is also known (i.e., the number of classes is fixed and known at graph construction time). score_thresh: scalar threshold for score (low scoring boxes are removed). iou_thresh: scalar threshold for IOU (boxes that that high IOU overlap with previously selected boxes are removed). max_output_size: maximum number of retained boxes per class. Returns: a box_mask_list holding M boxes with a rank-1 scores field representing corresponding scores for each box with scores sorted in decreasing order and a rank-1 classes field representing a class label for each box. Raises: ValueError: if iou_thresh is not in [0, 1] or if input box_mask_list does not have a valid scores field.
def multi_class_non_max_suppression( box_mask_list, score_thresh, iou_thresh, max_output_size ): """Multi-class version of non maximum suppression. This op greedily selects a subset of detection bounding boxes, pruning away boxes that have high IOU (intersection over union) overlap (> thresh) with already selected boxes. It operates independently for each class for which scores are provided (via the scores field of the input box_list), pruning boxes with score less than a provided threshold prior to applying NMS. Args: box_mask_list: np_box_mask_list.BoxMaskList holding N boxes. Must contain a 'scores' field representing detection scores. This scores field is a tensor that can be 1 dimensional (in the case of a single class) or 2-dimensional, in which case we assume that it takes the shape [num_boxes, num_classes]. We further assume that this rank is known statically and that scores.shape[1] is also known (i.e., the number of classes is fixed and known at graph construction time). score_thresh: scalar threshold for score (low scoring boxes are removed). iou_thresh: scalar threshold for IOU (boxes that that high IOU overlap with previously selected boxes are removed). max_output_size: maximum number of retained boxes per class. Returns: a box_mask_list holding M boxes with a rank-1 scores field representing corresponding scores for each box with scores sorted in decreasing order and a rank-1 classes field representing a class label for each box. Raises: ValueError: if iou_thresh is not in [0, 1] or if input box_mask_list does not have a valid scores field. """ if not 0 <= iou_thresh <= 1.0: raise ValueError("thresh must be between 0 and 1") if not isinstance(box_mask_list, np_box_mask_list.BoxMaskList): raise ValueError("box_mask_list must be a box_mask_list") if not box_mask_list.has_field("scores"): raise ValueError("input box_mask_list must have 'scores' field") scores = box_mask_list.get_field("scores") if len(scores.shape) == 1: scores = np.reshape(scores, [-1, 1]) elif len(scores.shape) == 2: if scores.shape[1] is None: raise ValueError( "scores field must have statically defined second " "dimension" ) else: raise ValueError("scores field must be of rank 1 or 2") num_boxes = box_mask_list.num_boxes() num_scores = scores.shape[0] num_classes = scores.shape[1] if num_boxes != num_scores: raise ValueError("Incorrect scores field length: actual vs expected.") selected_boxes_list = [] for class_idx in range(num_classes): box_mask_list_and_class_scores = np_box_mask_list.BoxMaskList( box_data=box_mask_list.get(), mask_data=box_mask_list.get_masks() ) class_scores = np.reshape(scores[0:num_scores, class_idx], [-1]) box_mask_list_and_class_scores.add_field("scores", class_scores) box_mask_list_filt = filter_scores_greater_than( box_mask_list_and_class_scores, score_thresh ) nms_result = non_max_suppression( box_mask_list_filt, max_output_size=max_output_size, iou_threshold=iou_thresh, score_threshold=score_thresh, ) nms_result.add_field( "classes", np.zeros_like(nms_result.get_field("scores")) + class_idx ) selected_boxes_list.append(nms_result) selected_boxes = np_box_list_ops.concatenate(selected_boxes_list) sorted_boxes = np_box_list_ops.sort_by_field(selected_boxes, "scores") return box_list_to_box_mask_list(boxlist=sorted_boxes)
Prunes the boxes in list1 that overlap less than thresh with list2. For each mask in box_mask_list1, we want its IOA to be more than minoverlap with at least one of the masks in box_mask_list2. If it does not, we remove it. If the masks are not full size image, we do the pruning based on boxes. Args: box_mask_list1: np_box_mask_list.BoxMaskList holding N boxes and masks. box_mask_list2: np_box_mask_list.BoxMaskList holding M boxes and masks. minoverlap: Minimum required overlap between boxes, to count them as overlapping. Returns: A pruned box_mask_list with size [N', 4].
def prune_non_overlapping_masks(box_mask_list1, box_mask_list2, minoverlap=0.0): """Prunes the boxes in list1 that overlap less than thresh with list2. For each mask in box_mask_list1, we want its IOA to be more than minoverlap with at least one of the masks in box_mask_list2. If it does not, we remove it. If the masks are not full size image, we do the pruning based on boxes. Args: box_mask_list1: np_box_mask_list.BoxMaskList holding N boxes and masks. box_mask_list2: np_box_mask_list.BoxMaskList holding M boxes and masks. minoverlap: Minimum required overlap between boxes, to count them as overlapping. Returns: A pruned box_mask_list with size [N', 4]. """ intersection_over_area = ioa( box_mask_list2, box_mask_list1 ) # [M, N] tensor intersection_over_area = np.amax( intersection_over_area, axis=0 ) # [N] tensor keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap)) keep_inds = np.nonzero(keep_bool)[0] new_box_mask_list1 = gather(box_mask_list1, keep_inds) return new_box_mask_list1
Concatenate list of box_mask_lists. This op concatenates a list of input box_mask_lists into a larger box_mask_list. It also handles concatenation of box_mask_list fields as long as the field tensor shapes are equal except for the first dimension. Args: box_mask_lists: list of np_box_mask_list.BoxMaskList objects fields: optional list of fields to also concatenate. By default, all fields from the first BoxMaskList in the list are included in the concatenation. Returns: a box_mask_list with number of boxes equal to sum([box_mask_list.num_boxes() for box_mask_list in box_mask_list]) Raises: ValueError: if box_mask_lists is invalid (i.e., is not a list, is empty, or contains non box_mask_list objects), or if requested fields are not contained in all box_mask_lists
def concatenate(box_mask_lists, fields=None): """Concatenate list of box_mask_lists. This op concatenates a list of input box_mask_lists into a larger box_mask_list. It also handles concatenation of box_mask_list fields as long as the field tensor shapes are equal except for the first dimension. Args: box_mask_lists: list of np_box_mask_list.BoxMaskList objects fields: optional list of fields to also concatenate. By default, all fields from the first BoxMaskList in the list are included in the concatenation. Returns: a box_mask_list with number of boxes equal to sum([box_mask_list.num_boxes() for box_mask_list in box_mask_list]) Raises: ValueError: if box_mask_lists is invalid (i.e., is not a list, is empty, or contains non box_mask_list objects), or if requested fields are not contained in all box_mask_lists """ if fields is not None: if "masks" not in fields: fields.append("masks") return box_list_to_box_mask_list( np_box_list_ops.concatenate(boxlists=box_mask_lists, fields=fields) )
Filter to keep only boxes and masks with score exceeding a given threshold. This op keeps the collection of boxes and masks whose corresponding scores are greater than the input threshold. Args: box_mask_list: BoxMaskList holding N boxes and masks. Must contain a 'scores' field representing detection scores. thresh: scalar threshold Returns: a BoxMaskList holding M boxes and masks where M <= N Raises: ValueError: if box_mask_list not a np_box_mask_list.BoxMaskList object or if it does not have a scores field
def filter_scores_greater_than(box_mask_list, thresh): """Filter to keep only boxes and masks with score exceeding a given threshold. This op keeps the collection of boxes and masks whose corresponding scores are greater than the input threshold. Args: box_mask_list: BoxMaskList holding N boxes and masks. Must contain a 'scores' field representing detection scores. thresh: scalar threshold Returns: a BoxMaskList holding M boxes and masks where M <= N Raises: ValueError: if box_mask_list not a np_box_mask_list.BoxMaskList object or if it does not have a scores field """ if not isinstance(box_mask_list, np_box_mask_list.BoxMaskList): raise ValueError("box_mask_list must be a BoxMaskList") if not box_mask_list.has_field("scores"): raise ValueError("input box_mask_list must have 'scores' field") scores = box_mask_list.get_field("scores") if len(scores.shape) > 2: raise ValueError("Scores should have rank 1 or 2") if len(scores.shape) == 2 and scores.shape[1] != 1: raise ValueError( "Scores should have rank 1 or have shape " "consistent with [None, 1]" ) high_score_indices = np.reshape( np.where(np.greater(scores, thresh)), [-1] ).astype(np.int32) return gather(box_mask_list, high_score_indices)
Computes area of boxes. Args: boxes: Numpy array with shape [N, 4] holding N boxes Returns: a numpy array with shape [N*1] representing box areas
def area(boxes): """Computes area of boxes. Args: boxes: Numpy array with shape [N, 4] holding N boxes Returns: a numpy array with shape [N*1] representing box areas """ return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
Compute pairwise intersection areas between boxes. Args: boxes1: a numpy array with shape [N, 4] holding N boxes boxes2: a numpy array with shape [M, 4] holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area
def intersection(boxes1, boxes2): """Compute pairwise intersection areas between boxes. Args: boxes1: a numpy array with shape [N, 4] holding N boxes boxes2: a numpy array with shape [M, 4] holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area """ [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), 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), all_pairs_min_xmax - all_pairs_max_xmin, ) return intersect_heights * intersect_widths
Computes pairwise intersection-over-union between box collections. Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding N boxes. Returns: a numpy array with shape [N, M] representing pairwise iou scores.
def iou(boxes1, boxes2): """Computes pairwise intersection-over-union between box collections. Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding N boxes. Returns: a numpy array with shape [N, M] representing pairwise iou scores. """ 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-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding N boxes. Returns: a numpy array with shape [N, M] representing pairwise ioa scores.
def ioa(boxes1, boxes2): """Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding N boxes. Returns: a numpy array with shape [N, M] representing pairwise ioa scores. """ intersect = intersection(boxes1, boxes2) areas = np.expand_dims(area(boxes2), axis=0) return intersect / areas
Computes area of masks. Args: masks: Numpy array with shape [N, height, width] holding N masks. Masks values are of type np.uint8 and values are in {0,1}. Returns: a numpy array with shape [N*1] representing mask areas. Raises: ValueError: If masks.dtype is not np.uint8
def area(masks): """Computes area of masks. Args: masks: Numpy array with shape [N, height, width] holding N masks. Masks values are of type np.uint8 and values are in {0,1}. Returns: a numpy array with shape [N*1] representing mask areas. Raises: ValueError: If masks.dtype is not np.uint8 """ if masks.dtype != np.uint8: raise ValueError("Masks type should be np.uint8") return np.sum(masks, axis=(1, 2), dtype=np.float32)