code
stringlengths
101
5.91M
def has_nonnegative_entries(input_matrix: Union[(sparse.csr_matrix, np.ndarray)]) -> bool: if (type(input_matrix) == sparse.csr_matrix): return np.all((input_matrix.data >= 0)) else: return np.all((input_matrix >= 0))
def generate_stack(node_name, in_name, out_name, axis, base_name, func_counter): sp = nnabla_pb2.Function() sp.type = 'Stack' set_function_name(sp, node_name, base_name, func_counter) sp.input.extend(in_name) sp.output.extend([out_name]) spp = sp.stack_param spp.axis = axis return sp
class FixedProblemSet(Dataset): def __init__(self, probs: list[tuple[(type[Problem], tuple)]], paradigm, vocab): self.probs = probs self.paradigm = paradigm self.vocab = vocab def __getitem__(self, item): (prob_cls, args) = self.probs[item] (x, y, label) = prob_cls.solve(...
def main(): sc = sp.Client() def make_blurred_frame(streams): frames = sc.io.Input(streams) blurred_frames = sc.ops.Blur(frame=frames, kernel_size=3, sigma=0.5) sampled_frames = sc.streams.Range(blurred_frames, [(0, 30)]) return (frames, sampled_frames) example_video_path = u...
class MetricLogger(object): def __init__(self, delimiter='\t'): self.meters = defaultdict(SmoothedValue) self.delimiter = delimiter def update(self, **kwargs): for (k, v) in kwargs.items(): if isinstance(v, torch.Tensor): v = v.item() assert isinst...
class ComparisonModule(nn.Module): def __init__(self, dim_v): super().__init__() self.projection = nn.Sequential(nn.Linear(dim_v, 128), nn.ReLU(), nn.Linear(128, dim_v)) def forward(self, enc1, enc2): input = (enc1 - enc2) out = self.projection(input) return out
class NILMDataloader(): def __init__(self, args, ds_parser, pretrain=False): self.args = args self.mask_prob = args.mask_prob self.batch_size = args.batch_size if pretrain: (self.train_dataset, self.val_dataset) = ds_parser.get_pretrain_datasets(mask_prob=self.mask_prob) ...
.usefixtures('spark', 'schema') () def dataframe_two_columns_no_cut(spark, schema): data_two_columns_no_cut = [(1, [2, 0, 0, 0, 0], [19842, (- 1), (- 1), (- 1), (- 1)]), (1, [2, 4, 0, 0, 0], [19842, 19844, (- 1), (- 1), (- 1)]), (1, [2, 4, 3, 0, 0], [19842, 19844, 19843, (- 1), (- 1)]), (1, [2, 4, 3, 5, 0], [19842,...
def variable_recurrent_factory(inner, reverse=False): if reverse: return VariableRecurrentReverse(inner) else: return VariableRecurrent(inner)
class ConvCrossAttentionBlock(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm, resolution=1.0): super().__init__() self.norm0 = norm_layer(dim) self.conv0 = nn.Conv...
class TestCpow(object): def setup(self): self.olderr = np.seterr(invalid='ignore') def teardown(self): np.seterr(**self.olderr) def test_simple(self): x = np.array([(1 + 1j), (0 + 2j), (1 + 2j), np.inf, np.nan]) y_r = (x ** 2) y = np.power(x, 2) for i in range...
def sub(g, self, other, alpha): if (_scalar(alpha) != 1): return _unimplemented('sub', 'alpha != 1') return g.op('Sub', self, _if_scalar_type_as(other, self), **_broadcast_if_scalar(other))
def get_results(deployment, experiment, output_dir): if (deployment.name == 'aws'): return get_results_aws(deployment, experiment, output_dir)
class TilingStrategy(): def __init__(self, window_size: Tuple[(int, int)]=None, image_shape: Tuple[(int, int)]=None, **kwargs): if window_size: self.window_size = window_size else: self.window_size = image_shape (self.image_width, self.image_height) = image_shape ...
_function_dispatch(_irr_dispatcher) def irr(values): res = np.roots(values[::(- 1)]) mask = ((res.imag == 0) & (res.real > 0)) if (not mask.any()): return np.nan res = res[mask].real rate = ((1 / res) - 1) rate = rate.item(np.argmin(np.abs(rate))) return rate
def test_convert(): pt = np.array([3.76632, 0.072447, 0.30173]) assert np.allclose(pt, mp3d_to_habitat(habitat_to_mp3d(pt)))
def register_bdd_panoptic(name, metadata, image_root, panoptic_root, panoptic_json): panoptic_name = name DatasetCatalog.register(panoptic_name, (lambda : load_bdd_panoptic_json(panoptic_json, image_root, panoptic_root, metadata))) MetadataCatalog.get(panoptic_name).set(panoptic_root=panoptic_root, image_ro...
class OutputSceneJmol(OutputBase): def __init__(self, scene_zip, preview_png): self.scene_zip = OutputBuffer(scene_zip) self.preview_png = OutputBuffer(preview_png) def launch_script_filename(self): from sage.misc.temporary_file import tmp_dir basedir = tmp_dir() scene_fi...
class _conv_dw(nn.Module): def __init__(self, inp, oup, stride): super(_conv_dw, self).__init__() self.conv = nn.Sequential(nn.Sequential(Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False), nn.BatchNorm2d(inp), nn.ReLU6(inplace=True)), nn.Sequential(Conv2d(inp, oup, 1, 1, 0, bias=False), nn.Batc...
def save_model_state(model, optimizer, trn_param, filename): torch.save({'trn_param': trn_param, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict()}, filename)
def handle_encoding_declaration(contents, out): lines = contents.splitlines() for (num, line) in enumerate(lines[:2]): if re.search('coding[:=]\\s*([-\\w.]+)', line): out.write((line + '\n')) return '\n'.join((lines[:num] + lines[(num + 1):])) out.write('# -*- coding: utf-8 -...
def load_tf_basicConv2d(weights, layer): load_tf_conv2d(weights[0], layer.conv) load_tf_batchNorm(weights[1:], layer.bn)
def filename_to_url(filename: str, cache_dir: Union[(str, Path)]=None) -> Tuple[(str, str)]: if (cache_dir is None): cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if isinstance(cache_dir, Path): cache_dir = str(cache_dir) cache_path = os.path.join(cache_dir, filename) if (not os.path.exists(...
def deconv(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, activation_fn=None, use_batchnorm=False, pre_activation=False, bias=True, weight_init_fn=None): if ((not pre_activation) and use_batchnorm): assert (not bias) layers = [] if pre_activation: if use_batch...
class AlexNet(nn.Module): def __init__(self, num_classes=1000): super(AlexNet, self).__init__() self.features = nn.Sequential(nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(64, 192, kernel_size=5, padding=2), nn.ReLU(inp...
def perfect_uplift_curve(y_true: np.ndarray, treatment: np.ndarray) -> np.ndarray: if (type_of_target(y_true) == 'binary'): perfect_control_score = ((treatment == 0).astype(int) * ((2 * (y_true != 1).astype(int)) - 1)) perfect_treatment_score = (((treatment == 1).astype(int) * 2) * (y_true == 1).ast...
def test_cartesian(): with pytest.raises(ValueError, match='cannot operate on arrays with incompatible backends'): ak.cartesian((left, right), axis=0) result = ak.cartesian((left, typetracer), axis=0) assert (ak.backend(result) == 'typetracer')
def load_rcv1(): data_home = get_data_home() train_file = os.path.join(data_home, 'rcv1_train.multiclass') test_file = os.path.join(data_home, 'rcv1_test.multiclass') return _load(train_file, test_file, 'rcv1')
def _assert_equal_on_sequences(actual, desired, err_msg=''): assert_equal(len(actual), len(desired), err_msg) for k in range(len(desired)): assert_equal(actual[k], desired[k], ('item=%r\n%s' % (k, err_msg))) return
def pad_tensor(x, max_len, mode='zero'): padding = np.zeros_like(x[0]) if (mode == 'last'): padding = x[(- 1)] return np.concatenate([x, np.tile(padding, (((max_len - len(x)),) + ((1,) * np.ndim(x[0]))))])
def base_transform(image, size, mean): x = cv2.resize(image, (size, size)).astype(np.float32) x -= mean x = x.astype(np.float32) return x
('Eltwise') def TranslateElementWise(layer, pretrained_blobs, is_test, **kwargs): param = layer.eltwise_param if (len(param.coeff) or (param.operation != 1)): raise RuntimeError('This eltwise layer is not yet supported.') caffe_op = BaseTranslate(layer, 'Sum') return (caffe_op, [])
def test_dbscan_metric_params(): eps = 0.8 min_samples = 10 p = 1 with warnings.catch_warnings(record=True) as warns: db = DBSCAN(metric='minkowski', metric_params={'p': p}, eps=eps, p=None, min_samples=min_samples, algorithm='ball_tree').fit(X) assert (not warns), warns[0].message (core...
def fit_encoder_only(surrogate, optimizer, mll, train_loader, num_epochs): assert hasattr(surrogate, 'encoder') surrogate.requires_grad_(False) surrogate.encoder.requires_grad_(True) for epoch_idx in range(num_epochs): surrogate.train() avg_loss = 0.0 for (inputs, targets) in tra...
def save_model(model, optimizer, save_variable_list, args): argparse_dict = vars(args) with open(os.path.join(args.save_path, 'config.json'), 'w') as fjson: json.dump(argparse_dict, fjson) torch.save({**save_variable_list, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.sta...
() ('workspace-one', default='-') ('workspace-two', default='-') ('-j', '--join', default='none', type=click.Choice(Workspace.valid_joins), help='The join operation to apply when combining the two workspaces.') ('--output-file', help='The location of the output json file. If not specified, prints to screen.', default=N...
class TCN_GCN_unit(nn.Module): def __init__(self, in_channels, out_channels, A, stride=1, residual=True, adaptive=True): super(TCN_GCN_unit, self).__init__() self.gcn1 = unit_gcn(in_channels, out_channels, A, adaptive=adaptive) self.tcn1 = unit_tcn(out_channels, out_channels, stride=stride) ...
def test_inout_connector_validation_success(): sdfg = dace.SDFG('test_inout_connector_validation_success') sdfg.add_array('A', [1], dace.int32) sdfg.add_array('B', [1], dace.int32) nsdfg = dace.SDFG('nested_sdfg') nsdfg.add_array('C', [1], dace.int32) nstate = nsdfg.add_state() read_c = nsta...
class UnetSimpleCondMerge(nn.Module): def __init__(self, in_ch, out_ch, nf=3, cond_nf=64, norm_layer=nn.InstanceNorm2d): super(UnetSimpleCondMerge, self).__init__() self.downscale = 16 self.in_ch = in_ch self.out_ch = out_ch self.nf = nf self.cond_nf = cond_nf ...
def do_setup(): root = get_root() try: cfg = get_config_from_root(root) except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (OSError, configparser.NoSectionError)): print('Adding sample versioneer config to setup.cfg', file=sys.stderr)...
class FreeGradedModule(CombinatorialFreeModule): def __classcall__(cls, algebra, generator_degrees, category=None, names=None, prefix=None, **kwds): if (algebra.base_ring() not in PrincipalIdealDomains()): raise ValueError('the ground ring of the algebra must be a PID') generator_degrees...
def filter_attrs(attr_list): valid_attrs = [] reserved_words = ['next', 'runtime', 'execute_next'] for attr in attr_list: if ((not attr[0].startswith('_')) and (attr[0] not in reserved_words) and (not hasattr(TestFlowReferenceWithExclude, attr[0]))): if (not isinstance(attr[1], MethodTyp...
class ChannelPool(nn.Module): def __init__(self): super().__init__() def forward(self, x: torch.Tensor) -> torch.Tensor: return x.mean(dim=1, keepdim=True)
def remove_spatial_bn_layers(caffenet, caffenet_weights): remove_types = ['BatchNorm', 'Scale'] def _remove_layers(net): for i in reversed(range(len(net.layer))): if (net.layer[i].type in remove_types): net.layer.pop(i) _remove_layers(caffenet) bn_layers = [layer for ...
def register_Ns3Icmpv6DestinationUnreachable_methods(root_module, cls): cls.add_constructor([param('ns3::Icmpv6DestinationUnreachable const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) cls.add_method('GetInsta...
def register_Ns3RandomDirection2dMobilityModel_methods(root_module, cls): cls.add_constructor([param('ns3::RandomDirection2dMobilityModel const &', 'arg0')]) cls.add_constructor([]) cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) cls.add_method('DoAssignStreams', 'int64_t', [param('int64_...
def preprocess_args(args): if ((args.mode == 'local') and (args.label == '')): args.label = 'local'
class Concatenate(Model): def __init__(self, *, input_shape=None, name=None, core_model=None): if (core_model is None): core_creator = search_core_model('Concatenate', []).create core_model = core_creator() super(Concatenate, self).__init__(core_model=core_model, input_shape=...
def get_max_batch_size(gpu_mem, max_bsz_dict): quantized_gpu_mem = floor_quantize(gpu_mem, max_bsz_dict.keys()) return max_bsz_dict[quantized_gpu_mem]
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar', dir_name='./ckpts/moco'): torch.save(state, os.path.join(dir_name, filename)) if is_best: shutil.copyfile(os.path.join(dir_name, filename), os.path.join(dir_name, 'model_best.pth.tar'))
_wrapped_func def async_update(args, emb, queue): th.set_num_threads(args.num_thread) while True: (grad_indices, grad_values, gpu_id) = queue.get() clr = emb.args.lr if (grad_indices is None): return with th.no_grad(): grad_sum = (grad_values * grad_values...
.parametrize('url, is_login, is_ajax', [(' 0, 0), (' 0, 1), (' 1, 0), (' 1, 1)], ids=['req_without_login', 'ajax_req_without_login', 'req_with_login', 'ajax_req_with_login']) def test_parse_home_info(url, is_login, is_ajax, cookies, session): if (is_login == 1): content = session.get(url).text if (n...
def print_losses(current_losses, i_iter): list_strings = [] for (loss_name, loss_value) in current_losses.items(): list_strings.append(f'{loss_name} = {to_numpy(loss_value):.6f} ') full_string = ' '.join(list_strings) print(f'iter = {i_iter} {full_string}')
class SawyerDrawerOpenV2Policy(Policy): _fully_parsed def _parse_obs(obs): return {'hand_pos': obs[:3], 'drwr_pos': obs[3:6], 'unused_info': obs[6:]} def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({'delta_pos': np.arange(3), 'grab_effort': 3}) pos_curr ...
def convconcat(tensor_in, condition, reshape_shape): reshaped = tf.reshape(condition, reshape_shape) out_shape = (([tf.shape(tensor_in)[0]] + tensor_in.get_shape().as_list()[1:(- 1)]) + [condition.get_shape().as_list()[1]]) to_concat = (reshaped * tf.ones(out_shape)) return tf.concat([tensor_in, to_conc...
def build(num_classes, num_keypoints=0, pretrained=True, freeze_base=False, use_dcn=False, use_skip=False, rotated_boxes=False): heads = {'hm': num_classes, 'wh': (2 if (not rotated_boxes) else 3), 'reg': 2} if (num_keypoints > 0): heads['kps'] = (num_keypoints * 2) return CenterMobileNetV2(heads, p...
_HEADS.register_module class ResLayer(nn.Module): def __init__(self, depth, stage=3, stride=2, dilation=1, style='pytorch', norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, with_cp=False, dcn=None): super(ResLayer, self).__init__() self.norm_eval = norm_eval self.norm_cfg = norm...
def auto_select_c(d): dim2 = (d / 2.0) R = (gamma((dim2 + 1)) / (np.pi ** (dim2 - 1))) R = (R ** (1 / float(d))) c = (1 / (R ** 2)) return c
class MgpstrEncoder(nn.Module): def __init__(self, config: MgpstrConfig): super().__init__() dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)] self.blocks = nn.Sequential(*[MgpstrLayer(config=config, drop_path=dpr[i]) for i in range(config.num_hidde...
def animate_imlist(im_list, anim_name='movie'): (fig, ax) = plt.subplots() ims = [] for p in im_list: im = plt.imshow(p) ims.append(im) import ipdb ipdb.set_trace() ani = animation.ArtistAnimation(fig, ims, interval=10, blit=True, repeat_delay=1000) ani.save(f'{anim_name}.mp4...
class MPNetForMaskedLM(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class TestsOmniglot(unittest.TestCase): def test_2_way_batch_4(self): config = {'data.dataset_path': '/home/igor/dl/siamese-networks-tf/data/omniglot', 'data.dataset': 'omniglot', 'data.train_way': 2, 'data.test_way': 2, 'data.split': 'vinyals', 'data.batch': 4, 'data.episodes': 2, 'data.cuda': 1, 'data.gpu...
class EncodeText(Dataset): def __init__(self, text: List[str], tokenizer: Tokenizer, iob: List[str]=None) -> None: super().__init__() self.text = text self.iob = iob if (iob is not None): assert (len(text) == len(iob)) self.tokenizer = tokenizer def __len__(se...
def wel_maker(file_name, min_weight, max_weight, vertices, min_edge, max_edge, sign, direct, self_loop, multigraph): (edge_dic, weight_dic, edge_number) = edge_gen(vertices, min_weight, max_weight, min_edge, max_edge, sign, direct, self_loop, multigraph) with open((file_name + '.wel'), 'w') as buf: _wri...
def _remove_dup_items(lst): new_lst = [] for item in lst: if (item not in new_lst): new_lst.append(item) return new_lst
def get_kernel_embedding(args, train_files, val_files, test_files): print('\n******Running WL Kernel on train set******') gk = GraphKernel(kernel=[{'name': 'weisfeiler_lehman', 'n_iter': args['n_iter']}, 'subtree_wl'], normalize=True, n_jobs=args['n_cores']) graphs = Parallel(n_jobs=args['n_cores'])((delaye...
def extract_nth_traceback(trace: (TracebackType | None), n: int) -> (TracebackType | None): depth = 0 while ((depth < n) and (trace is not None)): trace = trace.tb_next depth += 1 return trace
class PoolingLayer(My2DLayer): def __init__(self, in_channels, out_channels, pool_type, kernel_size=2, stride=2, use_bn=False, act_func=None, dropout_rate=0, ops_order='weight_bn_act'): self.pool_type = pool_type self.kernel_size = kernel_size self.stride = stride super(PoolingLayer,...
def test_array_index_function_result(): p = sqlparse.parse('somefunc()[1]')[0].tokens assert (len(p) == 1) assert (len(list(p[0].get_array_indices())) == 1)
def plotPoseDataset(): POSE_PAIRS = [[1, 0], [1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], [1, 8], [0, 9], [9, 11], [0, 10], [10, 12]] HAND_PAIRS = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [1...
class BatchNormLayer(L.Layer): def __init__(self, incoming, axes='auto', epsilon=0.0001, alpha=0.1, mode='low_mem', beta=lasagne.init.Constant(0), gamma=lasagne.init.Constant(1), mean=lasagne.init.Constant(0), std=lasagne.init.Constant(1), **kwargs): super(BatchNormLayer, self).__init__(incoming, **kwargs) ...
_utils.test(arch=supported_archs_texture) def test_rw_texture_wrong_fmt(): tex = ti.Texture(ti.Format.rgba8, (32, 32)) def write(tex: ti.types.rw_texture(num_dimensions=2, fmt=ti.Format.r32f, lod=0)): for (i, j) in tex: tex.store(ti.Vector([i, j]), ti.Vector([1.0, 0.0, 0.0, 0.0])) with p...
def restart(): operation_log = [('', ''), ('Try to upload your video and click the Get video info button to get started!', 'Normal')] return ({'user_name': '', 'video_name': '', 'origin_images': None, 'painted_images': None, 'masks': None, 'inpaint_masks': None, 'logits': None, 'select_frame_number': 0, 'fps': ...
def print_fig(input, target=None, title=None, save_dir=None): (fig, axes) = plt.subplots(1, len(input), figsize=((3 * len(input)), 3)) if title: fig.suptitle(title, size=16) if (len(input) == 1): axes = [axes] for (i, ax) in enumerate(axes): if (len(input.shape) == 4): ...
class PolEmoOUTTask(BaseTask): def __init__(self): self._spec = TaskSpecification('POLEMO', 'classification', 4, 1) self._spec.output_dir = 'POLEMO-OUT' def read(self, data_path: str, split: str) -> Iterable[DataExample]: split = (split if (split == 'train') else f'out-{split}') ...
('decomposable_attention') class DecomposableAttention(Model): def __init__(self, vocab: Vocabulary, text_field_embedder: TextFieldEmbedder, attend_feedforward: FeedForward, similarity_function: SimilarityFunction, compare_feedforward: FeedForward, aggregate_feedforward: FeedForward, premise_encoder: Optional[Seq2S...
class NLIDataReader(object): def __init__(self, dataset_folder): self.dataset_folder = dataset_folder def get_examples(self, filename, max_examples=0): s1 = gzip.open(os.path.join(self.dataset_folder, ('s1.' + filename)), mode='rt', encoding='utf-8').readlines() s2 = gzip.open(os.path.jo...
() ('db_file', type=click.Path()) ('entity_db_file', type=click.Path()) ('out_file', type=click.Path()) ('--min-word-count', default=5) ('--min-entity-count', default=3) def build_vocab(db_file, entity_db_file, out_file, **kwargs): db = AbstractDB(db_file, 'r') entity_db = EntityDB.load(entity_db_file) voca...
def assert_arctan2_ispzero(x, y): assert_(((ncu.arctan2(x, y) == 0) and (not np.signbit(ncu.arctan2(x, y)))), ('arctan(%s, %s) is %s, not +0' % (x, y, ncu.arctan2(x, y))))
class SymforceLinterTest(TestCase): _on_sympy ((sys.version_info[:3] >= (3, 10, 7)), '\n Mypy fails on Python 3.10.7 because of this bug, which is fixed in mypy 0.981:\n ') def test_linter(self) -> None: try: python_util.execute_subprocess(['make', 'lint'], cwd=SYMF...
def create_lmdb_for_vimeo90k(): with open(yml_path, 'r') as fp: fp = yaml.load(fp, Loader=yaml.FullLoader) root_dir = fp['dataset']['root'] gt_folder = fp['dataset']['train']['gt_folder'] lq_folder = fp['dataset']['train']['lq_folder'] gt_path = fp['dataset']['train']['gt_pat...
def get_sequence_list_and_phyche_value(input_data, k, phyche_index, extra_phyche_index, all_property): if (phyche_index is None): phyche_index = [] if (extra_phyche_index is None): extra_phyche_index = {} diphyche_list = ['Base stacking', 'Protein induced deformability', 'B-DNA twist', 'Dinu...
class RLAlgorithm(Algorithm): def __init__(self, sampler, n_epochs=1000, n_train_repeat=1, n_initial_exploration_steps=10000, epoch_length=1000, eval_n_episodes=10, eval_deterministic=True, eval_render=False, control_interval=1): self.sampler = sampler self._n_epochs = int(n_epochs) self._n_...
class BoundaryEntDiscriminator(nn.Module): def __init__(self): super(BoundaryEntDiscriminator, self).__init__() filter_num_list = [64, 128, 256, 512, 1] self.conv1 = nn.Conv2d(3, filter_num_list[0], kernel_size=4, stride=2, padding=2, bias=False) self.conv2 = nn.Conv2d(filter_num_lis...
def test_load_spatialevents(): dataset = tau2019sse.Dataset(TEST_DATA_HOME) clip = dataset.clip('foa_dev/split1_ir0_ov1_1') csv_path = clip.csv_path events_data = tau2019sse.load_spatialevents(csv_path) assert (events_data.labels[0] == 'cough') assert (events_data.labels[(- 1)] == 'phone') a...
.skipif((not has_pytorch()), reason='Pytorch not installed.') .parametrize('size', [[1, 2, 3, 4]]) _utils.test(arch=[ti.cpu, ti.cuda, ti.opengl]) def test_get_external_tensor_shape_access_ndarray(size): def func(x: ti.types.ndarray(), index: ti.template()) -> ti.i32: return x.shape[index] x_hat = ti.nda...
class Discriminator(object): def __init__(self, x_dim=16): self.x_dim = x_dim self.name = 'pendigit/mlp/d_net' def __call__(self, x, keep=1.0, reuse=True): with tf.variable_scope(self.name) as vs: if reuse: vs.reuse_variables() fc1 = tc.layers.full...
def _finalize_parameters_specs(user_parameters, _paramsets_requirements): _paramsets_user_configs = {} for parameter in user_parameters: if (parameter['name'] in _paramsets_user_configs): raise exceptions.InvalidModel(f"Multiple parameter configurations for {parameter['name']} were found.") ...
class FacebookManagerGetPost(VirtualFunctionTool): name = 'FacebookManagerGetPost' summary = 'Get the details of a post by its post_id.' parameters: List[ArgParameter] = [{'name': 'post_id', 'type': 'string', 'description': 'The unique identifier of the post.', 'required': True}] returns: List[ArgReturn...
def main(): parser = argparse.ArgumentParser() parser.add_argument('-v', '--version', action='version', version='fsner-{version}'.format(version=__version__)) sub_parsers = parser.add_subparsers() trainer_parser = sub_parsers.add_parser('trainer') trainer_parser = init_trainer_parser(trainer_parser)...
_spec_function('msmarco') def get_msmarco_spec(track: str, valid_topk: Optional[int]=None) -> RunSpec: valid_topk = (None if (valid_topk is None) else int(valid_topk)) scenario_spec = ScenarioSpec(class_name='helm.benchmark.scenarios.msmarco_scenario.MSMARCOScenario', args={'track': track, 'valid_topk': valid_t...
def detokenizer(string): string = string.replace('`` ', '"') string = string.replace(" ''", '"') string = string.replace('` ', '"') string = string.replace(" ' ", '" ') string = string.replace("s '", "s'") string = re.sub("/' [0-9]/", "/'[0-9]/", string) string = string.replace(' - ', '-') ...
def gauss_on_linear(I): I = (Polynomial(p) for p in I) linear = [] non_linear = [] for p in I: if p.is_zero(): continue if (p.deg() <= 1): linear.append(p) else: non_linear.append(p) if (not linear): return non_linear linear = l...
def setup_cfg(args): cfg = get_cfg() cfg.DATALOADER.NUM_WORKERS = 0 cfg = add_export_config(cfg) add_pointrend_config(cfg) cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) cfg.freeze() return cfg
class Runner(object): def __init__(self, *, env, model, nsteps, gamma, lam): self.env = env self.model = model nenv = env.num_envs self.obs = np.zeros(((nenv,) + env.observation_space.shape), dtype=model.train_model.X.dtype.name) self.obs[:] = env.reset() self.gamma =...
class CTRLConfig(PretrainedConfig): pretrained_config_archive_map = CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP def __init__(self, vocab_size=246534, n_positions=256, n_ctx=256, n_embd=1280, dff=8192, n_layer=48, n_head=16, resid_pdrop=0.1, embd_pdrop=0.1, attn_pdrop=0.1, layer_norm_epsilon=1e-06, initializer_range=0.02...
.skipif((not _ti_core.GGUI_AVAILABLE), reason='GGUI Not Available') _utils.test(arch=supported_archs) def test_draw_part_of_mesh_instances(): N = 10 NV = ((N + 1) ** 2) NT = (2 * (N ** 2)) NE = (((2 * N) * (N + 1)) + (N ** 2)) pos = ti.Vector.field(3, ti.f32, shape=NV) tri = ti.field(ti.i32, sha...
def _have_importers(): has_py_importer = False has_pyx_importer = False for importer in sys.meta_path: if isinstance(importer, PyxImporter): if isinstance(importer, PyImporter): has_py_importer = True else: has_pyx_importer = True return (h...
def main(args): parser = get_config() all_args = parse_args(args, parser) if ((all_args.algorithm_name == 'rmappo') or (all_args.algorithm_name == 'rmappg')): assert (all_args.use_recurrent_policy or all_args.use_naive_recurrent_policy), 'check recurrent policy!' elif ((all_args.algorithm_name =...
def tanh_quantize(input, bits): assert (bits >= 1), bits if (bits == 1): return torch.sign(input) input = torch.tanh(input) input_rescale = ((input + 1.0) / 2) n = (math.pow(2.0, bits) - 1) v = (torch.floor(((input_rescale * n) + 0.5)) / n) v = ((2 * v) - 1) v = (0.5 * torch.log(...