code
stringlengths
17
6.64M
def ResNet50(): return ResNet(Bottleneck, [3, 4, 6, 3])
def ResNet101(): return ResNet(Bottleneck, [3, 4, 23, 3])
def ResNet152(): return ResNet(Bottleneck, [3, 8, 36, 3])
def test(): net = ResNet18() y = net(torch.randn(1, 3, 32, 32)) print(y.size())
class Block(nn.Module): 'Grouped convolution block.' expansion = 2 def __init__(self, in_planes, cardinality=32, bottleneck_width=4, stride=1): super(Block, self).__init__() group_width = (cardinality * bottleneck_width) self.conv1 = nn.Conv2d(in_planes, group_width, kernel_size=1...
class ResNeXt(nn.Module): def __init__(self, num_blocks, cardinality, bottleneck_width, num_classes=10): super(ResNeXt, self).__init__() self.cardinality = cardinality self.bottleneck_width = bottleneck_width self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=1,...
def ResNeXt29_2x64d(): return ResNeXt(num_blocks=[3, 3, 3], cardinality=2, bottleneck_width=64)
def ResNeXt29_4x64d(): return ResNeXt(num_blocks=[3, 3, 3], cardinality=4, bottleneck_width=64)
def ResNeXt29_8x64d(): return ResNeXt(num_blocks=[3, 3, 3], cardinality=8, bottleneck_width=64)
def ResNeXt29_32x4d(): return ResNeXt(num_blocks=[3, 3, 3], cardinality=32, bottleneck_width=4)
def test_resnext(): net = ResNeXt29_2x64d() x = torch.randn(1, 3, 32, 32) y = net(x) print(y.size())
class BasicBlock(nn.Module): def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, ...
class PreActBlock(nn.Module): def __init__(self, in_planes, planes, stride=1): super(PreActBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) ...
class SENet(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(SENet, self).__init__() self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(block...
def SENet18(): return SENet(PreActBlock, [2, 2, 2, 2])
def test(): net = SENet18() y = net(torch.randn(1, 3, 32, 32)) print(y.size())
class ShuffleBlock(nn.Module): def __init__(self, groups): super(ShuffleBlock, self).__init__() self.groups = groups def forward(self, x): 'Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,w] -> [N,C,H,W]' (N, C, H, W) = x.size() g = self.groups retur...
class Bottleneck(nn.Module): def __init__(self, in_planes, out_planes, stride, groups): super(Bottleneck, self).__init__() self.stride = stride mid_planes = (out_planes / 4) g = (1 if (in_planes == 24) else groups) self.conv1 = nn.Conv2d(in_planes, mid_planes, kernel_size=...
class ShuffleNet(nn.Module): def __init__(self, cfg): super(ShuffleNet, self).__init__() out_planes = cfg['out_planes'] num_blocks = cfg['num_blocks'] groups = cfg['groups'] self.conv1 = nn.Conv2d(3, 24, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(24) ...
def ShuffleNetG2(): cfg = {'out_planes': [200, 400, 800], 'num_blocks': [4, 8, 4], 'groups': 2} return ShuffleNet(cfg)
def ShuffleNetG3(): cfg = {'out_planes': [240, 480, 960], 'num_blocks': [4, 8, 4], 'groups': 3} return ShuffleNet(cfg)
def test(): net = ShuffleNetG2() x = torch.randn(1, 3, 32, 32) y = net(x) print(y)
def VGG19(): return VGG('VGG19')
class VGG(nn.Module): def __init__(self, vgg_name): super(VGG, self).__init__() self.features = self._make_layers(cfg[vgg_name]) self.classifier = nn.Linear(512, 10) def forward(self, x): out = self.features(x) out = out.view(out.size(0), (- 1)) out = self.cla...
def test(): net = VGG('VGG11') x = torch.randn(2, 3, 32, 32) y = net(x) print(y.size())
def fmad(ys, xs, dxs): v = [t.zeros_like(y, requires_grad=True) for y in ys] g = grad(ys, xs, grad_outputs=v, create_graph=True) return grad(g, v, grad_outputs=dxs)
def chunks(lst, n): 'Yield successive n-sized chunks from lst.' for i in range(0, len(lst), n): (yield lst[i:(i + n)])
class LogicDataset(Dataset): def __init__(self, examples, args=None, simple_tokenizer_vocab=None): self.simple_tokenizer_vocab = simple_tokenizer_vocab if args.keep_only_negative: self.examples = [i for i in examples if (i['label'] == 0)] self.examples = examples for (...
def limit_examples(examples_by_depth, max_depth_during_train, control_num=2000): for key in list(examples_by_depth.keys()): if (key > max_depth_during_train): del examples_by_depth[key] limit_length = len(examples_by_depth[max_depth_during_train]) print('Original lenght', limit_length)...
def merge_and_balance_dataset(file_name, file_range, max_depth_during_train, final_file_name, control_num, depth='depth'): all_examples = [] for i in range(file_range): print(i) with open(file_name.replace('INDEX', str(i))) as f: examples = json.load(f) examples_by_depth = ...
@functools.lru_cache() def _get_global_gloo_group(): '\n Return a process group based on gloo backend, containing all the ranks\n The result is cached.\n ' if (dist.get_backend() == 'nccl'): return dist.new_group(backend='gloo') return dist.group.WORLD
def all_gather(data): '\n Run all_gather on arbitrary picklable data (not necessarily tensors)\n Args:\n data: any picklable object\n Returns:\n list[data]: list of data gathered from each rank\n ' world_size = get_world_size() if (world_size == 1): return [data] cpu_...
def reduce_dict(input_dict, average=True): '\n Args:\n input_dict (dict): all the values will be reduced\n average (bool): whether to do average or sum\n Reduce the values in the dictionary from all processes so that all processes\n have the averaged results. Returns a dict with the same fi...
def setup_for_distributed(is_master): '\n This function disables printing when not in master process\n ' import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): force = kwargs.pop('force', False) if (is_master or force): builtin_p...
def is_dist_avail_and_initialized(): '\n Returns:\n True if distributed training is enabled\n ' if (not dist.is_available()): return False if (not dist.is_initialized()): return False return True
def get_world_size(): '\n Returns:\n The number of processes in the process group\n ' if (not is_dist_avail_and_initialized()): return 1 return dist.get_world_size()
def get_rank(): '\n Returns:\n The rank of the current process within the global process group.\n ' if (not is_dist_avail_and_initialized()): return 0 return dist.get_rank()
def get_local_rank() -> int: '\n Returns:\n The rank of the current process within the local (per-machine) process group.\n ' 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(...
def get_local_size() -> int: '\n Returns:\n The size of the per-machine process group,\n i.e. the number of processes per machine.\n ' if (not dist.is_available()): return 1 if (not dist.is_initialized()): return 1 return dist.get_world_size(group=_LOCAL_PROCESS_GRO...
def is_main_process(): 'Return true if the current process is the main one' return (get_rank() == 0)
def save_on_master(*args, **kwargs): 'Utility function to save only from the main process' if is_main_process(): torch.save(*args, **kwargs)
def init_distributed_mode(args): 'Initialize distributed training, if appropriate' if (('RANK' in os.environ) and ('WORLD_SIZE' in os.environ)): args.rank = int(os.environ['RANK']) args.world_size = int(os.environ['WORLD_SIZE']) args.gpu = int(os.environ['LOCAL_RANK']) elif ('SLURM...
def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if (args.n_gpu > 0): torch.cuda.manual_seed_all(args.seed)
def train(args, train_dataset, model, tokenizer, eval_dataset=None): ' Train the model ' args.train_batch_size = (args.per_gpu_train_batch_size * max(1, args.n_gpu)) train_sampler = (RandomSampler(train_dataset) if (args.local_rank == (- 1)) else DistributedSampler(train_dataset)) train_dataloader = D...
def evaluate(args, model, tokenizer, prefix='', eval_dataset=None): results = {} args.eval_batch_size = (args.per_gpu_eval_batch_size * max(1, args.n_gpu)) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, collate_fn=eval_dataset.collate_fn, sampler=eval_sampler...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--model_type', default=None, type=str, required=True) parser.add_argument('--model_name_or_path', default=None, type=str, required=True) parser.add_argument('--output_dir', default=None, type=str, required=True, help='The output direc...
def setup_for_distributed(is_master): '\n This function disables printing when not in master process\n ' import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): force = kwargs.pop('force', False) if (is_master or force): builtin_p...
class TrainingMeter(): def __init__(self): self.counter_dict = defaultdict(float) self.true_dict = defaultdict(float) def update(self, loss_dict): for (key, item) in loss_dict.items(): self.counter_dict[key] += 1 self.true_dict[key] += item def report(sel...
def load_state_dict_flexible(model, state_dict): try: model.load_state_dict(state_dict) except: print('Full loading failed!! Try partial loading!!') own_state = model.state_dict() for (name, param) in state_dict.items(): if (name not in own_state): print(('Skipped: ...
def expand_position_embeddings(model, length=None, model_type='bert'): if ('bert' in model_type): embedding_model = model.bert.embeddings original_embedding = embedding_model.position_embeddings.weight.data new_embedding = nn.Embedding((length - 500), (1024 if ('large' in model_type) else 768)) ...
def _init_weights(module, config): ' Initialize the weights ' if isinstance(module, (nn.Linear, nn.Embedding)): module.weight.data.normal_(mean=0.0, std=config.initializer_range) elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) if (i...
def init(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--input_file', default='input.json', type=str) arg_parser.add_argument('--output_file', default='output.json', type=str) arg_parser.add_argument('--min_rule_num', default=0, type=int) arg_parser.add_argument('--max_rule_nu...
def stats(examples): label_sum = 0.0 depth_sum = 0.0 backward_depth_sum = 0.0 max_tree_depth_sum = 0.0 tree_depth_sum = 0.0 example_num = len(examples) if (example_num == 0): return for example in examples: label_sum += example['label'] depth_sum += example['dep...
def main(): args = init() with open(args.input_file, 'r') as fin: examples = json.load(fin) random.shuffle(examples) print('loaded') balanced_examples = {} for key in range(0, 121): balanced_examples[key] = [[], []] threshold = 1.0 for example in examples: rule_...
def init(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--vocab_file', default='vocab.txt', type=str) arg_parser.add_argument('--output_file', default='prop_examples.txt', type=str) arg_parser.add_argument('--example_num', default=1000, type=int) arg_parser.add_argument('--min_...
def read_vocab(vocab_file): vocab = [] with open(vocab_file, 'r') as fin: vocab = [line.strip() for line in fin.readlines()] print('vocabulary size: ', len(vocab)) return vocab
def sample_one_rule(preds): head_num = random.randint(1, 3) lits = random.sample(preds, min((head_num + 1), len(preds))) random.shuffle(lits) return (lits[:(- 1)], lits[(- 1)])
def sample_rule_priority(preds): pred_num = len(preds) rule_num = random.randint(0, (4 * pred_num)) fact_num = random.randint(0, pred_num) cache = set() rules = [] for _ in range(0, rule_num): rule = None while True: rule = sample_one_rule(preds) rule_ha...
def sample_label_priority(preds): preds_ = preds[:] random.shuffle(preds_) pred_num = len(preds) graph_depth = random.randint(1, (pred_num // 2)) width = (pred_num // graph_depth) preds_0 = preds_[:(pred_num % graph_depth)] preds_ = preds_[(pred_num % graph_depth):] rules = [] leve...
def sample_lp_star(preds): preds_ = preds[:] pred_num = len(preds) graph_depth = random.randint(2, (pred_num // 2)) width = (pred_num // graph_depth) preds_0 = preds_[:(pred_num % graph_depth)] preds_ = preds_[(pred_num % graph_depth):] rules = [] levels = [] prev_level = [[x, rand...
def forward_chain(rules, facts): res = {} for fact in facts: res[fact] = 0 depth = 1 prev_len = 0 while (len(res) > prev_len): new_facts = [] for rule in rules: (head, tail) = rule if all([(lit in res) for lit in head]): new_facts.app...
def backward_chain_(u, depth, rules, facts, max_depth, ances): INF = 100000000 if (u in facts): return INF if ((u in ances) or (depth == max_depth)): return depth res = depth for rule in [x for x in rules if (x[1] == u)]: (head, _) = rule tmp = INF for lit i...
def backward_chain(query, rules, facts, max_depth): return backward_chain_(query, 0, rules, facts, max_depth, set())
def process_example(example, max_depth): [random.shuffle(rule[0]) for rule in example['rules']] random.shuffle(example['rules']) random.shuffle(example['facts']) res = forward_chain(example['rules'], example['facts']) example['label'] = (1 if (example['query'] in res) else 0) if (example['labe...
def sample_one_example(vocab, min_pred_num, max_pred_num, max_depth, algo): pred_num = random.randint(min_pred_num, max_pred_num) preds = random.sample(vocab, pred_num) if (algo == 'RP'): (rules, facts, query) = sample_rule_priority(preds) if (algo == 'LP'): (rules, facts, query) = sam...
def sample_examples(example_num, vocab, min_pred_num, max_pred_num, max_depth, algo): examples = [] for _ in tqdm(range(0, example_num)): example = None while (example is None): example = sample_one_example(vocab, min_pred_num, max_pred_num, max_depth, algo) examples.append...
def stats(examples): label_sum = 0.0 depth_sum = 0.0 example_num = len(examples) if (example_num == 0): return for example in examples: label_sum += example['label'] depth_sum += example['depth'] print('# of examples:', example_num) print('percentage of positive exa...
def write_examples(examples, output_file): random.shuffle(examples) with open(output_file, 'w') as fout: json.dump(examples, fout)
def main(): args = init() vocab = read_vocab(args.vocab_file) if args.balance_by_depth: examples = {} example_num = args.example_num keys = [x for x in range(0, (args.max_depth + 1))] for k in keys: examples[k] = [] while True: examples_ = sa...
def main(): args = parser.parse_args() if (args.seed is not None): random.seed(args.seed) torch.manual_seed(args.seed) cudnn.deterministic = True warnings.warn('You have chosen to seed training. This will turn on the CUDNN deterministic setting, which can slow down your trainin...
def main_worker(gpu, ngpus_per_node, args): args.gpu = gpu if (args.multiprocessing_distributed and (args.gpu != 0)): def print_pass(*args): pass builtins.print = print_pass if (args.gpu is not None): print('Use GPU: {} for training'.format(args.gpu)) if args.distr...
def train(train_loader, model, criterion, optimizer, epoch, args): batch_time = AverageMeter('Time', ':6.3f') data_time = AverageMeter('Data', ':6.3f') losses = AverageMeter('Loss', ':.4e') top1 = AverageMeter('Acc@1', ':6.2f') top5 = AverageMeter('Acc@5', ':6.2f') progress = ProgressMeter(len...
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): torch.save(state, filename) if is_best: shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object): 'Computes and stores the average and current value' def __init__(self, name, fmt=':f'): self.name = name self.fmt = fmt self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(...
class ProgressMeter(object): def __init__(self, num_batches, meters, prefix=''): self.batch_fmtstr = self._get_batch_fmtstr(num_batches) self.meters = meters self.prefix = prefix def display(self, batch): entries = [(self.prefix + self.batch_fmtstr.format(batch))] ent...
def adjust_learning_rate(optimizer, epoch, args): 'Decay the learning rate based on schedule' lr = args.lr if args.cos: lr *= (0.5 * (1.0 + math.cos(((math.pi * epoch) / args.epochs)))) else: for milestone in args.schedule: lr *= (0.1 if (epoch >= milestone) else 1.0) f...
def accuracy(output, target, topk=(1,)): 'Computes the accuracy over the k top predictions for the specified values of k' with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) (_, pred) = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(ta...
class TwoCropsTransform(): 'Take two random crops of one image as the query and key.' def __init__(self, base_transform): self.base_transform = base_transform def __call__(self, x): q = self.base_transform(x) k = self.base_transform(x) return [q, k]
class GaussianBlur(object): 'Gaussian blur augmentation in SimCLR https://arxiv.org/abs/2002.05709' def __init__(self, sigma=[0.1, 2.0]): self.sigma = sigma def __call__(self, x): sigma = random.uniform(self.sigma[0], self.sigma[1]) x = x.filter(ImageFilter.GaussianBlur(radius=si...
def reformat_incre_equations(x): result = '' if (len(x) >= 1): for eq in x: if (len(result) == 0): result += eq[2:(- 2)] else: result += (', ' + eq[2:(- 2)]) return result
def reformat_equations_from_peano(eq_list): result = '' for eq in eq_list.split(','): if ('eq' in eq): if (len(result) == 0): result += eq[(eq.index('eq') + 2):] else: result += (', ' + eq[(eq.index('eq') + 2):]) elif ('answer' in eq): ...
def get_declarative_equations(model, question, prompt, max_tokens, stop_token, temperature): prompt = prompt.format(question=question) response = openai.Completion.create(model=model, prompt=prompt, max_tokens=max_tokens, stop=stop_token, temperature=temperature, top_p=1) result = response['choices'][0]['...
def get_final_using_sympy(equations): try: transformations = ((standard_transformations + (implicit_multiplication_application,)) + (convert_xor,)) if (str(equations) == 'nan'): return np.nan equation_list = equations.split(',') for eq in equation_list: for ...
def get_detector(opt=None): if (opt.detector == 'yolo'): from detector.yolo_api import YOLODetector from detector.yolo_cfg import cfg return YOLODetector(cfg, opt) elif (opt.detector == 'tracker'): from detector.tracker_api import Tracker from detector.tracker_cfg impor...
class BaseDetector(ABC): def __init__(self): pass @abstractmethod def image_preprocess(self, img_name): pass @abstractmethod def images_detection(self, imgs, orig_dim_list): pass @abstractmethod def detect_one_img(self, img_name): pass
class TrackState(object): New = 0 Tracked = 1 Lost = 2 Removed = 3
class BaseTrack(object): _count = 0 track_id = 0 is_activated = False state = TrackState.New history = OrderedDict() features = [] curr_feature = None score = 0 start_frame = 0 frame_id = 0 time_since_update = 0 location = (np.inf, np.inf) @property def end_fra...
class Evaluator(object): def __init__(self, data_root, seq_name, data_type): self.data_root = data_root self.seq_name = seq_name self.data_type = data_type self.load_annotations() self.reset_accumulator() def load_annotations(self): assert (self.data_type == '...
def write_results(filename, results_dict: Dict, data_type: str): if (not filename): return path = os.path.dirname(filename) if (not os.path.exists(path)): os.makedirs(path) if (data_type in ('mot', 'mcmot', 'lab')): save_format = '{frame},{id},{x1},{y1},{w},{h},1,-1,-1,-1\n' ...
def read_results(filename, data_type: str, is_gt=False, is_ignore=False): if (data_type in ('mot', 'lab')): read_fun = read_mot_results else: raise ValueError('Unknown data type: {}'.format(data_type)) return read_fun(filename, is_gt, is_ignore)
def read_mot_results(filename, is_gt, is_ignore): valid_labels = {1} ignore_labels = {2, 7, 8, 12} results_dict = dict() if os.path.isfile(filename): with open(filename, 'r') as f: for line in f.readlines(): linelist = line.split(',') if (len(linelis...
def unzip_objs(objs): if (len(objs) > 0): (tlwhs, ids, scores) = zip(*objs) else: (tlwhs, ids, scores) = ([], [], []) tlwhs = np.asarray(tlwhs, dtype=float).reshape((- 1), 4) return (tlwhs, ids, scores)
def get_logger(name='root'): formatter = logging.Formatter(fmt='%(asctime)s [%(levelname)s]: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.addHandler(handler) ...
def parse_model_cfg(path): 'Parses the yolo-v3 layer configuration file and returns module definitions' file = open(path, 'r') lines = file.read().split('\n') lines = [x for x in lines if (x and (not x.startswith('#')))] lines = [x.rstrip().lstrip() for x in lines] module_defs = [] for lin...
def parse_data_cfg(path): 'Parses the data configuration file' options = dict() options['gpus'] = '0' options['num_workers'] = '10' with open(path, 'r') as fp: lines = fp.readlines() for line in lines: line = line.strip() if ((line == '') or line.startswith('#')): ...
class Timer(object): 'A simple timer.' def __init__(self): self.total_time = 0.0 self.calls = 0 self.start_time = 0.0 self.diff = 0.0 self.average_time = 0.0 self.duration = 0.0 def tic(self): self.start_time = time.time() def toc(self, averag...
def add_path(path): if (path not in sys.path): sys.path.insert(0, path)
class BoundingBox(): def __init__(self, imageName, classId, x, y, w, h, typeCoordinates=CoordinatesType.Absolute, imgSize=None, bbType=BBType.GroundTruth, classConfidence=None, format=BBFormat.XYWH): "Constructor.\n Args:\n imageName: String representing the image name.\n cla...
class BoundingBoxes(): def __init__(self): self._boundingBoxes = [] def addBoundingBox(self, bb): self._boundingBoxes.append(bb) def removeBoundingBox(self, _boundingBox): for d in self._boundingBoxes: if BoundingBox.compare(d, _boundingBox): del self...
class Evaluator(): def GetPascalVOCMetrics(self, boundingboxes, IOUThreshold=0.5, method=MethodAveragePrecision.EveryPointInterpolation): 'Get the metrics used by the VOC Pascal 2012 challenge.\n Get\n Args:\n boundingboxes: Object of the class BoundingBoxes representing ground t...