code
stringlengths
101
5.91M
def test_conf_raises_for_unaccessible_arguments(): def conf_scope(a, b, c): answer = 42 with pytest.raises(KeyError): conf_scope(preset={'a': 1}, fallback={'b': 2})
def inference(file, inputs, outputs): inputs_flatten = flatten(inputs) inputs_flatten = update_flatten_list(inputs_flatten, []) outputs_flatten = flatten(outputs) outputs_flatten = update_flatten_list(outputs_flatten, []) sess = onnxruntime.InferenceSession(file) ort_inputs = dict(((sess.get_inp...
.parametrize('return_dataframe', [True, False]) .parametrize('embed_continuous', [True, False]) def test_bayesian_mlp_models(return_dataframe, embed_continuous): tab_preprocessor = TabPreprocessor(cat_embed_cols=embed_cols, continuous_cols=cont_cols) X_tab = tab_preprocessor.fit_transform(df_init) model = B...
def run(cmd, quit_on_error=True, shell=False): p = subprocess.run(cmd, shell=shell, stdout=subprocess.PIPE) if (quit_on_error and (p.returncode != 0)): quit(p.returncode) return p
class DraggableCubePolygon(DraggablePolygon): def __init__(self, canvas, cube_id): cube_xy = ((VectorEnv.CUBE_WIDTH / 2) * np.array([[(- 1), 1], [1, 1], [1, (- 1)], [(- 1), (- 1)]])).tolist() polygon = Polygon(cube_xy, True, color=VectorEnv.CUBE_COLOR) super().__init__(canvas, polygon) ...
class TFRobertaForQuestionAnswering(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
class SimulationActorClientDynamics(AbstractDynamics): def __init__(self, world, robot): self.world = world self.robot = robot def apply(self, state, action): self.robot.arm(action.arm_cmd, action.arm_mode) return None
def order_data(data, param_list, wpgen, planner, maps, classic, quantity): other_quantity = np.array([*param_list.keys()])[[(x != quantity) for x in [*param_list.keys()]]][0] indices = list(data.index) params = [quantity, other_quantity] wpgen_col = (['none'] * len(indices)) planner_col = (['none'] ...
class PixelNormalize(FeatureTransformer): def __init__(self, means, bigdl_type='float'): super(PixelNormalize, self).__init__(bigdl_type, means)
class TestNuScenesLidarseg(unittest.TestCase): def setUp(self): assert ('NUSCENES' in os.environ), 'Set NUSCENES env. variable to enable tests.' self.nusc = NuScenes(version='v1.0-mini', dataroot=os.environ['NUSCENES'], verbose=False) def test_num_classes(self) -> None: self.assertEqual(...
class GroundtruthFilterTest(tf.test.TestCase): def test_filter_groundtruth(self): input_image = tf.placeholder(tf.float32, shape=(None, None, 3)) input_boxes = tf.placeholder(tf.float32, shape=(None, 4)) input_classes = tf.placeholder(tf.int32, shape=(None,)) input_is_crowd = tf.plac...
def ThresholdSumOther4(array): scaled_array = scaling4(array) threshold = np.median(scaled_array, axis=0) lower_threshold_indices = (scaled_array > threshold) scaled_array[lower_threshold_indices] = 0 return np.sum(scaled_array.T, axis=0)
def get_parser(): parser = argparse.ArgumentParser(description='MeTRAbs 3D Human Pose Estimator', allow_abbrev=False) parser.add_argument('--comment', type=str, default=None) parser.add_argument('--seed', type=int, default=1, help='Seed for the random number generators') parser.add_argument('--wandb-pro...
def np2pil(arr: ty.A, /) -> Image: if (arr.dtype == np.uint8): return Image.fromarray(arr) assert (arr.max() <= 1) return Image.fromarray((arr * 255).astype(np.uint8))
def DirectedEdgeDetect(alpha=0, direction=(0.0, 1.0), name=None, deterministic=False, random_state=None): alpha_param = iap.handle_continuous_param(alpha, 'alpha', value_range=(0, 1.0), tuple_to_uniform=True, list_to_choice=True) direction_param = iap.handle_continuous_param(direction, 'direction', value_range=...
def bn(channel): layer = nn.BatchNorm2d(channel) nn.init.constant(layer.weight, 1) nn.init.constant(layer.bias, 0) return layer
def main(): parser = argparse.ArgumentParser() parser.add_argument('--data_dir', default=None, type=str, required=True, help='The input data dir. Should contain the .tsv files (or other data files) for the task.') parser.add_argument('--model_name_or_path', default=None, type=str, required=True, help='Path ...
def test_brace_initialization(): a = m.BraceInitialization(123, 'test') assert (a.field1 == 123) assert (a.field2 == 'test') b = m.NoBraceInitialization([123, 456]) assert (b.vec == [123, 456])
class MaxIteration(JavaValue): def __init__(self, max, bigdl_type='float'): JavaValue.__init__(self, None, bigdl_type, max)
def get_percentile_min_max(input, lower_percentile, upper_percentile, output_tensor=False): input_length = input.shape[0] lower_index = round((input_length * (1 - (lower_percentile * 0.01)))) upper_index = round(((input_length * upper_percentile) * 0.01)) upper_bound = torch.kthvalue(input, k=upper_inde...
def build_inference_based_loader(cfg: CfgNode, dataset_cfg: CfgNode, model: torch.nn.Module, embedder: Optional[torch.nn.Module]=None) -> InferenceBasedLoader: dataset = build_bootstrap_dataset(dataset_cfg.DATASET, dataset_cfg.IMAGE_LOADER) meta = MetadataCatalog.get(dataset_cfg.DATASET) training_sampler = ...
def _get_creation_string() -> str: argv = sys.argv argv[0] = argv[0].split('/')[(- 1)] return ('python ' + ' '.join(argv))
def get_model_loader(filename): if filename.endswith('.npy'): assert os.path.isfile(filename), filename return ParamRestore(np.load(filename, encoding='latin1').item()) else: return SaverRestore(filename)
class ConvE(torch.nn.Module): def __init__(self, d, d1, d2, **kwargs): super(ConvE, self).__init__() self.in_channels = kwargs['in_channels'] self.out_channels = kwargs['out_channels'] self.filt_h = kwargs['filt_h'] self.filt_w = kwargs['filt_w'] self.E = torch.nn.Emb...
_task('speech_text_joint_to_text') class SpeechTextJointToTextTask(SpeechToTextTask): def add_args(cls, parser): super(SpeechTextJointToTextTask, cls).add_args(parser) parser.add_argument('--parallel-text-data', default='', help='path to parallel text data directory') parser.add_argument('--...
class SEModule(nn.Module): def __init__(self, channels, reduction=16, act_layer=nn.ReLU, gate_layer='sigmoid', reduction_ratio=None, reduction_channels=None, min_channels=8, divisor=1): super(SEModule, self).__init__() if (reduction_channels is not None): reduction_channels = reduction_c...
def _worker_loop(dataset_kind, dataset, index_queue, data_queue, done_event, auto_collation, collate_fn, drop_last, seed, init_fn, worker_id, num_workers): try: signal_handling._set_worker_signal_handlers() torch.set_num_threads(1) random.seed(seed) torch.manual_seed(seed) gl...
class ModifiedVGG16Model(torch.nn.Module): def __init__(self, model=None): super(ModifiedVGG16Model, self).__init__() model = models.vgg16(pretrained=True) self.features = model.features self.classifier = nn.Sequential(nn.Dropout(), nn.Linear(25088, 4096), nn.ReLU(inplace=True), nn.D...
class ConditionalMLP(MLP): def __init__(self, input_dim, condition_dims, *args, verbose=False, **kwargs): self._condition_dims = condition_dims self._condition_keys = sorted(self._condition_dims.keys()) concat_dim = (input_dim + sum(condition_dims.values())) super(ConditionalMLP, sel...
class HourGlassResidual(nn.Module): def __init__(self, in_channels, out_channels): super(HourGlassResidual, self).__init__() self.skip_layer = (Identity() if (in_channels == out_channels) else nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=True), nn.BatchNorm2d(out_channels))...
class RDB(nn.Module): def __init__(self, in_channels, growthRate, num_layer): super(RDB, self).__init__() in_channels_ = in_channels modules = [] for i in range(num_layer): modules.append(dense_layer(in_channels_, growthRate)) in_channels_ += growthRate ...
def search_raw_array_pytorch(res, xb, xq, k, D=None, I=None, metric=faiss.METRIC_L2): assert (xb.device == xq.device) (nq, d) = xq.size() if xq.is_contiguous(): xq_row_major = True elif xq.t().is_contiguous(): xq = xq.t() xq_row_major = False else: raise TypeError('ma...
def has_cl_indicator(span): ind_list = (de_claim_indicators if (lang == 'de') else claim_indicators) for token in span: if (token.text in ind_list): return 1 return 0
def train(): print(f'Starting training {config.name}...') train_losses = [] t_start = time() while True: for input in train_loader: config.step += 1 input = input.to(config.device) (noisy_input, noise_tensor) = add_noise(input) loss = train_step(in...
def evaluate(model): infer = model.signatures['serving_default'] output_dict_keys = infer.structured_outputs.keys() output_name = list(output_dict_keys)[0] from neural_compressor import METRICS metrics = METRICS('tensorflow') metric = metrics['topk']() def eval_func(dataloader, metric): ...
def load_task_with_labels(x, y, labels): tmp = [] for i in labels: tmp.append(np.where((y == i))[0]) idx = np.concatenate(tmp, axis=None) return (x[idx], y[idx])
def require_fairscale(test_case): return unittest.skipUnless(is_fairscale_available(), 'test requires fairscale')(test_case)
class TargetNode(Node): def __init__(self, srcs, hdrs, deps, copts, name=None): super().__init__(name) self.srcs = srcs self.hdrs = hdrs self.deps = deps self.copts = copts def _eval(self, executor): pass
class ModelArguments(): text_model_name_or_path: str = field(metadata={'help': "The text model checkpoint for weights initialization.Don't set if you want to train a model from scratch."}) vision_model_name_or_path: str = field(metadata={'help': "The vision model checkpoint for weights initialization.Don't set ...
def prototype_twitter_VHRED_StandardBias(): state = prototype_state() state['train_dialogues'] = '../TwitterData/Training.dialogues.pkl' state['test_dialogues'] = '../TwitterData/Test.dialogues.pkl' state['valid_dialogues'] = '../TwitterData/Validation.dialogues.pkl' state['dictionary'] = '../Twitte...
def main(): if ((int(os.environ.get('LOCAL_RANK', (- 1))) != (- 1)) and ('--no_cuda' in sys.argv)): from intel_extension_for_transformers.transformers.utils.utility import distributed_init distributed_init() parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments, Opt...
def test_batched_attribution_consistency_decoder_only(saliency_gpt2_model): (texts_single, reference_single) = EXAMPLES['short_texts_decoder'][0] (texts_batch, reference_batch) = EXAMPLES['short_texts_decoder'][1] out_single = saliency_gpt2_model.attribute(texts_single, reference_single, show_progress=False...
def deeplabv3_resnetd50b_coco(pretrained_backbone=False, num_classes=21, aux=True, **kwargs): backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features del backbone[(- 1)] return get_deeplabv3(backbone=backbone, num_classes=num_classes, aux=aux, model_name='deepl...
class GaussianLinearMean(nn.Module): def __init__(self, out_dim: int, noise_init: float, noise_is_shared: bool): super(GaussianLinearMean, self).__init__() self.out_dim = out_dim self.noise_is_shared = noise_is_shared if noise_is_shared: log_var_noise = nn.Parameter((torc...
def test_captured_utf8_3byte_offset1(capsys): msg = '\uffff' msg = ('1' + (msg * ((1024 // len(msg)) + 1))) m.captured_output_default(msg) (stdout, stderr) = capsys.readouterr() assert (stdout == msg) assert (stderr == '')
def IGA_hyper(sample): if sample: return {'penalty_weight': (lambda r: (10 ** r.uniform(1, 5)))} else: return {'penalty_weight': (lambda r: 10.0)}
class RobertaTokenizerFast(metaclass=DummyObject): _backends = ['tokenizers'] def __init__(self, *args, **kwargs): requires_backends(self, ['tokenizers'])
def verify_blender_scene(blender_scene_name: str='Scene') -> bpy.types.Scene: scene = bpy.data.scenes.get(blender_scene_name, None) if (scene is None): log.debug(f'Could not find scene {blender_scene_name}') scene = bpy.data.scenes[0] log.debug(f'Setting scene to {scene.name}') bpy.conte...
def get_image_net(worker, enc_net, ref_net, init_net_path=None): net = get_net(enc_net, ref_net, init_net_path=init_net_path) train_set = _verify_and_get_test_set(worker) return ImageNet(net, train_set)
class MSDeAOT(AOT): def __init__(self, cfg, encoder='mobilenetv2', decoder='fpn'): super().__init__(cfg, encoder, decoder) self.LSTT = MSDualBranchGPM(cfg.MODEL_LSTT_NUM, cfg.MODEL_ENCODER_EMBEDDING_DIM, cfg.MODEL_SELF_HEADS, cfg.MODEL_ATT_HEADS, emb_dropout=cfg.TRAIN_LSTT_EMB_DROPOUT, droppath=cfg....
class RagRetriever(): _init_retrieval = True def __init__(self, config, question_encoder_tokenizer, generator_tokenizer): super().__init__() self.index = (LegacyIndex(config.retrieval_vector_size, (config.index_path or LEGACY_INDEX_PATH)) if (config.index_name == 'legacy') else HFIndex(config.da...
class KaldiWriter(BaseWriter): def __init__(self, wspecifier, write_num_frames=None, compress=False, compression_method=2): if compress: self.writer = kaldiio.WriteHelper(wspecifier, compression_method=compression_method) else: self.writer = kaldiio.WriteHelper(wspecifier) ...
def action_step(state, action_1, action_2, step, sample_len, opt, dataset): (lp, mp, rp) = state seg_len_1 = (((mp - lp) + 1) * action_1) seg_len_2 = ((rp - mp) * action_2) seg_len_1 = min(max(4, seg_len_1), (sample_len / val_opt['min_cycles'])) seg_len_2 = min(max(4, seg_len_2), (sample_len / val_o...
class BottleNeckUpSampling(nn.Module): def __init__(self, in_dim, projectionFactor, out_dim, dtype=torch.float32): super(BottleNeckUpSampling, self).__init__() self.conv0 = nn.Conv2d(in_dim, int((in_dim / projectionFactor)), kernel_size=3, padding=1) self.bn0 = nn.BatchNorm2d(int((in_dim / p...
def download_data(): if (not os.path.exists(zipfile_path)): print(f'Downloading {config.download_url} to {zipfile_path}') urlretrieve(config.download_url, zipfile_path) print(f'Successfully downloaded {zipfile_path}') zip_ref = ZipFile(zipfile_path, 'r') zip_ref.extractall(co...
def main(): args = parse_args() logging_dir = Path(args.output_dir, args.logging_dir) accelerator_project_config = ProjectConfiguration(total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir) accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accu...
def launch_experiment(create_runner_fn, create_agent_fn): run_experiment.load_gin_configs(FLAGS.gin_files, FLAGS.gin_bindings) runner = create_runner_fn(FLAGS.base_dir, create_agent_fn, FLAGS.random_seed, FLAGS.agent_name, FLAGS.game_name, FLAGS.num_iterations) runner.run_experiment()
def jload_twofiles_custom(f1, f2, mode='r'): f1 = _make_r_io_base(f1, mode) jdict1 = json.load(f1) f2 = _make_r_io_base(f2, mode) jdict2 = json.load(f2) f1.close() f2.close() entries = [] for (instance1, instance2) in zip(jdict1, jdict2): entry = {'instruction': instance1['prompt...
class AdapterT5BlockOutput(): feed_forward: AdapterOutput = None self_attention: AdapterOutput = None cross_attention: AdapterOutput = None
def test_small_request() -> None: (start_dt, end_dt) = sanitize_date_range('2019-06-01', None) result = _small_request(start_dt, end_dt) assert (result is not None) assert (not result.empty) assert (len(result.columns) == CURRENT_SC_COLUMNS) assert (len(result) > 0)
class Conv1d_layer(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding='SAME', dilation=1, bias=True, norm='batch', activation='relu', mode='conv'): super(Conv1d_layer, self).__init__() self.conv1d = nn.Sequential() if (mode == 'deconv'): padd...
def model_info(model, verbose=False): n_p = sum((x.numel() for x in model.parameters())) n_g = sum((x.numel() for x in model.parameters() if x.requires_grad)) if verbose: print(('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))) for (i,...
class _BaseMetric(ABC): def __init__(self): self.plottable = False self.integer_fields = [] self.float_fields = [] self.array_labels = [] self.integer_array_fields = [] self.float_array_fields = [] self.fields = [] self.summary_fields = [] self...
class DetrForSegmentation(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def main(): env = CartPoleBulletEnv(renders=False) model = deepq.models.mlp([64]) act = deepq.learn(env, q_func=model, lr=0.001, max_timesteps=100000, buffer_size=50000, exploration_fraction=0.1, exploration_final_eps=0.02, print_freq=10, callback=callback) print('Saving model to cartpole_model.pkl') ...
_task_action class GoTowardPoint(TeleportAction): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self._rotate_agent = self._config.rotate_agent def step(self, *args: Any, r: float, theta: float, **kwargs: Any) -> Observations: y_delta = (kwargs['...
def evaluate(args, model, corpus_dev, corpus_dev_cnt, dev_batches): model.eval() acc_loss = 0 acc_kl_loss = 0 acc_real_ppl = 0 word_cnt = 0 doc_cnt = 0 start_time = time.time() ntokens = 2000 for (idx, batch) in enumerate(dev_batches): (data_batch, count_batch, mask) = fetch_...
def multiprecision_track(target, start, sols, gamma=0, pwt=2, decimals=80): from phcpy.phcpy2c3 import py2c_copy_multprec_container_to_target_system from phcpy.phcpy2c3 import py2c_copy_multprec_container_to_start_system from phcpy.phcpy2c3 import py2c_copy_multprec_container_to_start_solutions from phc...
class VarPropagationLayer(Layer): def __init__(self, layer, use_cov=False, **kwargs): self.layer = layer self.use_cov = use_cov super(VarPropagationLayer, self).__init__(**kwargs) def build(self, input_shape): super(VarPropagationLayer, self).build(input_shape) def call(self,...
def nfsp_default_log_filter(result: ResultDict) -> bool: return (('avg_policy_exploitability' in result) or ((result['training_iteration'] % 100) == 0))
def resnet50_landscape(pretrained=False, progress=True, **kwargs): return _resnet_landscape('resnet50_landscape', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs)
def test_tinydb_observer_artifact_event(tinydb_obs, sample_run): tinydb_obs.started_event(**sample_run) filename = 'setup.py' name = 'mysetup' tinydb_obs.artifact_event(name, filename) assert tinydb_obs.fs.exists(filename) db_run = tinydb_obs.runs.get(eid=1) assert (db_run['artifacts'][0][0]...
class Elementwise(nn.ModuleList): def __init__(self, merge=None, *args): assert (merge in [None, 'first', 'concat', 'sum', 'mlp']) self.merge = merge super(Elementwise, self).__init__(*args) def forward(self, input): inputs = [feat.squeeze(2) for feat in input.split(1, dim=2)] ...
class MLP(nn.Module): def __init__(self, dim_in, dim_hidden, dim_out): super(MLP, self).__init__() self.layer_input = nn.Linear(dim_in, dim_hidden) self.relu = nn.ReLU() self.dropout = nn.Dropout() self.layer_hidden = nn.Linear(dim_hidden, dim_out) self.softmax = nn.S...
def add_forbidden(conf_space, pipeline, matches, dataset_properties, include, exclude): node_i_is_choice = [] node_i_choices_names = [] node_i_choices = [] all_nodes = [] for (node_name, node) in pipeline: all_nodes.append(node) is_choice = hasattr(node, 'get_available_components') ...
.skip() def test_redwood_indoor_office2(): gt_prefix = 'RedwoodIndoorOffice2' (_, gt_download_dir, gt_extract_dir) = get_test_data_dirs(gt_prefix) dataset = o3d.data.RedwoodIndoorOffice2() assert Path(gt_download_dir).is_dir() assert Path(gt_extract_dir).is_dir() pcd = o3d.io.read_point_cloud(da...
def load_embeddings(embfile): print('Loading embeddings... ', end='') sys.stdout.flush() if (not embfile): print() sys.stderr.write("No clusters specified. Please add line 'clusters[path]' to data config file!\n") sys.exit(1) f = (line.split(' ', 1)[1] for line in open(embfile)) ...
def _get_stanford2d3d_pairs(folder, fold, mode='train'): img_paths = [] if (mode == 'train'): area_ids = __FOLD__['{}_{}'.format(fold, mode)] elif (mode == 'val'): area_ids = __FOLD__['{}_{}'.format(fold, mode)] elif (mode == 'trainval'): area_ids = __FOLD__[mode] else: ...
class MLP(Layer): def __init__(self, *args, **kwargs): Serializable.quick_init(self, locals()) Layer.__init__(self, *args, **kwargs) self.build_graph() def build_graph(self): with tf.variable_scope(self.name, reuse=tf.AUTO_REUSE): if (self._params is None): ...
def _get_file_md5sum(file_name): hash_obj = hashlib.md5() with open(file_name, 'r') as f: hash_obj.update(f.read()) return hash_obj.hexdigest()
def state_divergence_loss(prior, posterior, config, reduce=True, balance=0.2): prior_dist = reshape_dist(prior, config) post_dist = reshape_dist(posterior, config) post = kl_div_categorical(post_dist, prior_dist.detach()) pri = kl_div_categorical(post_dist.detach(), prior_dist) kl_div = ((balance * ...
def train(train_loader, model, criterion, optimizer, epoch): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() model.train() end = time.time() for (i, (input, target)) in enumerate(train_loader): lr = adjust...
def train(model, criterion_xent, criterion_htri, optimizer, trainloader, use_gpu): model.train() losses = AverageMeter() for (batch_idx, (imgs, pids, _)) in enumerate(trainloader): if use_gpu: (imgs, pids) = (imgs.cuda(), pids.cuda()) (imgs, pids) = (Variable(imgs), Variable(pids...
def flops_per_step(n_blocks, dim, batch_size, model_type, seq_len=SEQ_LEN): flops_per_token = (6 * params(n_blocks, dim)) if (model_type == 'autoregressive'): flops_per_token += ((n_blocks * seq_len) * dim) elif (model_type == 'diffusion'): flops_per_token += (2 * ((n_blocks * seq_len) * dim...
def main(log_dir, augmentation, dataset, batch_size, num_workers): print(check_output(['nodejs', '--version']).decode('utf-8')) torch.backends.cudnn.benchmark = True transform = torchvision.transforms.Compose([CacheNPY(prefix='b64_', repeat=augmentation, pick_randomly=False, transform=torchvision.transforms...
(num_cpus=0) class RemoteLinearParameterScheduler(object): def __init__(self, start_val: float, end_val: float, timesteps_annealing: int): self._start_val = start_val self._end_val = end_val assert (timesteps_annealing >= 0), timesteps_annealing self._timesteps_annealing = timesteps_...
class MobileViTOutput(nn.Module): def __init__(self, config: MobileViTConfig, hidden_size: int, intermediate_size: int) -> None: super().__init__() self.dense = nn.Linear(intermediate_size, hidden_size) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states...
class CustomHFIndex(HFIndexBase): def __init__(self, vector_size: int, dataset, index_path=None): super().__init__(vector_size, dataset, index_initialized=(index_path is None)) self.index_path = index_path def load_from_disk(cls, vector_size, dataset_path, index_path): logger.info(f'Load...
class AWACDataset(Dataset): def __init__(self, env_name: str, clip_to_eps: bool=True, eps: float=1e-05): dataset_path = os.path.join(d4rl.offline_env.DATASET_PATH, 'avac') zip_path = os.path.join(dataset_path, 'all.zip') url = ' gdown.cached_download(url, zip_path, postprocess=gdown....
class TestConvTBC(unittest.TestCase): def test_convtbc(self): conv_tbc = ConvTBC(4, 5, kernel_size=3, padding=1) conv1d = nn.Conv1d(4, 5, kernel_size=3, padding=1) conv_tbc.weight.data.copy_(conv1d.weight.data.transpose(0, 2)) conv_tbc.bias.data.copy_(conv1d.bias.data) input_...
def save_model(path, optimizer, ema, epoch, H): (optimizer, ema) = jax_utils.unreplicate((optimizer, ema)) checkpoints.save_checkpoint(path, (optimizer, epoch), optimizer.state.step) checkpoints.save_checkpoint((path + '_ema'), ema, optimizer.state.step) from_log = os.path.join(H.save_dir, 'log.jsonl') ...
class Leaf(F): def __init__(self, val): self.val = val def __str__(self): return str(self.val) def to_str(self, namer, sort=False): return namer(self.val) def to_expr(self, namer=(lambda x: x)): return pyeda.boolalg.expr.exprvar(namer(self.val)) def __len__(self): ...
class GenericAntisymmetrize(Module): fn_to_antisymmetrize: Callable[([Array], Array)] logabs: bool = True def setup(self): self._fn_to_antisymmetrize = self.fn_to_antisymmetrize def _get_single_leaf_perm(self, x: Array) -> Tuple[(Array, Array)]: n = x.shape[(- 2)] return Parallel...
def quantize(input_path: str, output_path: str, model_family: str, dtype: str='q4_0'): invalidInputError((model_family in ['llama', 'bloom', 'gptneox', 'starcoder']), "Now we only support quantization of model family('llama', 'bloom', 'gptneox', 'starcoder')", '{} is not in the list.'.format(...
def request_data_key_plaintext(ip, port, encrypted_primary_key, encrypted_data_key): action = 'Decrypt' payload = {'keyid': encrypted_primary_key, 'ciphertext': encrypted_data_key, 'aad': 'test'} data_key_plaintext = post_request(ip, port, action, payload)['plaintext'] return data_key_plaintext
def dict_to_tf_example(data, dataset_directory, label_map_dict, ignore_difficult_instances=False, image_subdirectory='JPEGImages'): img_path = os.path.join(data['folder'], image_subdirectory, data['filename']) full_path = os.path.join(dataset_directory, img_path) with tf.gfile.GFile(full_path, 'rb') as fid:...
class BERT_MLP_CA(BERT_MLP): def __init__(self, max_length=128, word_embedding_size=200, **kwargs): super(BERT_MLP_CA, self).__init__(**kwargs) self.name = f"{'CA'}-b{self.batch_size}.e{self.epochs}.len{self.max_seq_length}.bert" self.parent_tokenizer = Tokenizer() self.max_length = ...
class FactorizationSupportedNeuralNetworkModel(torch.nn.Module): def __init__(self, field_dims, embed_dim, mlp_dims, dropout): super().__init__() self.embedding = FeaturesEmbedding(field_dims, embed_dim) self.embed_output_dim = (len(field_dims) * embed_dim) self.mlp = MultiLayerPerce...
class TestJSDDiv(unittest.TestCase): def setUp(self) -> None: self.shape = (10, 5, 224, 224) self.logit = torch.randn(*self.shape, requires_grad=True) self.pred = F.softmax(self.logit, 1) self.target = torch.randint(low=0, high=self.shape[1], size=[self.shape[i] for i in range(self.s...
def main(): if (not os.path.exists(FINAL_DIR)): os.makedirs(FINAL_DIR) files = [f for f in os.listdir(DIR) if f.endswith('.pck')] files.sort() num_files = len(files) for (i, f) in enumerate(files): subsample_file(f) print('Done with {} of {}'.format(i, num_files))