code
stringlengths
101
5.91M
def prologue(args): if ((not hasattr(args, 'id')) or (args.id is None)): args.id = np.random.randint(10000) args.outdir = (args.outdir + f'/{args.arch}/{args.id}/') if (not os.path.exists(args.outdir)): os.makedirs(args.outdir) copy_code(args.outdir) train_dataset = get_dataset(args....
def build_optimizer(config, model): assert isinstance(config, dict) opt_type = config['opt_type'].upper() base_lr = config['base_lr'] base_wd = config.get('base_wd', 0.0) bias_lr_multiplier = config.get('bias_lr_multiplier', 1.0) bias_wd_multiplier = config.get('bias_wd_multiplier', 1.0) if ...
def test_dataset(csv_file_path: str): df = load_matrix_from_csv(csv_file_path, start_col_index=0, end_col_index=4, header=0) rumor_num = 0 non_rumor_num = 0 for tweet_row in df[:]: tweet_id = tweet_row[0] created_time = tweet_row[1] tweet_text = tweet_row[2] tag = tweet_r...
class BernoulliLayer(Initializable, ProbabilisticLayer): def __init__(self, dim_X, dim_Y, **kwargs): super(BernoulliLayer, self).__init__(**kwargs) self.dim_X = dim_X self.dim_Y = dim_Y self.linear_transform = Linear(name=(self.name + '_linear'), input_dim=dim_Y, output_dim=dim_X, we...
class Res_CBAM_block(nn.Module): def __init__(self, in_channels, out_channels, stride=1): super(Res_CBAM_block, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1) self.bn1 = nn.BatchNorm2d(out_channels) self.relu = nn.ReLU(inpl...
def output_results(results, output=None): headers = ['Scenario Name', 'Steps', 'Total Reward'] rows = [] for name in AVAIL_BENCHMARKS: rows.append([name, *results[name].get_formatted_summary()]) table = PrettyTable(headers) for row in rows: table.add_row(row) if (output is not No...
def collect_env_info(): has_gpu = torch.cuda.is_available() torch_version = torch.__version__ from torch.utils.cpp_extension import CUDA_HOME, ROCM_HOME has_rocm = False if ((getattr(torch.version, 'hip', None) is not None) and (ROCM_HOME is not None)): has_rocm = True has_cuda = (has_gp...
class MobileNetV3(nn.Module): def __init__(self, channels, exp_channels, init_block_channels, final_block_channels, classifier_mid_channels, kernels3, use_relu, use_se, first_stride, final_use_se, in_channels=3, in_size=(224, 224), num_classes=1000): super(MobileNetV3, self).__init__() self.in_size ...
class Normalize(object): def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self, image, target): image = F.normalize(image, mean=self.mean, std=self.std) return (image, target)
def init_random_seed(random_seed): import random random.seed(random_seed) import numpy as np np.random.seed(random_seed) torch.manual_seed(random_seed) torch.cuda.manual_seed_all(random_seed)
def txt_logger(txtname, log): with open(txtname, 'a') as f: for item in log: f.write(item) f.write(',') f.write('\n')
def test_attribute_unpacking_no_overwrite(): run_cell('\n class Foo:\n def __init__(self, x):\n self.x = x\n ') run_cell('x = Foo(5)') run_cell('y = Foo(6)') run_cell('w = 42') run_cell('z = 43') run_cell('x.x, y.x = w + 2, z + 3') run_cell('s, t = 12,...
def store_standard_system(polsys, **nbvar): from phcpy.phcpy2c3 import py2c_syscon_clear_standard_system from phcpy.phcpy2c3 import py2c_syscon_initialize_number_of_standard_polynomials from phcpy.phcpy2c3 import py2c_syscon_store_standard_polynomial py2c_syscon_clear_standard_system() dim = len(pol...
class QasmParser(): def __init__(self, filename): if (filename is None): filename = '' self.lexer = QasmLexer(filename) self.tokens = self.lexer.tokens self.parse_dir = tempfile.mkdtemp(prefix='qiskit') self.precedence = (('left', '+', '-'), ('left', '*', '/'), ('...
class SemanticSegmentationModelOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None
def mit_convert(ckpt): new_ckpt = OrderedDict() for (k, v) in ckpt.items(): if k.startswith('head'): continue elif k.startswith('patch_embed'): stage_i = int(k.split('.')[0].replace('patch_embed', '')) new_k = k.replace(f'patch_embed{stage_i}', f'layers.{(stag...
class LocalSearch(Algorithm[(S, R)], threading.Thread): def __init__(self, problem: Problem[S], mutation: Mutation, termination_criterion: TerminationCriterion=store.default_termination_criteria, comparator: Comparator=store.default_comparator): super(LocalSearch, self).__init__() self.comparator = ...
_searchspace('continuous') class ContinuousSearchSpace(BaseSearchSpace): def __init__(self, bound, interval=None, value=None, type=None): super().__init__(bound, interval, value, 'continuous') def get_value(self): if (self.bound[1] > 1): int_num = random.randrange(int(self.bound[0]),...
def output_real_images(dataloader, num_imgs, real_dir): img_counter = 0 batch_size = dataloader.batch_size dataloader = iter(dataloader) for i in range((num_imgs // batch_size)): (real_imgs, _) = next(dataloader) for img in real_imgs: save_image(img, os.path.join(real_dir, f'...
def load_from_pretrained(args, pretrained_model_name_or_path): config = AutoConfig.from_pretrained(pretrained_model_name_or_path, num_labels=(args.num_labels if hasattr(args, 'num_labels') else None), finetuning_task=args.task_name.lower(), cache_dir=args.cache_dir) tokenizer = AutoTokenizer.from_pretrained(pre...
class BaseModel(): def __init__(self, opt): self.opt = opt self.device = torch.device(('cuda' if (opt['num_gpu'] != 0) else 'cpu')) self.is_train = opt['is_train'] self.schedulers = [] self.optimizers = [] def feed_data(self, data): pass def optimize_parameter...
class MSC(nn.Module): def __init__(self, base, scales=None): super(MSC, self).__init__() self.base = base if scales: self.scales = scales else: self.scales = [0.5, 0.75] def forward(self, x): import pdb logits = self.base(x) return ...
class Xception(nn.Module): def __init__(self, num_classes=1000, in_chans=3, drop_rate=0.0, global_pool='avg'): super(Xception, self).__init__() self.drop_rate = drop_rate self.global_pool = global_pool self.num_classes = num_classes self.num_features = 2048 self.conv1...
class TestPolicy(unittest.TestCase): def setUp(self): sess = tf.get_default_session() if (sess is None): tf.InteractiveSession() def test_output_sym(self): with tf.Session() as sess: obs_dim = 23 action_dim = 7 self.env = DummyEnv(obs_dim, ...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm3d(planes) self.conv2 = nn.Conv3d(planes, plan...
def prep_command_tokens(tokenlist, token_format=token_format): return [CommandToken(tok[0], token_format.format(tok[0]), tok[1]) for tok in tokenlist]
class ShuffleNet(nn.Module): def __init__(self, channels, init_block_channels, groups, in_channels=3, in_size=(224, 224), num_classes=1000): super(ShuffleNet, self).__init__() self.in_size = in_size self.num_classes = num_classes self.features = nn.Sequential() self.features....
def contrastive_loss(labels, embeddings_anchor, embeddings_positive, margin=1.0): distances = math_ops.sqrt(math_ops.reduce_sum(math_ops.square((embeddings_anchor - embeddings_positive)), 1)) return math_ops.reduce_mean(((math_ops.to_float(labels) * math_ops.square(distances)) + ((1.0 - math_ops.to_float(labels...
def setup_task(cfg): assert ('task' in cfg.run_cfg), 'Task name must be provided.' task_name = cfg.run_cfg.task task = registry.get_task_class(task_name).setup_task(cfg=cfg) assert (task is not None), 'Task {} not properly registered.'.format(task_name) return task
def imagenet_dino_small_pretrained(output_dim): model_kwargs = dict(patch_size=16, embed_dim=384, depth=12, num_heads=6, num_classes=output_dim) model = load_dino_model('/scratch/nvg7279/dino_models/dino_deitsmall16_pretrain.pth', **model_kwargs) return _vit_replace_fc(model, output_dim)
.dataclass class FlaxSeq2SeqSequenceClassifierOutput(ModelOutput): logits: jnp.ndarray = None past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None decoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None decoder_attentions: Optional[Tuple[jnp.ndarray]] = None cross_attentions: Optional[Tupl...
def pidfile_taken(path, verbose=False, force=False): try: os.makedirs(os.path.dirname(path), exist_ok=True) fd = os.open(path, ((os.O_CREAT | os.O_EXCL) | os.O_RDWR)) except OSError as e: if (e.errno == errno.EEXIST): conflicter = 'race' try: with ...
class NullMutation(Mutation[Solution]): def __init__(self): super(NullMutation, self).__init__(probability=0) def execute(self, solution: Solution) -> Solution: return solution def get_name(self): return 'Null mutation'
class VocabUtility(): def vocab_range_from_per_partition_vocab_size(per_partition_vocab_size, rank, world_size): index_f = (rank * per_partition_vocab_size) index_l = (index_f + per_partition_vocab_size) return (index_f, index_l) def vocab_range_from_global_vocab_size(global_vocab_size, ...
.skipif((Box2D is None), reason='Box2D not installed') def test_lunar_lander(): _test_lander(LunarLander(), seed=0)
class TensorboardLogger(object): def __init__(self, log_dir): self.writer = SummaryWriter(logdir=log_dir) self.step = 0 def set_step(self, step=None): if (step is not None): self.step = step else: self.step += 1 def update(self, head='scalar', step=Non...
def tensor_size(array): if is_numpy_array(array): return np.size(array) elif is_torch_tensor(array): return array.numel() elif is_tf_tensor(array): import tensorflow as tf return tf.size(array) elif is_jax_tensor(array): return array.size else: raise V...
def auto_augment_transform(config_str, hparams): config = config_str.split('-') policy_name = config[0] config = config[1:] for c in config: cs = re.split('(\\d.*)', c) if (len(cs) < 2): continue (key, val) = cs[:2] if (key == 'mstd'): hparams.setd...
def analyze(prediction_file, gold_file): with open(prediction_file) as f: prediction = json.load(f) with open(gold_file) as f: gold = json.load(f) metrics = {'em': 0, 'f1': 0, 'prec': 0, 'recall': 0, 'sp_em': 0, 'sp_f1': 0, 'sp_prec': 0, 'sp_recall': 0, 'joint_em': 0, 'joint_f1': 0, 'joint_p...
def test_nms_device_and_dtypes_cpu(): iou_thr = 0.7 base_dets = np.array([[49.1, 32.4, 51.0, 35.9, 0.9], [49.3, 32.9, 51.0, 35.3, 0.9], [35.3, 11.5, 39.9, 14.5, 0.4], [35.2, 11.7, 39.7, 15.7, 0.3]]) dets = base_dets.astype(np.float32) (supressed, inds) = nms(dets, iou_thr) assert (dets.dtype == supr...
def process_tokens(temp_tokens): tokens = [] for token in temp_tokens: flag = False l = ('-', '', '', '', '/', '~', '"', "'", '', '', '', '', '') to_append = re.split('([{}])'.format(''.join(l)), token) for t in to_append: if (t != ''): tokens.append(t...
def _eval_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn): iterations_per_loop_var = _create_or_get_iterations_per_loop() (single_tpu_eval_step, host_calls, captured_scaffold_fn, captured_eval_hooks) = model_fn_wrapper.convert_to_single_tpu_eval_step(dequeue_fn) def multi_tpu_eval_steps_on_single_shard(): ...
class FurthestPointSamplingWithDist(Function): def forward(ctx, points_dist: torch.Tensor, num_points: int) -> torch.Tensor: assert points_dist.is_contiguous() (B, N, _) = points_dist.size() output = points_dist.new_zeros([B, num_points], dtype=torch.int32) temp = points_dist.new_zer...
def test_double_Laurent_polynomial(vrblvl=0): set_double_Laurent_dimension(2, vrblvl) dim = get_double_Laurent_dimension(vrblvl) print('the dimension :', dim) org = 'x*y^(-3) - 1;' idx = 1 set_double_Laurent_polynomial(idx, dim, org, vrblvl) pol = get_double_Laurent_polynomial(idx, vrblvl) ...
def linspace(start: torch.Tensor, stop: torch.Tensor, num: int): steps = (torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1)) for i in range(start.ndim): steps = steps.unsqueeze((- 1)) out = (start[None] + (steps * (stop - start)[None])) return out
class MPDataset(IterableDataset): def __init__(self, root, transform=None, target_transform=None, top_k=(1, 5), keep_rgb: bool=False, shuffle: bool=False, num_gpus: int=1, rank_id: int=0, epoch: int=0, drop_last: bool=False): super(MPDataset).__init__() self.root = root self.transform = tran...
def trigger_loss4(model, criterion, inputs, backdoor_inputs, backdoor_labels, pattern, extractor, device, grads): convs = model.state_dict()['conv1.weight'] avg_convs = convs.mean([0]) w = convs[(0, ...)].size()[1] assert (w == 7) resize = transforms.Resize((w, w)) backdoor_conv_weight = resize(...
class BasicBlock(nn.Module): expansion = 1 num_layers = 2 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) ...
def isclose(a, b, rel_tol=1e-05, abs_tol=0.0): return (abs((a - b)) <= max((rel_tol * max(abs(a), abs(b))), abs_tol))
def load_embedding(dataset: str, architecture: str, seed: int, step: int, layer: int) -> np.ndarray: folder_path = get_embedding_folder(dataset, architecture, seed, step, layer) if (not os.path.exists(folder_path)): print('Computing representations for model') os.makedirs(folder_path) re...
def export_saved_model(self, export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False, checkpoint_path=None, experimental_mode=ModeKeys.PREDICT, save_incr_model=True): if (not serving_input_receiver_fn): raise ValueError('An input_receiver_fn must be defined.') input_receiver_fn_map ...
def main(args): if (args.buffer_size < 1): args.buffer_size = 1 if ((args.max_tokens is None) and (args.max_sentences is None)): args.max_sentences = 1 assert ((not args.sampling) or (args.nbest == args.beam)), '--sampling requires --nbest to be equal to --beam' assert ((not args.max_sen...
def result(args, records): print(' test-run information ') print((('\x1b[1m\tModel\x1b[0m: \x1b[0;31m' + args.model) + '\x1b[0m')) print((('\x1b[1m\tStage\x1b[0m: \x1b[0;31m' + args.stage) + '\x1b[0m')) print((('\x1b[1m\tDataset\x1b[0m: \x1b[0;31m' + args.dataset) + '\x1b[0m')) if args.cores: ...
def _copy_dir(files, run_dir): src = os.path.join(run_dir, 'src') if (not os.path.exists(src)): os.makedirs(src) for file_name in files: if os.path.isdir(file_name): shutil.copytree(file_name, os.path.join(src, file_name)) else: shutil.copyfile(file_name, os.p...
def get_matched_ner_from_file(gold_file, pred_file, up_ignore_layer=0): gold_lines = open(gold_file, encoding='utf-8').readlines() pred_lines = open(pred_file, encoding='utf-8').readlines() sentence_num = len(gold_lines) assert (sentence_num == len(pred_lines)) gold_entity = [] pred_entity = [] ...
def dubbing_video(video_path, out_video_path, text_info, font_size=0.5, font_v_pos=0.95, font_color=(0, 0, 255)): extract_audio(video_path, './temp_audio.wav') video = cv2.VideoCapture(video_path) frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIG...
def main(_run, seed, test_mode, evaluation_metric, minimize, total_trials, parameterization): ((train_dl, val_dl, test_dl), input_dim, output_dim, static_dim, model_interpolation, return_sequences) = load_data(test_mode=test_mode) def train_evaluate(parameterization): (model_params, trainer_params) = ha...
def get_pyramidnet(blocks, alpha, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs): if (blocks == 10): layers = [1, 1, 1, 1] elif (blocks == 12): layers = [2, 1, 1, 1] elif (blocks == 14): layers = [2, 2, 1, 1] elif (blocks == 16): ...
def const_or_evo_func(x): if callable(x): return x else: return (lambda y: ((y * 0) + x))
class FlaxBartForConditionalGeneration(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
def training_loss_2nd_item_task(data, batch_index, model, sess, train_data, is_training): train_loss = 0.0 num_batch = (data.oracle_num_items // setting.batch_size) for index in batch_index: (b_target_item, b_k_shot_user, b_second_order_items, b_third_order_users, b_oracle_item_ebd, b_mask_num_secon...
class AvgMeter(object): def __init__(self, num=40): self.num = num self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 self.losses = [] def update(self, val, n=1): self.val = val self.sum += (val * n) ...
def unit_postprocessing(unit, vid_size=None): unit = unit.squeeze() unit = unit.cpu().detach().numpy() unit = np.clip(unit, (- 1), 1) unit = np.round(((np.transpose(unit, (1, 2, 0)) + 1.0) * 127.5)).astype(np.uint8) if ((unit.shape[:2][::(- 1)] != vid_size) and (vid_size is not None)): unit ...
def convert(src, dst, depth): if (depth not in arch_settings): raise ValueError('Only support ResNet-50 and ResNet-101 currently') block_nums = arch_settings[depth] caffe_model = mmcv.load(src, encoding='latin1') blobs = (caffe_model['blobs'] if ('blobs' in caffe_model) else caffe_model) sta...
def validate_status_exec(g_code, library, device='gpu') -> (ExecutionStatus, str): write_code = wrap_code_with_device(g_code, library, device) with open('/tmp/tmp{}.py'.format(CURRENT_TIME), 'w') as f: f.write(write_code) try: if (library == 'tf'): import tensorflow as tf ...
class DepthwiseConv2d(Conv2d): def convolve(self, x: TensorType) -> tf.Tensor: if isinstance(x, inducing_variables.DepthwiseInducingImages): return tf.nn.depthwise_conv2d(input=x.as_images, filter=self.filters, strides=(1, 1, 1, 1), padding='VALID') return self.kernel.convolve(input=x, f...
def _calculate_expected_aligned_error(alignment_confidence_breaks: torch.Tensor, aligned_distance_error_probs: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor)]: bin_centers = _calculate_bin_centers(alignment_confidence_breaks) return (torch.sum((aligned_distance_error_probs * bin_centers), dim=(- 1)), bin_c...
def contrastStretching(img, saturated_pixel=0.004): ' constrast stretching according to imageJ\n values = np.sort(img, axis=None) nr_pixels = np.size(values) lim = int(np.round((saturated_pixel * nr_pixels))) v_min = values[lim] v_max = values[((- lim) - 1)] img = (((img - v_min) * 255.0...
class LeanParser(): lean_file: LeanFile token_lines: List[List[Token]] line: int column: int pos: int current_token: Token parameter_positions: Dict[(Tuple[(int, int)], List[Tuple[(int, int)]])] tactic_block_positions: Set[Tuple[(int, int)]] def __init__(self, lean_file: LeanFile, li...
def build_fake_yaml2(sigopt_api_token, sigopt_project_id): fake_yaml = '\n model:\n name: fake_yaml\n framework: tensorflow\n inputs: x\n outputs: op2_to_store\n device: cpu\n evaluation:\n accuracy:\n metric:\n topk: 1\n ...
def parse_args(): parser = argparse.ArgumentParser(description='MMDet test (and eval) a model') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--work-dir', help='the directory to save the file containing evaluati...
class MetricBase(): def __init__(self, name): self.name = name self._dataset_obj = None self._progress_lo = None self._progress_hi = None self._progress_max = None self._progress_sec = None self._progress_time = None self._reset() def close(self): ...
_end_docstrings(PIPELINE_INIT_ARGS) class Text2TextGenerationPipeline(Pipeline): return_name = 'generated' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.check_model_type((TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if (self.framework == 'tf') else MODEL_FOR_SEQ_TO_SEQ...
_module() class CityscapesDataset(CocoDataset): METAINFO = {'classes': ('person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle'), 'palette': [(220, 20, 60), (255, 0, 0), (0, 0, 142), (0, 0, 70), (0, 60, 100), (0, 80, 100), (0, 0, 230), (119, 11, 32)]} def filter_data(self) -> List[dict]: ...
class AutoConfigTest(unittest.TestCase): def test_module_spec(self): self.assertIsNotNone(transformers.models.auto.__spec__) self.assertIsNotNone(importlib.util.find_spec('transformers.models.auto')) def test_config_from_model_shortcut(self): config = AutoConfig.from_pretrained('bert-bas...
def training_loss_3rd_user_task(data, batch_index, model, sess, train_data, is_training): train_loss = 0.0 num_batch = (data.oracle_num_users // setting.batch_size) for index in batch_index: (b_target_user, b_k_shot_item, b_second_order_users, b_third_order_items, b_oracle_user_ebd, b_mask_num_secon...
def cfg_from_list(cfg_list): from ast import literal_eval assert ((len(cfg_list) % 2) == 0) for (k, v) in zip(cfg_list[0::2], cfg_list[1::2]): key_list = k.split('.') d = __C for subkey in key_list[:(- 1)]: assert (subkey in d) d = d[subkey] subkey = k...
class ShearX(object): def __init__(self, fillcolor=(128, 128, 128)): self.fillcolor = fillcolor def __call__(self, x, magnitude): return x.transform(x.size, Image.AFFINE, (1, (magnitude * random.choice([(- 1), 1])), 0, 0, 1, 0), Image.BICUBIC, fillcolor=self.fillcolor)
def cosine_lr_schedule(optimizer, epoch, max_epoch, init_lr, min_lr): lr = ((((init_lr - min_lr) * 0.5) * (1.0 + math.cos(((math.pi * epoch) / max_epoch)))) + min_lr) for param_group in optimizer.param_groups: param_group['lr'] = lr
def test_version_used_when_live(): run_cell('x = 0') run_cell('\n if True:\n y = 7\n else:\n # even though this branch is not taken,\n # liveness-based usage should detect the\n # version of `x` used at the time it was\n # live, meaning cell 1...
def _infunc(x_val, func, c, d, more_args, epsrel=1.49e-08): myargs = ((x_val,) + more_args) return integrate.quad(func, c, d, args=myargs, epsrel=epsrel, limit=2000)[0]
class CIFAR10(data.Dataset): base_folder = 'cifar-10-batches-py' url = ' filename = 'cifar-10-python.tar.gz' tgz_md5 = 'c58f30108f718f92721af3b95e74349a' train_list = [['data_batch_1', 'c99cafc152244af753f735de768cd75f'], ['data_batch_2', 'd4bba439e000b95fd0a9bffe97cbabec'], ['data_batch_3', '54ebc0...
def mk_vis_txt_pair_datalist(anno_path, data_ratio=1.0, vis_id_key='coco_id', txt_key='caption'): raw_datalist = load_datalist_with_ratio(anno_path, data_ratio) datalist = [] for raw_d in raw_datalist: d = dict(txt=raw_d[txt_key], vis_id=raw_d[vis_id_key]) datalist.append(d) grouped = de...
def test_kinetic_energy_shape(): (_, log_f) = make_dummy_log_f() x = make_dummy_x() kinetic_energy_fn = physics.kinetic.create_laplacian_kinetic_energy(log_f) kinetic_energy_fn = jax.vmap(kinetic_energy_fn, in_axes=(None, 0), out_axes=0) kinetic_energies = kinetic_energy_fn(None, x) assert (kine...
class Trainer(object): def __init__(self, args): if (args.algorithm == 'fed_mutual'): self.train = train_mutual elif (args.algorithm == 'fed_avg'): self.train = train_avg elif (args.algorithm == 'normal'): self.train = train_normal def __call__(self, n...
class WeightedSumTestCases(unittest.TestCase): def test_should_aggregative_sum_work_properly_with_2D_vectors(self) -> None: aggregative_function = WeightedSum() self.assertEqual(1.5, aggregative_function.compute([1.5, 2.9], [1.0, 0.0])) self.assertEqual(2.9, aggregative_function.compute([1.5...
def gender(word, pos=NOUN): w = word.lower() if (pos == NOUN): if w.endswith(gender_masculine): return MASCULINE if w.endswith(gender_feminine): return FEMININE if w.endswith(gender_neuter): return NEUTER for g in gender_majority_vote: ...
class LeakyParallel(nn.Module): def __init__(self, input_size, hidden_size, beta=None, bias=True, threshold=1.0, dropout=0.0, spike_grad=None, surrogate_disable=False, learn_beta=False, learn_threshold=False, graded_spikes_factor=1.0, learn_graded_spikes_factor=False, weight_hh_enable=False, device=None, dtype=None...
def _rm_hp(cs, k): if (k in cs._hyperparameters): cs._hyperparameters.pop(k) for hp in cs.get_hyperparameters(): if hp.name.startswith('{}'.format(k)): cs._hyperparameters.pop(hp.name)
def test_attribute_unpacking(): run_cell('\n class Foo:\n def __init__(self, x):\n self.x = x\n ') run_cell('x = Foo(5)') run_cell('y = Foo(6)') run_cell('w = 42') run_cell('z = 43') run_cell('x.x, y.x = w + 2, z + 3') run_cell('z = 9001') run_cell...
class Cat(nn.Module): def __init__(self, dim=1): super(Cat, self).__init__() self.dim = dim def forward(self, x): return torch.cat(x, dim=self.dim)
def approx_corr(D, X, Y): D_X = D(X) with torch.no_grad(): XY = (X Y.transpose(1, 0)) idx_Y = torch.argmax((XY - D_X), dim=0) Y_inv = X[idx_Y] W_loss_XY = (D_X - D(Y_inv)).mean() with torch.no_grad(): W_loss_nograd_XY = (((- (X ** 2).sum(dim=1)) / 2).mean() + ((Y_inv * Y...
class InvertedResidual(nn.Module): def __init__(self, inp, oup, stride, expand_ratio): super(InvertedResidual, self).__init__() self.stride = stride assert (stride in [1, 2]) hidden_dim = int(round((inp * expand_ratio))) self.use_res_connect = ((self.stride == 1) and (inp == ...
def process_entities(query, doc, mentioned_time: dict) -> dict: location = [] name = [] organization = [] s_time = [] for ent in doc.ents: if (ent.label_ == 'GPE'): location.append(ent.text) elif (ent.label_ == 'LOC'): location.append(ent.text) elif (e...
_experiment def vpgis_inverted_pendulum(ctxt=None, seed=1): set_seed(seed) with LocalTFRunner(ctxt) as runner: env = GarageEnv(normalize(gym.make('InvertedPendulum-v2'))) policy = GaussianMLPPolicy(env_spec=env.spec, hidden_sizes=(32, 32)) baseline = LinearFeatureBaseline(env_spec=env.sp...
class Frame(BaseJsonLogger): def __init__(self, frame_id: int, timestamp: float=None): self.frame_id = frame_id self.timestamp = timestamp self.bboxes = [] def add_bbox(self, bbox_id: int, top: int, left: int, width: int, height: int): bboxes_ids = [bbox.bbox_id for bbox in self....
class SimulationActorAction(AbstractAction): def __init__(self): self.arm_cmd = [] self.arm_mode = pb.POSITION_CONTROL
def get_learning_rate_scheduler(optimizer, args): if (args.lr_decay_iters is not None): num_iters = args.lr_decay_iters else: num_iters = args.train_iters init_step = (- 1) warmup_iter = (args.warmup * num_iters) lr_scheduler = AnnealingLR(optimizer, start_lr=args.lr, warmup_iter=war...
def train_d4rl_sbc(args): test_env = gym.make(args.env_id) test_env.seed(args.seed) state_space = test_env.observation_space action_space = test_env.action_space agent = dc.sbc.SBCAgent(state_space.shape[0], action_space.shape[0], args.log_std_low, args.log_std_high) dset = d4rl.qlearning_datase...
def num_verb_phrases(const_pt): vp_chunks = [] vp_tag = None if (settings.LANGUAGE in ['fr']): lang = settings.LANGUAGE else: lang = 'default' vp_tag = VERB_PHRASE_LANGUAGE_MAP[lang] for leaf in _leaves(const_pt, vp_tag): vp_chunks.append(leaf.leaves()) return len(vp_...