code
stringlengths
17
6.64M
def mask_rcnn_fcn_head_v1up(dim_in, roi_xform_func, spatial_scale): 'v1up design: 2 * (conv 3x3), convT 2x2.' return mask_rcnn_fcn_head_v1upXconvs(dim_in, roi_xform_func, spatial_scale, 2)
class mask_rcnn_fcn_head_v1upXconvs(nn.Module): 'v1upXconvs design: X * (conv 3x3), convT 2x2.' def __init__(self, dim_in, roi_xform_func, spatial_scale, num_convs): super().__init__() self.dim_in = dim_in self.roi_xform = roi_xform_func self.spatial_scale = spatial_scale ...
class mask_rcnn_fcn_head_v1upXconvs_gn(nn.Module): 'v1upXconvs design: X * (conv 3x3), convT 2x2, with GroupNorm' def __init__(self, dim_in, roi_xform_func, spatial_scale, num_convs): super().__init__() self.dim_in = dim_in self.roi_xform = roi_xform_func self.spatial_scale = ...
class mask_rcnn_fcn_head_v0upshare(nn.Module): 'Use a ResNet "conv5" / "stage5" head for mask prediction. Weights and\n computation are shared with the conv5 box head. Computation can only be\n shared during training, since inference is cascaded.\n\n v0upshare design: conv5, convT 2x2.\n ' def __...
class mask_rcnn_fcn_head_v0up(nn.Module): 'v0up design: conv5, deconv 2x2 (no weight sharing with the box head).' def __init__(self, dim_in, roi_xform_func, spatial_scale): super().__init__() self.dim_in = dim_in self.roi_xform = roi_xform_func self.spatial_scale = spatial_sca...
def ResNet_roi_conv5_head_for_masks(dim_in): 'ResNet "conv5" / "stage5" head for predicting masks.' dilation = cfg.MRCNN.DILATION stride_init = (cfg.MRCNN.ROI_XFORM_RESOLUTION // 7) (module, dim_out) = ResNet.add_stage(dim_in, 2048, 512, 3, dilation, stride_init) return (module, dim_out)
def _import_symbols(locals): for symbol in dir(_lib): fn = getattr(_lib, symbol) if callable(fn): locals[symbol] = _wrap_function(fn, _ffi) else: locals[symbol] = fn __all__.append(symbol)
class RoIAlignFunction(Function): def __init__(self, aligned_height, aligned_width, spatial_scale, sampling_ratio): self.aligned_width = int(aligned_width) self.aligned_height = int(aligned_height) self.spatial_scale = float(spatial_scale) self.sampling_ratio = int(sampling_ratio)...
class RoIAlign(Module): def __init__(self, aligned_height, aligned_width, spatial_scale, sampling_ratio): super(RoIAlign, self).__init__() self.aligned_width = int(aligned_width) self.aligned_height = int(aligned_height) self.spatial_scale = float(spatial_scale) self.sampl...
class RoIAlignAvg(Module): def __init__(self, aligned_height, aligned_width, spatial_scale, sampling_ratio): super(RoIAlignAvg, self).__init__() self.aligned_width = int(aligned_width) self.aligned_height = int(aligned_height) self.spatial_scale = float(spatial_scale) self...
class RoIAlignMax(Module): def __init__(self, aligned_height, aligned_width, spatial_scale, sampling_ratio): super(RoIAlignMax, self).__init__() self.aligned_width = int(aligned_width) self.aligned_height = int(aligned_height) self.spatial_scale = float(spatial_scale) self...
def group_norm(x, num_groups, weight=None, bias=None, eps=1e-05): input_shape = x.shape ndim = len(input_shape) (N, C) = input_shape[:2] G = num_groups assert ((C % G) == 0), 'input channel dimension must divisible by number of groups' x = x.view(N, G, (- 1)) mean = x.mean((- 1), keepdim=T...
def XavierFill(tensor): 'Caffe2 XavierFill Implementation' size = reduce(operator.mul, tensor.shape, 1) fan_in = (size / tensor.shape[0]) scale = math.sqrt((3 / fan_in)) return init.uniform_(tensor, (- scale), scale)
def MSRAFill(tensor): 'Caffe2 MSRAFill Implementation' size = reduce(operator.mul, tensor.shape, 1) fan_out = (size / tensor.shape[1]) scale = math.sqrt((2 / fan_out)) return init.normal_(tensor, 0, scale)
class AffineChannel2d(nn.Module): ' A simple channel-wise affine transformation operation ' def __init__(self, num_features): super().__init__() self.num_features = num_features self.weight = nn.Parameter(torch.Tensor(num_features)) self.bias = nn.Parameter(torch.Tensor(num_fe...
class GroupNorm(nn.Module): def __init__(self, num_groups, num_channels, eps=1e-05, affine=True): super().__init__() self.num_groups = num_groups self.num_channels = num_channels self.eps = eps self.affine = affine if self.affine: self.weight = nn.Param...
class Broadcast(Function): @staticmethod def forward(ctx, target_gpus, *inputs): if (not all((input.is_cuda for input in inputs))): raise TypeError('Broadcast function not implemented for CPU tensors') ctx.target_gpus = target_gpus if (len(inputs) == 0): return...
class ReduceAddCoalesced(Function): @staticmethod def forward(ctx, destination, num_inputs, *grads): ctx.target_gpus = [grads[i].get_device() for i in range(0, len(grads), num_inputs)] grads = [grads[i:(i + num_inputs)] for i in range(0, len(grads), num_inputs)] return comm.reduce_add...
class Gather(Function): @staticmethod def forward(ctx, target_device, dim, *inputs): assert all(map((lambda i: i.is_cuda), inputs)) ctx.target_device = target_device ctx.dim = dim ctx.input_gpus = tuple(map((lambda i: i.get_device()), inputs)) ctx.input_sizes = tuple(m...
class Scatter(Function): @staticmethod def forward(ctx, target_gpus, chunk_sizes, dim, input): ctx.target_gpus = target_gpus ctx.chunk_sizes = chunk_sizes ctx.dim = dim ctx.input_device = (input.get_device() if input.is_cuda else (- 1)) streams = None if (ctx.i...
def _get_stream(device): 'Gets a background stream for copying between CPU and GPU' global _streams if (device == (- 1)): return None if (_streams is None): _streams = ([None] * torch.cuda.device_count()) if (_streams[device] is None): _streams[device] = torch.cuda.Stream(d...
class DataParallel(Module): "Implements data parallelism at the module level.\n\n This container parallelizes the application of the given module by\n splitting the input across the specified devices by chunking in the batch\n dimension. In the forward pass, the module is replicated on each device,\n ...
def data_parallel(module, inputs, device_ids=None, output_device=None, dim=0, module_kwargs=None): 'Evaluates module(input) in parallel across the GPUs given in device_ids.\n\n This is the functional version of the DataParallel module.\n\n Args:\n module: the module to evaluate in parallel\n i...
def get_a_var(obj): if isinstance(obj, Variable): return obj if (isinstance(obj, list) or isinstance(obj, tuple)): results = map(get_a_var, obj) for result in results: if isinstance(result, Variable): return result if isinstance(obj, dict): resul...
def parallel_apply(modules, inputs, kwargs_tup=None, devices=None): assert (len(modules) == len(inputs)) if (kwargs_tup is not None): assert (len(modules) == len(kwargs_tup)) else: kwargs_tup = (({},) * len(modules)) if (devices is not None): assert (len(modules) == len(devices...
def replicate(network, devices): from ._functions import Broadcast devices = tuple(devices) num_replicas = len(devices) params = list(network.parameters()) param_indices = {param: idx for (idx, param) in enumerate(params)} param_copies = Broadcast.apply(devices, *params) if (len(params) > ...
def scatter(inputs, target_gpus, dim=0): '\n Slices variables into approximately equal chunks and\n distributes them across given GPUs. Duplicates\n references to objects that are not variables. Does not\n support Tensors.\n ' def scatter_map(obj): if isinstance(obj, Variable): ...
def scatter_kwargs(inputs, kwargs, target_gpus, dim=0): 'Scatter with support for kwargs dictionary' inputs = (scatter(inputs, target_gpus, dim) if inputs else []) kwargs = (scatter(kwargs, target_gpus, dim) if kwargs else []) if (len(inputs) < len(kwargs)): inputs.extend([() for _ in range((l...
def gather(outputs, target_device, dim=0): '\n Gathers variables from different GPUs on a specified device\n (-1 means the CPU).\n ' error_msg = 'outputs must contain tensors, numbers, dicts or lists; found {}' def gather_map(outputs): out = outputs[0] elem_type = type(out) ...
def get_extensions(): this_dir = os.path.dirname(os.path.abspath(__file__)) extensions_dir = os.path.join(this_dir, 'model', 'csrc') main_file = glob.glob(os.path.join(extensions_dir, '*.cpp')) source_cpu = glob.glob(os.path.join(extensions_dir, 'cpu', '*.cpp')) source_cuda = glob.glob(os.path.joi...
class AttrDict(dict): IMMUTABLE = '__immutable__' def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__[AttrDict.IMMUTABLE] = False def __getattr__(self, name): if (name in self.__dict__): return self.__dict__[name] ...
class keydefaultdict(defaultdict): def __missing__(self, key): if (self.default_factory is None): raise KeyError(key) else: ret = self[key] = self.default_factory(key) return ret
def load_detectron_weight(net, detectron_weight_file): (name_mapping, orphan_in_detectron) = net.detectron_weight_mapping with open(detectron_weight_file, 'rb') as fp: src_blobs = pickle.load(fp, encoding='latin1') if ('blobs' in src_blobs): src_blobs = src_blobs['blobs'] params = net....
def resnet_weights_name_pattern(): pattern = re.compile('conv1_w|conv1_gn_[sb]|res_conv1_.+|res\\d+_\\d+_.+') return pattern
def get_runtime_dir(): 'Retrieve the path to the runtime directory.' return os.getcwd()
def get_py_bin_ext(): 'Retrieve python binary extension.' return '.py'
def set_up_matplotlib(): 'Set matplotlib up.' import matplotlib matplotlib.use('Agg')
def exit_on_error(): "Exit from a detectron tool when there's an error." sys.exit(1)
def aspect_ratio_rel(im, aspect_ratio): 'Performs width-relative aspect ratio transformation.' (im_h, im_w) = im.shape[:2] im_ar_w = int(round((aspect_ratio * im_w))) im_ar = cv2.resize(im, dsize=(im_ar_w, im_h)) return im_ar
def aspect_ratio_abs(im, aspect_ratio): 'Performs absolute aspect ratio transformation.' (im_h, im_w) = im.shape[:2] im_area = (im_h * im_w) im_ar_w = np.sqrt((im_area * aspect_ratio)) im_ar_h = np.sqrt((im_area / aspect_ratio)) assert np.isclose((im_ar_w / im_ar_h), aspect_ratio) im_ar = ...
def save_object(obj, file_name): 'Save a Python object by pickling it.' file_name = os.path.abspath(file_name) with open(file_name, 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def cache_url(url_or_file, cache_dir): 'Download the file specified by the URL to the cache_dir and return the\n path to the cached file. If the argument is not a URL, simply return it as\n is.\n ' is_url = (re.match('^(?:http)s?://', url_or_file, re.IGNORECASE) is not None) if (not is_url): ...
def assert_cache_file_is_ok(url, file_path): 'Check that cache file has the correct hash.' cache_file_md5sum = _get_file_md5sum(file_path) ref_md5sum = _get_reference_md5sum(url) assert (cache_file_md5sum == ref_md5sum), 'Target URL {} appears to be downloaded to the local cache file {}, but the md5 h...
def _progress_bar(count, total): 'Report download progress.\n Credit:\n https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console/27871113\n ' bar_len = 60 filled_len = int(round(((bar_len * count) / float(total)))) percents = round(((100.0 * count) / float(total)), 1) ...
def download_url(url, dst_file_path, chunk_size=8192, progress_hook=_progress_bar): 'Download url and write it to dst_file_path.\n Credit:\n https://stackoverflow.com/questions/2028517/python-urllib2-progress-hook\n ' response = urlopen(url) total_size = response.info().getheader('Content-Length'...
def _get_file_md5sum(file_name): 'Compute the md5 hash of a file.' hash_obj = hashlib.md5() with open(file_name, 'r') as f: hash_obj.update(f.read()) return hash_obj.hexdigest()
def _get_reference_md5sum(url): "By convention the md5 hash for url is stored in url + '.md5sum'." url_md5sum = (url + '.md5sum') md5sum = urlopen(url_md5sum).read().strip() return md5sum
def log_json_stats(stats, sort_keys=True): print('json_stats: {:s}'.format(json.dumps(stats, sort_keys=sort_keys)))
def log_stats(stats, misc_args): 'Log training statistics to terminal' if hasattr(misc_args, 'epoch'): lines = ('[%s][%s][Epoch %d][Iter %d / %d]\n' % (misc_args.run_name, misc_args.cfg_filename, misc_args.epoch, misc_args.step, misc_args.iters_per_epoch)) else: lines = ('[%s][%s][Step %d ...
class SmoothedValue(object): 'Track a series of values and provide access to smoothed values over a\n window or the global series average.\n ' def __init__(self, window_size): self.deque = deque(maxlen=window_size) self.series = [] self.total = 0.0 self.count = 0 de...
def send_email(subject, body, to): s = smtplib.SMTP('localhost') mime = MIMEText(body) mime['Subject'] = subject mime['To'] = to s.sendmail('detectron', to, mime.as_string())
def setup_logging(name): FORMAT = '%(levelname)s %(filename)s:%(lineno)4d: %(message)s' logging.root.handlers = [] logging.basicConfig(level=logging.INFO, format=FORMAT, stream=sys.stdout) logger = logging.getLogger(name) return logger
def get_run_name(args): ' A unique name for each run ' if (len(args.id) > 0): return args.id return ((datetime.now().strftime('%b%d-%H-%M-%S') + '_') + socket.gethostname())
def get_output_dir(args, run_name): ' Get root output directory for each run ' (cfg_filename, _) = os.path.splitext(os.path.split(args.cfg_file)[1]) return os.path.join(cfg.OUTPUT_DIR, cfg_filename, run_name)
def infer_load_ckpt(args): ' Get the latest checkpoint from output_dir ' args.run_name = (get_run_name(args) + '_step') output_dir = get_output_dir(args, args.run_name) sfiles = os.path.join(output_dir, 'ckpt', '*.pth') sfiles = glob.glob(sfiles) sfiles.sort(key=os.path.getmtime) if (len(s...
def is_image_file(filename): 'Checks if a file is an image.\n Args:\n filename (string): path to a file\n Returns:\n bool: True if the filename ends with a known image extension\n ' filename_lower = filename.lower() return any((filename_lower.endswith(ext) for ext in IMG_EXT...
def get_imagelist_from_dir(dirpath): images = [] for f in os.listdir(dirpath): if is_image_file(f): images.append(os.path.join(dirpath, f)) return images
def ensure_optimizer_ckpt_params_order(param_groups_names, checkpoint): 'Reorder the parameter ids in the SGD optimizer checkpoint to match\n the current order in the program, in case parameter insertion order is changed.\n ' assert (len(param_groups_names) == len(checkpoint['optimizer']['param_groups']...
def load_optimizer_state_dict(optimizer, state_dict): state_dict = deepcopy(state_dict) groups = optimizer.param_groups saved_groups = state_dict['param_groups'] if (len(groups) != len(saved_groups)): raise ValueError('loaded state dict has a different number of parameter groups') param_le...
def load_pretrained_imagenet_weights(model): 'Load pretrained weights\n Args:\n num_layers: 50 for res50 and so on.\n model: the generalized rcnnn module\n ' (_, ext) = os.path.splitext(cfg.RESNETS.IMAGENET_PRETRAINED_WEIGHTS) if (ext == '.pkl'): with open(cfg.RESNETS.IMAGENET_...
def convert_state_dict(src_dict): 'Return the correct mapping of tensor name and value\n\n Mapping from the names of torchvision model to our resnet conv_body and box_head.\n ' dst_dict = {} for (k, v) in src_dict.items(): toks = k.split('.') if k.startswith('layer'): ass...
def mobilenet_load_pretrained_imagenet_weights(model): 'Load pretrained weights\n Args:\n model: the generalized rcnnn module\n ' (_, ext) = os.path.splitext(cfg.TRAIN.IMAGENET_PRETRAINED_WEIGHTS) if (ext == '.pkl'): with open(cfg.TRAIN.IMAGENET_PRETRAINED_WEIGHTS, 'rb') as fp: ...
def mobilenet_convert_state_dict(src_dict): 'Return the correct mapping of tensor name and value\n\n Mapping from the names of torchvision model to our resnet conv_body and box_head.\n ' dst_dict = {} for (k, v) in src_dict.items(): if ('features' in k): dst_dict[k[len('features....
def vgg_load_pretrained_imagenet_weights(model, convert_state_dict): 'Load pretrained weights\n Args:\n model: the generalized rcnnn module\n ' (_, ext) = os.path.splitext(cfg.TRAIN.IMAGENET_PRETRAINED_WEIGHTS) if (ext == '.pkl'): with open(cfg.TRAIN.IMAGENET_PRETRAINED_WEIGHTS, 'rb')...
def vgg16_load_pretrained_imagenet_weights(model): vgg_load_pretrained_imagenet_weights(model, vgg16_convert_state_dict)
def vgg16_convert_state_dict(src_dict): 'Return the correct mapping of tensor name and value\n\n Mapping from the names of torchvision model to our resnet conv_body and box_head.\n ' mapping = {'features.0': 'conv1_1', 'features.2': 'conv1_2', 'features.5': 'conv2_1', 'features.7': 'conv2_2', 'features....
def vggm_load_pretrained_imagenet_weights(model): vgg_load_pretrained_imagenet_weights(model, vggm_convert_state_dict)
def vggm_convert_state_dict(src_dict): 'Return the correct mapping of tensor name and value\n\n Mapping from the names of torchvision model to our resnet conv_body and box_head.\n ' mapping = {'features.0': 'conv1', 'features.4': 'conv2', 'features.8': 'conv3', 'features.10': 'conv4', 'features.12': 'co...
def process_in_parallel(tag, total_range_size, binary, output_dir, load_ckpt, load_detectron, opts=''): 'Run the specified binary NUM_GPUS times in parallel, each time as a\n subprocess that uses one GPU. The binary must accept the command line\n arguments `--range {start} {end}` that specify a data process...
def log_subprocess_output(i, p, output_dir, tag, start, end): "Capture the output of each subprocess and log it in the parent process.\n The first subprocess's output is logged in realtime. The output from the\n other subprocesses is buffered and then printed all at once (in order) when\n subprocesses fi...
class Timer(object): 'A simple timer.' def __init__(self): self.reset() def tic(self): self.start_time = time.time() def toc(self, average=True): self.diff = (time.time() - self.start_time) self.total_time += self.diff self.calls += 1 self.average_tim...
class TrainingStats(object): 'Track vital training statistics.' def __init__(self, misc_args, log_period=20, tensorboard_logger=None): self.misc_args = misc_args self.LOG_PERIOD = log_period self.tblogger = tensorboard_logger self.tb_ignored_keys = ['iter', 'eta'] self...
def add_path(path): if (path not in sys.path): sys.path.insert(0, path)
def parse_args(): 'Parser command line argumnets' parser = argparse.ArgumentParser(formatter_class=ColorHelpFormatter) parser.add_argument('--output_dir', help='Directory to save downloaded weight files', default=os.path.join(cfg.DATA_DIR, 'pretrained_model')) parser.add_argument('-t', '--targets', na...
def download_file_from_google_drive(id, destination): URL = 'https://docs.google.com/uc?export=download' session = requests.Session() response = session.get(URL, params={'id': id}, stream=True) token = get_confirm_token(response) if token: params = {'id': id, 'confirm': token} resp...
def get_confirm_token(response): for (key, value) in response.cookies.items(): if key.startswith('download_warning'): return value return None
def save_response_content(response, destination): CHUNK_SIZE = 32768 with open(destination, 'wb') as f: for chunk in response.iter_content(CHUNK_SIZE): if chunk: f.write(chunk)
def main(): init() args = parse_args() for filename in args.targets: file_id = PRETRAINED_WEIGHTS[filename] if (not os.path.exists(args.output_dir)): os.makedirs(args.output_dir) destination = os.path.join(args.output_dir, filename) download_file_from_google_dri...
def parse_args(): 'Parse in command line arguments' parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') parser.add_argument('--dataset', help='training dataset') parser.add_argument('--cfg', dest='cfg_file', required=True, help='optional config file') parser.add_argument('--l...
def parse_args(): 'Parse input arguments' parser = argparse.ArgumentParser(description='Train a X-RCNN network') parser.add_argument('--dataset', dest='dataset', required=True, help='Dataset to use') parser.add_argument('--cfg', dest='cfg_file', required=True, help='Config file for training (and optio...
def main(): 'Main function' args = parse_args() print('Called with args:') print(args) if (not torch.cuda.is_available()): sys.exit('Need a CUDA device to run the code.') if (args.cuda or (cfg.NUM_GPUS > 0)): cfg.CUDA = True else: raise ValueError('Need Cuda device ...
def log_training_stats(training_stats, global_step, lr): stats = training_stats.GetStats(global_step, lr) log_stats(stats, training_stats.misc_args) if training_stats.tblogger: training_stats.tb_log_stats(stats, global_step)
def parse_args(): 'Parse input arguments' parser = argparse.ArgumentParser(description='Train a X-RCNN network') parser.add_argument('--dataset', dest='dataset', required=True, help='Dataset to use') parser.add_argument('--cfg', dest='cfg_file', required=True, help='Config file for training (and optio...
def save_ckpt(output_dir, args, step, train_size, model, optimizer, dataiterator=None, final=False): 'Save checkpoint' if args.no_save: return ckpt_dir = os.path.join(output_dir, 'ckpt') if (not os.path.exists(ckpt_dir)): os.makedirs(ckpt_dir) save_name = os.path.join(ckpt_dir, 'mo...
def main(): 'Main function' args = parse_args() print('Called with args:') print(args) if (not torch.cuda.is_available()): sys.exit('Need a CUDA device to run the code.') if (args.cuda or (cfg.NUM_GPUS > 0)): cfg.CUDA = True else: raise ValueError('Need Cuda device ...
class AverageMeter(): def __init__(self, *keys): self.__data = dict() for k in keys: self.__data[k] = [0.0, 0] def add(self, dict): for (k, v) in dict.items(): if (k not in self.__data): self.__data[k] = [0.0, 0] self.__data[k][0] +...
def crf_inference(img, probs, t=10, scale_factor=1, labels=21): (h, w) = img.shape[:2] n_labels = labels d = dcrf.DenseCRF2D(w, h, n_labels) unary = unary_from_softmax(probs) unary = np.ascontiguousarray(unary) img_c = np.ascontiguousarray(img) d.setUnaryEnergy(unary) d.addPairwiseGaus...
def crf_inference_label(img, labels, t=10, n_labels=21, gt_prob=0.7): (h, w) = img.shape[:2] d = dcrf.DenseCRF2D(w, h, n_labels) unary = unary_from_labels(labels, n_labels, gt_prob=gt_prob, zero_unsure=False) d.setUnaryEnergy(unary) d.addPairwiseGaussian(sxy=3, compat=3) d.addPairwiseBilateral...
class DenseCRF(object): def __init__(self, iter_max, pos_w, pos_xy_std, bi_w, bi_xy_std, bi_rgb_std): self.iter_max = iter_max self.pos_w = pos_w self.pos_xy_std = pos_xy_std self.bi_w = bi_w self.bi_xy_std = bi_xy_std self.bi_rgb_std = bi_rgb_std def __call__...
def multilabel_score(y_true, y_pred): return metrics.f1_score(y_true, y_pred)
def _fast_hist(label_true, label_pred, num_classes): mask = ((label_true >= 0) & (label_true < num_classes)) hist = np.bincount(((num_classes * label_true[mask].astype(int)) + label_pred[mask]), minlength=(num_classes ** 2)) return hist.reshape(num_classes, num_classes)
def scores(label_trues, label_preds, num_classes=21): hist = np.zeros((num_classes, num_classes)) for (lt, lp) in zip(label_trues, label_preds): hist += _fast_hist(lt.flatten(), lp.flatten(), num_classes) acc = (np.diag(hist).sum() / hist.sum()) acc_cls = (np.diag(hist) / hist.sum(axis=1)) ...
def pseudo_scores(label_trues, label_preds, num_classes=21): hist = np.zeros((num_classes, num_classes)) for (lt, lp) in zip(label_trues, label_preds): lt = lt.flatten() lp = lp.flatten() lt[(lp == 255)] = 255 lp[(lp == 255)] = 0 hist += _fast_hist(lt, lp, num_classes) ...
class PolyWarmupAdamW(torch.optim.AdamW): def __init__(self, params, lr, weight_decay, betas, warmup_iter=None, max_iter=None, warmup_ratio=None, power=None): super().__init__(params, lr=lr, betas=betas, weight_decay=weight_decay, eps=1e-08) self.global_step = 0 self.warmup_iter = warmup_...
class PolyWarmupSGD(torch.optim.SGD): def __init__(self, params, lr, weight_decay, betas, warmup_iter=None, max_iter=None, warmup_ratio=None, power=None): super().__init__(params, lr=lr, momentum=0.9, weight_decay=weight_decay) self.global_step = 0 self.warmup_iter = warmup_iter s...
def get_kernel(): weight = torch.zeros(8, 1, 3, 3) weight[(0, 0, 0, 0)] = 1 weight[(1, 0, 0, 1)] = 1 weight[(2, 0, 0, 2)] = 1 weight[(3, 0, 1, 0)] = 1 weight[(4, 0, 1, 2)] = 1 weight[(5, 0, 2, 0)] = 1 weight[(6, 0, 2, 1)] = 1 weight[(7, 0, 2, 2)] = 1 return weight
class PAR(nn.Module): def __init__(self, dilations, num_iter): super().__init__() self.dilations = dilations self.num_iter = num_iter kernel = get_kernel() self.register_buffer('kernel', kernel) self.pos = self.get_pos() self.dim = 2 self.w1 = 0.3 ...
def conv3x3(in_planes, out_planes, stride=1, dilation=1, padding=1): ' 3 x 3 conv' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=padding, dilation=dilation, bias=False)
def conv1x1(in_planes, out_planes, stride=1, dilation=1, padding=1): ' 1 x 1 conv' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, padding=padding, dilation=dilation, bias=False)
class LargeFOV(nn.Module): def __init__(self, in_planes, out_planes): super(LargeFOV, self).__init__() self.conv6 = conv3x3(in_planes=in_planes, out_planes=in_planes, padding=12, dilation=12) self.relu6 = nn.ReLU(inplace=True) self.conv7 = conv3x3(in_planes=in_planes, out_planes=i...