code
stringlengths
101
5.91M
def convert_ontonotes_file(filename, simplify, bigger_first): assert ('en_ontonotes' in filename) if (not os.path.exists(filename)): raise FileNotFoundError(('Cannot convert missing file %s' % filename)) new_filename = filename.replace('en_ontonotes', 'en_ontonotes-multi') with open(filename) as...
class ChamferDistanceFunction(torch.autograd.Function): def forward(ctx, xyz1, xyz2): (batchsize, n, _) = xyz1.size() (_, m, _) = xyz2.size() xyz1 = xyz1.contiguous() xyz2 = xyz2.contiguous() dist1 = torch.zeros(batchsize, n) dist2 = torch.zeros(batchsize, m) ...
def build_transforms_head(cfg, is_train=True, PIXEL_MEAN=[0.485, 0.456, 0.406], PIXEL_STD=[0.229, 0.224, 0.225]): normalize_transform = T.Normalize(mean=PIXEL_MEAN, std=PIXEL_STD) if is_train: transform = T.Compose([T.Resize([cfg.height, cfg.width]), T.Pad(10), T.RandomCrop([cfg.height, cfg.width]), T.C...
def register_Ns3LteRrcSapPhysCellIdRange_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::LteRrcSap::PhysCellIdRange const &', 'arg0')]) cls.add_instance_attribute('haveRange', 'bool', is_const=False) cls.add_instance_attribute('range', 'uint16_t', is_const=False) ...
_kl(ContinuousBernoulli, ContinuousBernoulli) def _kl_continuous_bernoulli_continuous_bernoulli(p, q): t1 = (p.mean * (p.logits - q.logits)) t2 = (p._cont_bern_log_norm() + torch.log1p((- p.probs))) t3 = ((- q._cont_bern_log_norm()) - torch.log1p((- q.probs))) return ((t1 + t2) + t3)
def rule0(graph, nodes, sep_sets, knowledge, verbose): reorientAllWith(graph, Endpoint.CIRCLE) fci_orient_bk(knowledge, graph) for node_b in nodes: adjacent_nodes = graph.get_adjacent_nodes(node_b) if (len(adjacent_nodes) < 2): continue cg = ChoiceGenerator(len(adjacent_n...
class EfficientFormerModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
.parametrize('dataset_type', [pytest.param('spark_dataframe_test', marks=pytest.mark.spark), pytest.param('pandas_dataframe_test', marks=pytest.mark.core)]) def test_with_session_ids(dataset_type, request): log = request.getfixturevalue(dataset_type) splitter = RandomSplitter(test_size=0.3, drop_cold_items=Fals...
class _QPool2dBenchmarkBase(op_bench.TorchBenchmarkBase): def setup(self, N, C, H, W, dtype, contig): if (N == 0): f_input = ((torch.rand(C, H, W) - 0.5) * 256) else: f_input = ((torch.rand(N, C, H, W) - 0.5) * 256) scale = 1.0 zero_point = 0 self.q_in...
class Mergeable(object): def getTypeName(self) -> str: raise NotImplementedError('getTypeName not implemented.') def shouldMerge(self, other: Mergeable) -> bool: raise NotImplementedError('equals not implemented.')
def test_transformer_decoder(): decoder = NRTRDecoder(num_classes=37, padding_idx=36, max_seq_len=5) decoder.init_weights() decoder.train() out_enc = torch.rand(1, 25, 512) tgt_dict = {'padded_targets': torch.LongTensor([[1, 1, 1, 1, 36]])} img_metas = [{'valid_ratio': 1.0}] tgt_dict['padded...
_to_string_io def load_events(fhandle: TextIO) -> annotations.Events: times = [] labels = [] confidence = [] reader = csv.reader(fhandle, delimiter='\t') for line in reader: times.append([float(line[0]), float(line[1])]) labels.append(line[2]) confidence.append(1.0) event...
class SimilarityEvaluator(): def __init__(self, model_path='models/sim/sim.pt', tokenizer_path='models/sim/sim.sp.30k.model', gpu=False): self.model_path = model_path self.tokenizer_path = tokenizer_path self.tok = TreebankWordTokenizer() kw = {} if (not torch.cuda.is_availab...
class DropoutAddLayerNormSubsetFn(torch.autograd.Function): def forward(ctx, x0, residual, gamma, beta, colscale, x0_subset, out_subset, dropout_p, epsilon, rowscale_const, out_numrows, residual_in_fp32=False, prenorm=False, is_rms_norm=False, return_dmask=False): x0 = maybe_align(x0.contiguous(), 16) ...
def run_job_synchronously(shell_command, directory, valgrind, is_python, build_path=''): suppressions_path = os.path.join(NS3_BASEDIR, VALGRIND_SUPPRESSIONS_FILE) if is_python: path_cmd = ((PYTHON[0] + ' ') + os.path.join(NS3_BASEDIR, shell_command)) elif len(build_path): path_cmd = os.path....
class WordSplitter(Registrable): default_implementation = 'spacy' def split_words(self, sentence: str) -> List[Token]: raise NotImplementedError def from_params(cls, params: Params) -> 'WordSplitter': choice = params.pop_choice('type', cls.list_available(), default_to_first_choice=True) ...
def generate_test_cpp_sources(test_params, template): (cpp_args_construction_stmts, _) = compute_cpp_args_construction_stmts_and_forward_arg_symbols(test_params) test_cpp_sources = template.substitute(functional_variant_name=test_params.functional_variant_name, cpp_args_construction_stmts=';\n '.join(cpp_args_...
('/response-conformance/missing-field', methods=['GET']) def missing_field(): response_data = {'id': '123', 'name': 'Alice'} return (jsonify(response_data), 200)
def gs_link_prediction(g, edge_ids, edge_labels, num_samples, optimizer, batch_size=4, epochs=4, bias=True, dropout=0.0, normalize='l2', seed=0, shuffle=True): set_seed(seed) tf.random.set_seed(seed) if shuffle: random.seed(seed) generator = GraphSAGELinkGenerator(g, batch_size, num_samples) ...
def HAT(max_byte_size=, memory_estimate_period=1000000, grace_period=200, split_criterion='info_gain', split_confidence=1e-07, tie_threshold=0.05, binary_split=False, stop_mem_management=False, remove_poor_atts=False, no_preprune=False, leaf_prediction='nba', nb_threshold=0, nominal_attributes=None, bootstrap_sampling=...
def load_data(path): urls = {} with open(path, 'r') as f: for line in f: (url, _) = line.split('\t') vid = url[(- 11):] urls[vid] = url return urls
class MovingAverageDict(object): def __init__(self, decay=0.99): self.decay = decay self.ma_dict = {} def __call__(self, value_dict): for (key, val) in value_dict.items(): if (isinstance(val, (np.float32, np.float64, np.float16)) or (isinstance(val, np.ndarray) and (val.dtype...
def get_polynomial_decay_schedule_with_warmup(*args, **kwargs): requires_backends(get_polynomial_decay_schedule_with_warmup, ['torch'])
def _is_this_machine(host): try: machine_ips = [addr[4][0] for addr in socket.getaddrinfo(socket.gethostname(), None)] host_ip = socket.gethostbyname(host) except socket.gaierror: return False return any(((host_ip == machine_ip) for machine_ip in machine_ips))
class EncoderLayer(tf.keras.layers.Layer): def __init__(self, d_model, num_heads, dff, rate=0.1): super(EncoderLayer, self).__init__() self.mha = MultiHeadAttention(d_model, num_heads) self.ffn = point_wise_feed_forward_network(d_model, dff) self.layernorm1 = tf.keras.layers.LayerNor...
def shfl_down_f32(mask, val, offset): return impl.call_internal('cuda_shfl_down_sync_f32', mask, val, offset, 31, with_runtime_context=False)
def _maybe_download_dataset(dataset_path): dataset_folder = os.path.join(dataset_path, clrs.get_clrs_folder()) if os.path.isdir(dataset_folder): logging.info('Dataset found at %s. Skipping download.', dataset_folder) return dataset_folder logging.info('Dataset not found in %s. Downloading......
def _cross_val_metrics(args_namespace): return cross_val_metrics(args_namespace.dataset_path, args_namespace.output_path, args_namespace.config_path, args_namespace.nb_folds, args_namespace.train_size_ratio, args_namespace.exclude_slot_metrics, args_namespace.include_errors, args_namespace.verbosity)
class RegNetForImageClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class CamembertTokenizer(): def __init__(self, *args, **kwargs): requires_sentencepiece(self) def from_pretrained(self, *args, **kwargs): requires_sentencepiece(self)
def register_Ns3ObjectBase_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) cls.add_method('GetAttributeFailSaf...
def gen_corrupt_batch_gpu(corruption, severity): def corrupt_batch_gpu(images, model): for i in range(images.size(0)): corr_func = corruption_dict[corruption] images[i] = corr_func(images[i], severity, gpu=True) return images return corrupt_batch_gpu
def replicate_small_cp_cmd(src, dst, recursive=True) -> Optional[str]: (provider_src, _, _) = parse_path(src) (provider_dst, _, _) = parse_path(dst) if ((provider_src == 'aws') and (provider_dst == 'aws')): return fallback_cmd_s3_cp(src, dst, recursive) elif ((provider_src == 'gcp') and (provide...
def scheduled_sample(ground_truth_x, generated_x, batch_size, num_ground_truth): idx = tf.random_shuffle(tf.range(int(batch_size))) ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth)) generated_idx = tf.gather(idx, tf.range(num_ground_truth, int(batch_size))) ground_truth_examps = tf.gather(gr...
class STSDataReader(): def __init__(self, dataset_folder, s1_col_idx=5, s2_col_idx=6, score_col_idx=4, delimiter='\t', quoting=csv.QUOTE_NONE, normalize_scores=True, min_score=0, max_score=5): self.dataset_folder = dataset_folder self.score_col_idx = score_col_idx self.s1_col_idx = s1_col_id...
def test_class_splitter_for_fold_overlaps(): class DemoTask(Task): def __init__(self): super(DemoTask, self).__init__(index=0, num_classes=None) self._inputs = np.arange(10) def __len__(self): return len(self._inputs) def __getitem__(self, index): ...
def write_recip_lattice(f, recip_lattice): f.write('begin recip_lattice\n') for i in range(3): a = recip_lattice[i] f.write(' {0:>11.7f} {1:>11.7f} {2:>11.7f}\n'.format(*a)) f.write('end recip_lattice\n\n')
class UnsetValue(object): def __str__(self): return '<unset value>' def __repr__(self): return '<unset value>' def __bool__(self): return False def __nonzero__(self): return False
class RGBImgObsWrapper(gym.core.ObservationWrapper): def __init__(self, env, tile_size=8): super().__init__(env) self.tile_size = tile_size self.observation_space.spaces['image'] = spaces.Box(low=0, high=255, shape=((self.env.width * tile_size), (self.env.height * tile_size), 3), dtype='uint...
def validate_cn_ric(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]: if isinstance(df, (pd.Series, dd.Series)): return df.apply(ric.is_valid) elif isinstance(df, (pd.DataFrame, dd.DataFrame)): if (column != ''): ...
class FlaxGPTNeoModel(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
.parametrize('forest_cls, expected_oob_score', [(RandomSurvivalForest, 0.), (ExtraSurvivalTrees, 0.)]) def test_oob_score(make_whas500, forest_cls, expected_oob_score): whas500 = make_whas500(to_numeric=True) forest = forest_cls(oob_score=True, bootstrap=False, random_state=2) with pytest.raises(ValueError,...
def register_Ns3NoOpHandoverAlgorithm_methods(root_module, cls): cls.add_constructor([param('ns3::NoOpHandoverAlgorithm const &', 'arg0')]) cls.add_constructor([]) cls.add_method('GetLteHandoverManagementSapProvider', 'ns3::LteHandoverManagementSapProvider *', [], is_virtual=True) cls.add_method('GetTyp...
def get_batch_size(tensor_shape): tensor_shape.assert_has_rank(rank=4) return tensor_shape[0].value
def register_all_hico(root): for (dataset_name, splits_per_dataset) in _PREDEFINED_SPLITS_HICO.items(): for (key, (image_root, json_file)) in splits_per_dataset.items(): register_hico_instances(key, _get_builtin_metadata(dataset_name), (os.path.join(root, json_file) if ('://' not in json_file) e...
class ViTMAEModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class ENetMinus(ENet): def __init__(self, n_classes=19, max_input_h=512, max_input_w=1024): (h, w) = (max_input_h, max_input_w) r = 0.86 nn.ModuleList.__init__(self, [Downsampler(3, 16), Bottleneck(16, 64, 0.01, downsample=True), Bottleneck(64, 64, 0.01), Bottleneck(64, 64, 0.01), Bottleneck...
class STS(): def __init__(self, directory, train=True, seed=0): cwd = os.getcwd().replace('dataset', '') directory = path.join(cwd, directory) ensure_dataset_exists(directory) self._directory = directory self._inner = 'Set{}'.format((1 + (((seed + 1) + int(train)) % 2))) ...
def generate_datasets(data_root): train_info = sio.loadmat(os.path.join(data_root, 'train_list.mat'))['file_list'] test_info = sio.loadmat(os.path.join(data_root, 'test_list.mat'))['file_list'] class_names = os.listdir(os.path.join(data_root, 'Images')) class_names.sort() train_dataset = [] test...
def postprocess_one(pred_sql, schema): pred_sql = pred_sql.replace('group_by', 'group by').replace('order_by', 'order by').replace('limit_value', 'limit 1').replace('_EOS', '').replace(' value ', ' 1 ').replace('distinct', '').strip(',').strip() if pred_sql.endswith('value'): pred_sql = (pred_sql[:(- le...
class ResidualStack(nn.Module): def __init__(self, in_channels, num_hiddens, num_residual_layers, num_residual_hiddens, use_kaiming_normal): super(ResidualStack, self).__init__() self._num_residual_layers = num_residual_layers self._layers = nn.ModuleList(([Residual(in_channels, num_hiddens,...
def read_train_split_to_str(dataset_dir): train_dir = os.path.join(dataset_dir, 'bbox_train') return read_train_test_directory_to_str(train_dir)
def compute_on_dataset(model, data_loader, device, timer=None): model.eval() results_dict = {} cpu_device = torch.device('cpu') for (_, batch) in enumerate(tqdm(data_loader)): (images_left, images_right, targets, calib, image_ids) = batch with torch.no_grad(): if timer: ...
def parse_notes_and_chords(stream: Stream, resolution: int=DEFAULT_RESOLUTION) -> Tuple[(List[Note], List[Chord])]: notes: List[Note] = [] chords: List[Chord] = [] ties: Dict[(int, int)] = {} for item in stream.flat.notesAndRests: if ((not item.isNote) and (not item.isChord)): contin...
def sturm_bound(level, weight=2): if is_ArithmeticSubgroup(level): if level.is_congruence(): return level.sturm_bound(weight) raise ValueError('no Sturm bound defined for noncongruence subgroups') if isinstance(level, (int, Integer)): return Gamma0(level).sturm_bound(weight)
def visit_forward(variables, callback, fclosed=None): if (fclosed is None): fclosed = set() stop = False for v in variables: stop |= v.stop f = v.parent if (f is None): continue if (f in fclosed): continue fclosed.add(f) stop_f ...
class Partition3(nn.Module): LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[8]/BertAttention[attention]/BertSelfOutput[output]/LayerNorm[LayerNorm]', 'BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[8]/BertIntermediate[intermediate]/Linear[dense]', '...
class TestConstant(unittest.TestCase): def test_objective_function(self): obj = objective.Constant(1) self.assertEqual(obj.calculate_objective_function(None), 1) val = 2 obj = objective.Constant(val) val = 3 self.assertEqual(obj.calculate_objective_function(None), 2) ...
def rotx(t): c = np.cos(t) s = np.sin(t) return np.array([[1, 0, 0], [0, c, (- s)], [0, s, c]])
class TextCapsCapEvalDataset(CaptionEvalDataset): def __init__(self, vis_processor, text_processor, vis_root, ann_paths): BaseDataset.__init__(self, vis_processor, text_processor, vis_root, ann_paths) self.annotation = self.annotation[3]['data'] self.annotation = [ann for ann in self.annotat...
def main(args): mimic_notes_fpath = args.mimic_notes anno_data_path = args.anno_data outputdir = args.outputdir dataset = {'gold': 'gold.pain_complications.mimic.row_ids.tsv', 'unlabeled': 'unlabeled.pain_complications.mimic.row_ids.tsv'} print('Loading MIMIC-III notes ...') for name in dataset:...
def main(): try: (opts, args) = getopt.getopt(sys.argv[1:], '') except: usage(sys.argv[0]) for (opt, arg) in opts: usage(sys.argv[0]) if (len(args) != 2): usage(sys.argv[0]) waves = int(args[0]) seeds = int(args[1]) print((((('Conditional estimation on snowbal...
class GooglenetModel(model.Model): def __init__(self): super(GooglenetModel, self).__init__('googlenet', 224, 32, 0.005) def add_inference(self, cnn): def inception_v1(cnn, k, l, m, n, p, q): cols = [[('conv', k, 1, 1)], [('conv', l, 1, 1), ('conv', m, 3, 3)], [('conv', n, 1, 1), ('c...
.script def batch_select(data, mask, dims, dim, index): data = data.select(dim, index) if dims[(dim - 1)]: mask = mask.select(dim, 0) else: mask = mask.select(dim, index) dims = torch.cat((dims[:(dim - 1)], dims[dim:dims.size(0)])) return (data, mask, dims)
class IBertForMaskedLM(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
def test_version_1_point_10(): assert_((NumpyVersion('1.9.0') < '1.10.0')) assert_((NumpyVersion('1.11.0') < '1.11.1')) assert_((NumpyVersion('1.11.0') == '1.11.0')) assert_((NumpyVersion('1.99.11') < '1.99.12'))
def calc_wer_on_dataset(dataset, refs, options, hyps): assert (dataset or refs) start_time = time.time() seq_len_stats = {'refs': Stats(), 'hyps': Stats()} seq_idx = options.startseq if (options.endseq < 0): options.endseq = float('inf') wer = 1.0 remaining_hyp_seq_tags = set(hyps.ke...
def _get_long_description(): with open(str((Path(__file__).parent / 'README.md')), 'r') as f: return f.read()
def depthwise_net_for_pruning(image, threshold, with_bias=False, channel_last=False, name_scope='net1'): with nn.parameter_scope(name_scope): h = image h /= 255.0 h = PF.convolution(h, 16, kernel=(3, 3), pad=(1, 1), with_bias=False, channel_last=channel_last, name='conv') inputs = h....
class Layout(Enum): alignEU = 0 compact = 1 offset = 2 stride = 3 matrix = 10 matrix2 = 11 _64IC = 20 _32IC = 21 _1IC = 22 _16IC = 23 T3 = 30 T4 = 31 T5 = 32 DMAstride = 40 DMA4Bank = 41 DMAmatrix = 42 DMAlinear = 43 alignEU_XN = 50 compact_XN ...
class LassoBenchmark(Predictor, Estimator, Benchmark): param_names = ['representation', 'precompute'] params = (['dense', 'sparse'], [True, False]) def setup_cache(self): super().setup_cache() def make_data(self, params): (representation, precompute) = params if (representation =...
class Datagen_set(): def __init__(self, X, Y, batch_size, code_dic, nl_dic, train=True): self.X = X self.Y = Y self.batch_size = batch_size self.code_dic = code_dic self.nl_dic = nl_dic self.train = train def __len__(self): return len(range(0, len(self.X),...
class PairedEvaluationDataset(Dataset): def __init__(self, pair_file_list, image_size=512): self.image_size = image_size self.pair_file_list = pair_file_list def __len__(self): return len(self.pair_file_list) def __getitem__(self, item): (pred_file, ref_file) = self.pair_file...
class ScipyLBFGSBTuner(Tuner): def tune_impl(self, **kwargs): if ('init_method' in kwargs): init_method = kwargs['init_method'] else: init_method = 'average' if (self.start_config is not None): config = self.start_config elif (init_method is 'avera...
(ipyvuetify=_HAS_IPYVUETIFY, IPython=_HAS_IPYTHON) def init_filename_textfield(): return v.TextField(class_='ml-3 pl-3', style_='max-width: 600px', v_model=str(Path.cwd().joinpath('plot.pdf')), label='Save As')
class SwitchWhiten2d(Module): def __init__(self, num_features, num_pergroup=16, sw_type=2, T=5, tie_weight=False, eps=1e-05, momentum=0.99, affine=True): super(SwitchWhiten2d, self).__init__() if (sw_type not in [2, 3, 5]): raise ValueError('sw_type should be in [2, 3, 5], but got {}'.fo...
def run_full_influence_functions(mode: str, num_examples_to_test: int, s_test_num_samples: int=1000) -> Dict[(int, Dict[(str, Any)])]: if (mode not in ['only-correct', 'only-incorrect']): raise ValueError(f'Unrecognized mode {mode}') (tokenizer, model) = misc_utils.create_tokenizer_and_model(constants.M...
_INGREDIENT.capture def build_model(graph_adj, node_features, labels, dataset_indices_placeholder, train_feed, trainval_feed, val_feed, test_feed, weight_decay, normalize_features, num_layers, hidden_size, dropout_prob): dropout = tf.placeholder(dtype=tf.float32, shape=[]) train_feed[dropout] = dropout_prob ...
(precision=4) def backward_difference(): (X, _, _) = get_mushroom_data() print(X.info()) enc = ce.BackwardDifferenceEncoder() enc.fit(X, None) out = enc.transform(X) print(out.info()) del enc, _, X, out
class UpSample(nn.Module): def __init__(self, layer_type): super().__init__() self.layer_type = layer_type def forward(self, x): if (self.layer_type == 'none'): return x elif (self.layer_type == 'timepreserve'): return F.interpolate(x, scale_factor=(2, 1),...
def get_rotated_mnist_loaders(angle, data_path, model_class='LeNet', download=False): if (model_class == 'MLP'): shift_tforms = transforms.Compose([RotationTransform(angle), transforms.ToTensor(), ReshapeTransform(((- 1),))]) else: shift_tforms = transforms.Compose([RotationTransform(angle), tra...
def to_gif(video, duration, event): output = '/tmp/processed-{}.gif'.format(os.path.basename(video)) call_ffmpeg(['-i', video, '-t', '{0}'.format(duration), '-vf', 'fps=10,scale=320:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse', '-loop', '0', output]) return output
def load_checkpoints(directory, is_gpu=True): checkpoints = [] for (root, _, filenames) in os.walk(directory): for filename in filenames: results = re.search('.*?-([0-9].*?).pt', filename) if (results is not None): epoch_idx = int(results.group(1)) ...
_model def hrnet_w18_small(pretrained=True, **kwargs): return _create_model('hrnet_w18_small', pretrained, kwargs)
_utils.test() def test_nested_subscript(): x = ti.field(ti.i32) y = ti.field(ti.i32) ti.root.dense(ti.i, 1).place(x) ti.root.dense(ti.i, 1).place(y) x[0] = 0 def inc(): for i in range(1): x[x[i]] += 1 inc() assert (x[0] == 1)
def test_mixed(spark_session): _run_job(spark=spark_session, name='mixed', data_cols=['Weekly_Sales', 'Temperature', 'CPI'], hierarchical=True, agg_dict={'Weekly_Sales': 'sum'}, predict_on_train=True, robust=False)
class LightConv3x3(nn.Module): def __init__(self, in_channels, out_channels): super(LightConv3x3, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, 1, stride=1, padding=0, bias=False) self.conv2 = nn.Conv2d(out_channels, out_channels, 3, stride=1, padding=1, bias=False, grou...
class TestAI21TokenCounter(): def setup_method(self, method): self.token_counter = AI21TokenCounter() def test_count_tokens(self): request = Request(model='openai/text-davinci-002', model_deployment='openai/text-davinci-002', prompt='The Center for Research on Foundation Models (CRFM) is an inte...
def clean_graph_item(graph_item): clean_graph_item = copy.deepcopy(graph_item) if ('optional' in clean_graph_item): del clean_graph_item['optional'] if ('required' in clean_graph_item): del clean_graph_item['required'] for (index, ii) in enumerate(clean_graph_item['objects']): if...
def getConnection(db=None, driver=None, user=None, password=None, host=None): conn_str = ('dbname=%s host=%s' % (db, host)) if (user is not None): conn_str = (conn_str + (' user=%s' % user)) if (password is not None): conn_str = (conn_str + (' password=%s' % password)) conn = psycopg2.co...
def _is_stopped(demo, i, obs, stopped_buffer, delta=0.1): next_is_not_final = (i == (len(demo) - 2)) gripper_state_no_change = ((i < (len(demo) - 2)) and ((obs.gripper_open == demo[(i + 1)].gripper_open) and (obs.gripper_open == demo[(i - 1)].gripper_open) and (demo[(i - 2)].gripper_open == demo[(i - 1)].grippe...
def truncate_seq_pair(tokens_a, tokens_b, max_length): while True: total_length = (len(tokens_a) + len(tokens_b)) if (total_length <= max_length): break if (len(tokens_a) > len(tokens_b)): tokens_a.pop(0) else: tokens_b.pop(0)
class A002113(SloaneSequence): def __init__(self): SloaneSequence.__init__(self, offset=0) def _repr_(self): return 'Palindromes in base 10.' def _precompute(self, how_many=150): try: self._b self._n except AttributeError: self._b = [] ...
class Decoder(layers.Layer): def __init__(self, original_dim, intermediate_dim=600, name='decoder', regularization_lambda=0.01, random_seed=42, **kwargs): super().__init__(name=name, **kwargs) tf.random.set_seed(random_seed) self.dense_proj = layers.Dense(intermediate_dim, activation='tanh',...
def save_models(path: str, net, *, write_layers=True, file_format=None): os.makedirs(path, exist_ok=True) net_name = net.get_name() _save_net_file(path, net_name, net, file_format=file_format) if write_layers: models = bb.get_model_list(net, flatten=True) fname_list = [] for (i, ...
_properties class StencilTiling(transformation.SubgraphTransformation): debug = Property(desc='Debug mode', dtype=bool, default=False) prefix = Property(dtype=str, default='stencil', desc='Prefix for new inner tiled range symbols') strides = ShapeProperty(dtype=tuple, default=(1,), desc='Tile stride') s...
class TFConvBertForTokenClassification(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
def test_recordarray_7(): def test_recordarray_7(x): return ((2 * x.y[(2, 0, 1)]) + 10) (value_jvp, jvp_grad) = jax.jvp(test_recordarray_7, (test_recordarray,), (test_recordarray_tangent,)) (value_vjp, vjp_func) = jax.vjp(test_recordarray_7, test_recordarray) assert (ak.to_list(value_jvp) == 14....
def load_dataset(choice, data_dir='./data/'): if (choice == 'mnist2d'): from datasets.mnist import mnist2d_10class return mnist2d_10class(data_dir) if (choice == 'mnist2d_2class'): from datasets.mnist import mnist2d_2class return mnist2d_2class(data_dir) if (choice == 'mnistv...
class Sampler(torch.utils.data.Sampler): def __init__(self, buckets, batch_size, shuffle=False, distributed=False, evaluate=False): self.batch_size = batch_size self.shuffle = shuffle (self.sizes, self.buckets) = zip(*[(size, bucket) for (size, bucket) in buckets.items()]) self.chunk...