code
stringlengths
101
5.91M
def lines(f, delim): while True: line = f.readline() if (line == ''): break (yield map(float, line.strip().split(delim)))
class DirectoryCLI(CLIMixin, metaclass=abc.ABCMeta): def get_parent_parser(cls, desc: str, valid_modalities: frozenset[str]=intnorm.VALID_MODALITIES, **kwargs: typing.Any) -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=desc, formatter_class=argparse.ArgumentDefaultsHelpFormatter) ...
def main(): args = parse_args() accelerator = Accelerator() logger.info(accelerator.state) logger.setLevel((logging.INFO if accelerator.is_local_main_process else logging.ERROR)) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.l...
(version='2.0') class Criterions(object): def __init__(self, framework): assert (framework in ('tensorflow', 'pytorch', 'pytorch_fx')), 'framework support tensorflow pytorch' self.criterions = framework_criterions[framework]().criterions def __getitem__(self, criterion_type): assert (cri...
_model def regnety_002(pretrained=False, **kwargs): return _create_regnet('regnety_002', pretrained, **kwargs)
def fetch_data(dataset: Callable[([str], Dataset)], transform: Optional[Callable]=None, target_transform: Optional[Callable]=None, num_workers: int=0, pin_memory: bool=True, drop_last: bool=False, train_splits: List[str]=[], test_splits: List[str]=[], train_shuffle: bool=True, test_shuffle: bool=False, test_image_size:...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--model', required=True, help='sentencepiece model to use for encoding') parser.add_argument('--inputs', nargs='+', default=['-'], help='input files to filter/encode') parser.add_argument('--outputs', nargs='+', default=['-'], help='pat...
def restore_model(pkl_file, checkpoint=None, train=False, fp16=None): info = load_pickle(pkl_file) init = info['init'] name = info['name'] search_in = join(nnunet.__path__[0], 'training', 'network_training') tr = recursive_find_python_class([search_in], name, current_module='nnunet.training.network_...
def test_properties_are_correct(archive_fixture): (archive, x0) = archive_fixture sigma = 1 batch_size = 2 emitter = GaussianEmitter(archive, sigma=sigma, x0=x0, batch_size=batch_size) assert np.all((emitter.x0 == x0)) assert (emitter.sigma == sigma) assert (emitter.batch_size == batch_size)
def _get_pre_context_function(pre_context_process, kws=None): pre_context_process = pre_context_process.lower() kws = (kws or {}) if (pre_context_process in 'summarization'): return SummarizationContextProcess(**kws) if (pre_context_process in 'selective'): return SelectiveContextProcess...
def emb_summarize(f, namer, search_n=25): load_spacy() nlps = get_nlps(f, namer) nlps = filter_oov(nlps) vecs = [n.vector for n in nlps] toks_flat = set() for n in nlps: toks_flat.update(list(n)) toks_flat = [t.text for t in toks_flat] vec = np.array(vecs).mean(0)[np.newaxis] ...
class Constraint(Data): def __init__(self, constraint, train_x, test_x): self.constraint = constraint self.train_x = train_x self.test_x = test_x def losses(self, targets, outputs, loss_fn, inputs, model, aux=None): f = tf.cond(model.net.training, (lambda : self.constraint(inputs...
def evaluate_3rd_user_task_fbne(fbne_data, valid_batch_index, model, sess, valid_data, is_training): (evaluate_loss, evaluate_pearson) = (0.0, 0.0) for index in tqdm.tqdm(valid_batch_index): (b_target_user, b_k_shot_item, b_second_order_users, b_third_order_items, b_oracle_user_ebd, b_mask_num_second_or...
class GraphSAGE(nn.Module): def __init__(self, in_feats, n_hidden, n_classes, n_layers): super(GraphSAGE, self).__init__() self.layers = nn.ModuleList() self.layers.append(GraphSAGELayer(in_feats, n_hidden)) self.layers.append(GraphSAGELayer(n_hidden, n_hidden)) self.layers.a...
def main(): parser.add_argument('--show_glue', action='store_true', help='show glue metric for each task instead of accuracy') parser.add_argument('--print_mode', default='best', help='best|all|tabular') parser.add_argument('--show_subdir', action='store_true', help='print the subdir that has the best resul...
class VarDict(object): def _setattr_(obj, key, val): if key.endswith('__'): key = key[:(- 2)] elif (key in obj.my_dict): logger.info(('re-assign glb.%s' % key)) obj.my_dict[key] = val def _getattr_(obj, key): if key.endswith('__'): key = key[:(...
class GeneratorHubInterface(nn.Module): def __init__(self, cfg, task, models): super().__init__() self.cfg = cfg self.task = task self.models = nn.ModuleList(models) self.src_dict = task.source_dictionary self.tgt_dict = task.target_dictionary for model in sel...
class TFTransfoXLPreTrainedModel(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def get_frame_index(name, frame): for idx in range(len(frame)): if (frame.iloc[(idx, 0)] == name): return idx raise Exception('Could not find image {} in data frame, unsuccessful in finding frame index'.format(name))
def data_loader(X, Y, batch_size, shuffle=True, drop_last=True): cuda = (True if torch.cuda.is_available() else False) TensorFloat = (torch.cuda.FloatTensor if cuda else torch.FloatTensor) (X, Y) = (TensorFloat(X), TensorFloat(Y)) data = torch.utils.data.TensorDataset(X, Y) dataloader = torch.utils....
class ACE2005NerLoader(Loader): def __init__(self): super().__init__() self.label_set.add('O') def _load(self, path): data = load_json(path) for item in data: for entity_mention in item['golden-entity-mentions']: for i in range(entity_mention['start'],...
class SGDFactory(OptimizerFactoryInterface): def add_arguments(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: return sgd(parser) def from_args(target, args: argparse.Namespace): opt = chainer.optimizers.SGD(lr=args.lr) opt.setup(target) opt.add_hook(WeightDecay(args...
_module() class LAD(KnowledgeDistillationSingleStageDetector): 'Implementation of `LAD < def __init__(self, backbone, neck, bbox_head, teacher_backbone, teacher_neck, teacher_bbox_head, teacher_ckpt, eval_teacher=True, train_cfg=None, test_cfg=None, pretrained=None): super(KnowledgeDistillationSingleSta...
def random_subsample(x: List, num_samples: int=8, time_difference: bool=False) -> Tuple[NDArray]: t = len(x) assert ((num_samples > 0) and (t > 0) and (t >= num_samples)) indices = np.linspace(0, (t - 1), num_samples) indices = np.clip(indices, 0, (t - 1)).astype(int) indices = np.sort(np.random.cho...
def _eager_safe_variable_handle(shape, key_dtype, value_dtype, shared_name, name, graph_mode, enter_threshold=0, kv_options=variable_scope.default_kv_option()): container = (ops.get_default_graph()._container or '') shape = tensor_shape.as_shape(shape.as_list()[1]) handle = gen_kv_variable_ops.kv_variable(v...
def retrieve_boxes(scene, objs, all_bboxes, cat2obj): all_bbox = {(tuple(c['object']['bbox']), c['object']['category']) for c in all_bboxes[scene['image_filename']]} all_bbox = [(list(b), c) for (b, c) in all_bbox] assert (len(all_bbox) == len(scene['objects'])), "Error, number of boxes doesn't match number...
class ReversibleBlock(nn.Module): def __init__(self, f, g): super().__init__() self.f = Deterministic(f) self.g = Deterministic(g) def forward(self, x, f_args={}, g_args={}): (x1, x2) = torch.chunk(x, 2, dim=2) (y1, y2) = (None, None) with torch.no_grad(): ...
class TestConfig(unittest.TestCase): def test_config(self): config = PostTrainingQuantConfig() self.assertEqual(config.recipes['smooth_quant'], False) self.assertEqual(config.recipes['fast_bias_correction'], False) self.assertEqual(config.recipes['weight_correction'], False) ...
def parse_resume_step_from_filename(filename): split = filename.split('model') if (len(split) < 2): return 0 split1 = split[(- 1)].split('.')[0] try: return int(split1) except ValueError: return 0
class InverseFlow(Flow): def __init__(self, flow: Flow) -> None: super(InverseFlow, self).__init__() self.flow = flow def forward(self, f: torch.tensor) -> torch.tensor: return self.flow.inverse(f) def inverse(self, f: torch.tensor) -> torch.tensor: return self.flow.forward(f...
class StableDiffusionGLIGENPipeline(metaclass=DummyObject): _backends = ['torch', 'transformers'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch', 'transformers']) def from_config(cls, *args, **kwargs): requires_backends(cls, ['torch', 'transformers']) def from_pret...
def build_model(): initializers = [] input = helper.make_tensor_value_info('input', TensorProto.FLOAT, [1, 3, 15, 15]) output = helper.make_tensor_value_info('reshape_output', TensorProto.FLOAT, [88, 11]) add_node = onnx.helper.make_node('Add', ['input', 'add_init'], ['add_out'], name='add') conv1_w...
def convert_fairseq_s2t_checkpoint_to_tfms(checkpoint_path, pytorch_dump_folder_path): m2m_100 = torch.load(checkpoint_path, map_location='cpu') args = m2m_100['args'] state_dict = m2m_100['model'] lm_head_weights = state_dict['decoder.output_projection.weight'] remove_ignore_keys_(state_dict) r...
def record(msg=''): if DEBUG_TIME: global start_time if ((start_time is None) or (msg == '')): start_time = time.time() print((('%.2f seconds: ' % 0) + 'start')) else: print((('%.2f seconds: ' % (time.time() - start_time)) + msg))
def Load_model_weight_checkpoint(experiment_folder='.', experiment_name=None, rank=0, epoch=10): path_checkpoint = ('%s/checkpoint/%s/' % (experiment_folder, experiment_name)) pthfile = (path_checkpoint + ('Rank%s_Epoch_%s_weights.pth' % (rank, epoch))) checkpoint_weights = torch.load(pthfile, map_location=...
class Server(): def __init__(self, model, clients=[], cfg=None, deadline=0): self._cur_time = 0 self.model = model self.all_clients = clients self.cfg = cfg self.deadline = deadline self.selected_clients = [] self.updates = [] self.clients_info = defau...
_config def model_lifelong_sidetune_double_fcn5s_taskonomy(): cfg = {'learner': {'model': 'LifelongSidetuneNetwork', 'model_kwargs': {'base_class': 'FCN5', 'base_weights_path': '/mnt/models/curvature_encoder_student.dat', 'base_kwargs': {'eval_only': True, 'train': False, 'normalize_outputs': False}, 'use_baked_enc...
def main(iterations, use_test=False): (x_train, y_train, x_val, y_val, x_test, y_test) = load_data(use_test) y_test += 1 print('Loaded {} training examples, {} validation examples, {} testing examples'.format(len(x_train), len(x_val), len(x_test))) model = train_model(x_train, y_train, x_val, y_val, ite...
class ConfigurationVersioningTest(unittest.TestCase): def test_local_versioning(self): configuration = AutoConfig.from_pretrained('bert-base-cased') configuration.configuration_files = ['config.4.0.0.json'] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrai...
def shufflenet_g1_w1(**kwargs): return get_shufflenet(groups=1, width_scale=1.0, model_name='shufflenet_g1_w1', **kwargs)
def get_down_seq(ni, nf, no): sequence = [nn.Conv2d(ni, nf, 4, 2, 1), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(nf, (nf * 2), 4, 2, 1), nn.InstanceNorm2d((nf * 2)), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d((nf * 2), (nf * 4), 4, 2, 1), nn.InstanceNorm2d((nf * 4)), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d((nf *...
class FirstOrderDifferenceLoss(torch.nn.Module): def __init__(self, reduction: str='mean'): super().__init__() self.loss = torch.nn.L1Loss(reduction=reduction) def forward(self, pred, target): pred_diff = torch.diff(pred) target_diff = torch.diff(target) return self.loss(...
class ConfigTester(object): def __init__(self, parent, config_class=None, has_text_modality=True, **kwargs): self.parent = parent self.config_class = config_class self.has_text_modality = has_text_modality self.inputs_dict = kwargs def create_and_test_config_common_properties(sel...
def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('--input_model', type=str, required=False, default='inception-v1-12.onnx') parser.add_argument('--output_model', type=str, required=True) return parser.parse_args()
def load_dataset(config: CfgNode, return_class=True, test=False): dataset_config = config.dataset processor = PROCESSORS[dataset_config.name.lower()]() train_dataset = None valid_dataset = None if (not test): try: train_dataset = processor.get_train_examples(dataset_config.path) ...
def get_root_logger(log_file=None, log_level=logging.INFO): logger = logging.getLogger(__name__.split('.')[0]) if logger.hasHandlers(): return logger format_str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig(format=format_str, level=log_level) (rank, _) = get_di...
class OwlViTFeatureExtractor(metaclass=DummyObject): _backends = ['vision'] def __init__(self, *args, **kwargs): requires_backends(self, ['vision'])
class Dataset(object): def __init__(self, batch_size=100): mnist = keras.datasets.mnist ((train_images, train_labels), (test_images, test_labels)) = mnist.load_data() self.train_images = (train_images / 255.0) self.test_images = (test_images / 255.0) self.train_labels = train...
class COCOPanopticEvaluator(DatasetEvaluator): def __init__(self, dataset_name, output_dir): self._metadata = MetadataCatalog.get(dataset_name) self._thing_contiguous_id_to_dataset_id = {v: k for (k, v) in self._metadata.thing_dataset_id_to_contiguous_id.items()} self._stuff_contiguous_id_to...
def accuracy(test=None, reference=None, confusion_matrix=None, **kwargs): if (confusion_matrix is None): confusion_matrix = ConfusionMatrix(test, reference) (tp, fp, tn, fn) = confusion_matrix.get_matrix() return float(((tp + tn) / (((tp + fp) + tn) + fn)))
class DownBlock3D(nn.Module): def __init__(self, in_channels: int, out_channels: int, temb_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_groups: int=32, resnet_pre_norm: bool=True, output_scale_factor=1.0, ad...
def register_datasets(datasets_data: Iterable[CocoDatasetInfo], datasets_root: Optional[os.PathLike]=None): for dataset_data in datasets_data: register_dataset(dataset_data, datasets_root)
def add_bel_output(bel, wire, port): if (wire not in wire_belports): wire_belports[wire] = set() wire_belports[wire].add((bel, port)) bel_wires[bel].append((constids[port], 1, wire))
_bs4 _tokenizers class MarkupLMProcessorTest(unittest.TestCase): tokenizer_class = MarkupLMTokenizer rust_tokenizer_class = MarkupLMTokenizerFast def setUp(self): vocab = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'G', 'Gl', 'Gn', 'Glo', 'Glow', 'er', 'Glowest', 'Gnewer', 'Gwider', 'Ghello',...
class TestNet(unittest.TestCase): def setUp(self): self.num_output = 13 net_file = simple_net_file(self.num_output) self.net = caffe.Net(net_file, caffe.TRAIN) self.net.blobs['label'].data[...] = np.random.randint(self.num_output, size=self.net.blobs['label'].data.shape) os.r...
def predictor(mocker): p = mocker.MagicMock() p.get_post_fmean = mocker.MagicMock(side_effect=get_post_fmean) p.get_post_fcov = mocker.MagicMock(side_effect=get_post_fcov) p.get_post_samples = mocker.MagicMock(side_effect=get_post_samples) return p
class RedisClient(): def __init__(self): hostname = socket.gethostname() assert hostname.startswith(ROBOT_HOSTNAME_PREFIX) self.bot_num = int(hostname[(- 1)]) self.client = Redis(f'{ROBOT_HOSTNAME_PREFIX}{self.bot_num}', password=REDIS_PASSWORD, decode_responses=True) def get_dri...
class FixedWindowScheduler(): def __init__(self, scheduler_config: SchedulerConfig, kv_cache: Optional) -> None: self.scheduler_config = scheduler_config self.prompt_limit = min(self.scheduler_config.max_model_len, self.scheduler_config.max_num_batched_tokens) self.policy = PolicyFactory.get...
def load_data(file, col): print(f".. loading data from '{file}'") d = pd.read_csv(file) data = d[col] print('') s = pd.Series(data) print(s.describe()) print(f'med {int(np.median(data))}') print('') return data
def insert_new(article_list, sent): token_list = word_tokenize(sent) article_list.append(' '.join(token_list[:sent_limit])) if (len(token_list) > sent_limit): insert_new(article_list, ' '.join(token_list[sent_limit:]))
def main(args): samples = load_tsv_to_dicts(args.raw_manifest) ids = [(sample[args.id_header] if args.id_header else '') for sample in samples] audio_paths = [sample[args.audio_header] for sample in samples] texts = [sample[args.text_header] for sample in samples] prepare_w2v_data(args.w2v_dict_dir,...
class AutoModelForSeq2SeqLM(): def __init__(self): raise EnvironmentError('AutoModelForSeq2SeqLM is designed to be instantiated using the `AutoModelForSeq2SeqLM.from_pretrained(pretrained_model_name_or_path)` or `AutoModelForSeq2SeqLM.from_config(config)` methods.') _list_option_in_docstrings(MODEL_FOR_...
def get_launcher(distributed=False): num_gpus = (min(2, get_gpu_count()) if distributed else 1) master_port = get_master_port(real_launcher=True) return f'deepspeed --num_nodes 1 --num_gpus {num_gpus} --master_port {master_port}'.split()
class Module(BaseModule): def __init__(self, symbol, data_names=('data',), label_names=('softmax_label',), logger=logging, context=ctx.cpu(), work_load_list=None, fixed_param_names=None, state_names=None): super(Module, self).__init__(logger=logger) if isinstance(context, ctx.Context): c...
class SwitchableDropoutWrapper(DropoutWrapper): def __init__(self, cell, is_train, input_keep_prob=1.0, output_keep_prob=1.0, seed=None): super(SwitchableDropoutWrapper, self).__init__(cell, input_keep_prob=input_keep_prob, output_keep_prob=output_keep_prob, seed=seed) self.is_train = is_train d...
class SAGPool(torch.nn.Module): def __init__(self, in_channels, ratio=0.8, Conv=GCNConv, non_linearity=torch.tanh): super(SAGPool, self).__init__() self.in_channels = in_channels self.ratio = ratio self.score_layer = Conv(in_channels, 1) self.non_linearity = non_linearity ...
class NormalizeActions(EnvWrapper): def __init__(self, env): super().__init__(env) self._mask = np.logical_and(np.isfinite(env.action_space.low), np.isfinite(env.action_space.high)) self._low = np.where(self._mask, env.action_space.low, (- 1)) self._high = np.where(self._mask, env.ac...
class Net(torch.nn.Module): def __init__(self, inputsize, taskcla): super(Net, self).__init__() (ncha, size, _) = inputsize self.taskcla = taskcla self.conv1 = torch.nn.Conv2d(ncha, 64, kernel_size=(size // 8)) s = utils.compute_conv_output_size(size, (size // 8)) s =...
def update_linker(linker): exits = get_exits(linker) exits = sorted(exits, key=(lambda e: e.GetIdx()), reverse=True) elinker = Chem.EditableMol(linker) for exit in exits: bonds = exit.GetBonds() if (len(bonds) > 1): raise Exception('Exit atom has more than 1 bond') bo...
class DirectoryIterator(Iterator): def __init__(self, directory, image_data_generator, target_size=(256, 256), color_mode='rgb', classes=None, class_mode='categorical', batch_size=32, shuffle=True, seed=None, save_to_dir=None, save_prefix='', save_format='png', follow_links=False, subset=None, interpolation='neares...
def remove_newlines(s): p = re.compile('[\n|\r\n|\n\r]') s = re.sub(p, ' ', s) s = remove_extraneous_whitespace(s) return s
def torch_nn_functional_one_hot(tensor, num_classes=(- 1)): if (num_classes < 0): raise ValueError("Don't support automatic num_classes inference for MetaTensor analysis") shape = (list(tensor.shape) + [num_classes]) return torch.empty(shape, device='meta')
class AtariNet(nn.Module): def __init__(self, observation_shape, num_actions): super(AtariNet, self).__init__() self.observation_shape = observation_shape self.num_actions = num_actions self.feat_convs = [] self.resnet1 = [] self.resnet2 = [] self.convs = [] ...
class DCN(DCNv2): def __init__(self, in_channels, out_channels, kernel_size, stride, padding=0, dilation=1, deformable_groups=2, groups=None, bias=True): super(DCN, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, deformable_groups) channels_ = (((self.deformable_gro...
def get_sparse_feature(feature_file, label_file): (sparse_x, _) = load_svmlight_file(feature_file, multilabel=True) return (normalize(sparse_x), (np.load(label_file) if (label_file is not None) else None))
class FCResNet(nn.Module): def __init__(self, input_size=(1, 40, 1091)): super(FCResNet, self).__init__() self.cnn1 = nn.Conv2d(1, 16, kernel_size=(3, 3), padding=(1, 1)) self.bn1 = nn.BatchNorm2d(16) self.re1 = nn.ReLU(inplace=True) self.cnn2 = nn.Conv2d(16, 16, kernel_size=...
class MIDI(Dataset): def __init__(self, piano_roll, max_min_notes, transform=None): self.piano_roll = piano_roll self.max_min_notes = max_min_notes self.transform = transform def __getitem__(self, ind): item = self.piano_roll[ind] item = convert_midi(item, self.max_min_no...
def kitti_2015_train(img_height, img_width, batch_size, num_workers): transforms = [tf.CreateScaledImage(True), tf.Resize((img_height, img_width), image_types=('color',)), tf.ConvertDepth(), tf.CreateColoraug(), tf.ToTensor(), tf.NormalizeZeroMean(), tf.AddKeyValue('domain', 'kitti_2015_train_depth'), tf.AddKeyValu...
def replace_unk_full(beam_lst, lst_src, int_order): result = [] for (idx, num) in enumerate(int_order): fields = get_wikibio_poswrds(lst_src[num]) fields = [wrd for ((k, idx), wrd) in fields.items()] result.append(fields) result_2 = [] x_idx = 0 temp_store = [] for ii in ...
def get_normalizer(): if FLAGS.backbone.startswith('efficientnetv2'): bn = effnetv2_utils.BatchNormalization else: bn = keras.layers.BatchNormalization if FLAGS.ghost_bn: split = [int(x) for x in FLAGS.ghost_bn.split(',')] prefix = ('tpu_' if FLAGS.backbone.startswith('effici...
def main(args): config = load_config(args) global_train_config = config['training_params'] (models, model_names) = config_modelloader_and_convert2mlp(config)
def _find_tied_weights_for_meta(model): _name_dict = dict() _tied_parameters = dict() for (name, param) in model.named_parameters(): if hasattr(param, 'checkpoint_name'): if (param.checkpoint_name in _name_dict): _tied_parameters[name] = _name_dict[param.checkpoint_name] ...
class transfer_conv(nn.Module): def __init__(self, in_feature, out_feature): super().__init__() self.in_feature = in_feature self.out_feature = out_feature self.Connectors = nn.Sequential(nn.Conv2d(in_feature, out_feature, kernel_size=1, stride=1, padding=0, bias=False), nn.BatchNorm...
_model def seresnet33ts(pretrained=False, **kwargs): return _create_byobnet('seresnet33ts', pretrained=pretrained, **kwargs)
def get_data(): seq_len = 480 data = pd.DataFrame(pd.date_range('', periods=seq_len), columns=['ds']) data.insert(1, 'y', np.random.rand(seq_len)) expect_horizon = np.random.randint(40, 50) return (data, expect_horizon)
def kEfficientNetBN(N=0, include_top=True, input_tensor=None, input_shape=None, pooling='avg', classes=1000, kType=2, dropout_rate=None, drop_connect_rate=0.2, skip_stride_cnt=(- 1), dropout_all_blocks=False, **kwargs): result = None if (N == (- 1)): dropout_rate = (0.2 if (dropout_rate is None) else dr...
def print_model_settings_dict(settings): print('Settings dict:') all_vars = [(k, v) for (k, v) in list(settings.items())] all_vars = sorted(all_vars, key=(lambda x: x[0])) for (var_name, var_value) in all_vars: print('\t{}: {}'.format(var_name, var_value))
class MSRANerLoader(Loader): def __init__(self): super().__init__() def _load(self, path): dataset = [] sentence = [] label = [] with open(path) as f: for line in f: if ((len(line) == 0) or (line[0] == '\n')): if (len(senten...
def xavier_init(module, gain=1, bias=0, distribution='normal'): assert (distribution in ['uniform', 'normal']) if (distribution == 'uniform'): nn.init.xavier_uniform_(module.weight, gain=gain) else: nn.init.xavier_normal_(module.weight, gain=gain) if (hasattr(module, 'bias') and (module....
class BasicConv2d(nn.Module): def __init__(self, in_channels, out_channels, **kwargs): super(BasicConv2d, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs) self.bn = nn.BatchNorm2d(out_channels, eps=1e-05) def forward(self, x): x = self.conv(...
def show_waiting(line_: str) -> Optional[str]: usage = 'Usage: %flow show_waiting [global|all]' line = line_.split() if ((len(line) == 0) or (line[0] == 'global')): sym_sets: Iterable[Iterable[Symbol]] = [flow().global_scope.all_symbols_this_indentation()] elif (line[0] == 'all'): sym_se...
('pseudolabeling') class PseudoLabelingPredictor(SuperGluePredictor): def dump_line(self, outputs: JsonDict) -> str: if (not self.numeric): prediction = outputs['label'] else: prediction = outputs['prediction'] if isinstance(prediction, float): pre...
class MatterportObjectsSplit(): def __init__(self, dataset, split='train'): self.cfg = dataset.cfg path_list = dataset.get_split_list(split) log.info('Found {} pointclouds for {}'.format(len(path_list), split)) self.path_list = path_list self.split = split self.datase...
def modify_model_after_init(model, training_args, adapter_args, adapter_config): freeze_model_params(model, adapter_args, adapter_config) if adapter_args.intrinsic_model: if adapter_args.intrinsic_said: model = intrinsic_dimension_said(model, adapter_args.intrinsic_dim, training_args.output_...
def nin_cifar100(num_classes=100, **kwargs): return get_nin_cifar(num_classes=num_classes, model_name='nin_cifar100', **kwargs)
class DataTrainingArguments(): data_file: str = field(metadata={'help': 'Text file with one unlabeled instance per line.'}) class_names_file: str = field(metadata={'help': 'Text file with one class name per line.'}) use_fast_tokenizer: bool = field(default=True, metadata={'help': 'Whether to use one of the ...
def conse(path): con = sqlite3.connect(path) cur = con.cursor() sql = 'SELECT start,end,globalPid FROM CUPTI_ACTIVITY_KIND_KERNEL' cur.execute(sql) data = cur.fetchall() conse = {} for i in data: if (i[2] not in conse): conse[i[2]] = {} conse[i[2]]['start'] = ...
class ConvMlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_args={'act': 'gelu'}, norm_args=None, drop=0.0): super().__init__() out_features = (out_features or in_features) hidden_features = (hidden_features or in_features) self.fc1 = nn.Con...
def sp_noise(image, prob): output = np.zeros(image.shape, np.uint8) thres = (1 - prob) for i in range(image.shape[0]): for j in range(image.shape[1]): rdn = random.random() if (rdn < prob): output[i][j] = 0 elif (rdn > thres): outpu...
def load_model_for_evaluate(pre_model_path, model): map_location = torch.device('cpu') load_dict = torch.load(pre_model_path, map_location) pretrained_dict = load_dict['model_params'] model_dict = model._networks.state_dict() pretrained_dict = {k: v for (k, v) in pretrained_dict.items() if (k in mod...