code
stringlengths
101
5.91M
def batch_accuracy(predicted, true): (_, predicted_index) = predicted.max(dim=1, keepdim=True) agreeing = true.gather(dim=1, index=predicted_index) return (agreeing * 0.3).clamp(max=1)
class ChooseSimpleDummyVecEnv(ShareVecEnv): def __init__(self, env_fns): self.envs = [fn() for fn in env_fns] env = self.envs[0] ShareVecEnv.__init__(self, len(env_fns), env.observation_space, env.share_observation_space, env.action_space) self.actions = None def step_async(self,...
class Test(): def __init__(self, levels=20, weights=4, onlyg0=False, onlyg1=False, onlychar=False): if (not isinstance(levels, list)): levels = list(range(1, (int(levels) + 1))) if (not isinstance(weights, list)): weights = list(range(2, (int(weights) + 1))) self.leve...
def _remove_starting_and_ending_whitespace(text): return '\n'.join([line.strip() for line in text.split('\n')])
def make_parser(): p = ArgumentParser('nightly') subcmd = p.add_subparsers(dest='subcmd', help='subcommand to execute') co = subcmd.add_parser('checkout', help='checkout a new branch') co.add_argument('-b', '--branch', help='Branch name to checkout', dest='branch', default=None, metavar='NAME') pull...
def reset_the_weight_value(inputs, output_axis, threshold): (x, w) = inputs[:2] shape = w.shape from functools import reduce items = reduce((lambda x, y: (x * y)), shape) upbound = ((threshold / (items / shape[output_axis])) ** 0.5) (slice0, slice1) = (None, None) if (output_axis == 0): ...
def test_power_constant(): var1 = optplan.Parameter() power1 = (var1 ** optplan.make_constant(2)) assert isinstance(power1, optplan.Power) assert (power1.function == var1) assert (power1.exp == 2)
def print_object(obj: Any, *, print_all_tensors: bool=False, stats_only: bool=False, prefix: str='', ctx: Optional[PrintCtx]=None, ctx_name: Optional[str]=None): if isinstance(obj, (dict, list, tuple)): for (k, v) in (obj.items() if isinstance(obj, dict) else enumerate(obj)): _print_key_value(k,...
def configure(dir=None, format_strs=None, comm=None, log_suffix=''): if (dir is None): dir = os.getenv('OPENAI_LOGDIR') if (dir is None): dir = osp.join(tempfile.gettempdir(), datetime.datetime.now().strftime('sony-%Y-%m-%d-%H-%M-%S-%f')) assert isinstance(dir, str) dir = os.path.expandu...
def main(model_name: str, backbone_name: str, image_size: list, num_classes: int, device: str): device = torch.device(('cuda' if (torch.cuda.is_available() and (device == 'cuda')) else 'cpu')) inputs = torch.randn(1, 3, *image_size).to(device) model = eval(model_name)(backbone_name, num_classes) model =...
def _new_invariant_is_linearly_independent(F, invariants): if (len(invariants) == 0): return True return (PolynomialSequence(invariants).coefficient_matrix()[0].rank() != PolynomialSequence((list(invariants) + [F])).coefficient_matrix()[0].rank())
def perceptualLoss(fakeIm, realIm, vggnet): weights = [1, 0.2, 0.04] features_fake = vggnet(fakeIm) features_real = vggnet(realIm) features_real_no_grad = [f_real.detach() for f_real in features_real] mse_loss = nn.MSELoss(reduction='elementwise_mean') loss = 0 for i in range(len(features_re...
class TestOnPolicyVectorizedSampler(TfGraphTestCase): .parametrize('cpus, n_envs, expected_n_envs', [*configs]) def test_on_policy_vectorized_sampler_n_envs(self, cpus, n_envs, expected_n_envs): with LocalTFRunner(snapshot_config, sess=self.sess, max_cpus=cpus) as runner: env = GarageEnv(gym...
class Scenario(BaseScenario): def __init__(self, num_agents=4, dist_threshold=0.1, arena_size=1, identity_size=0): self.num_agents = num_agents self.target_radius = 0.5 self.ideal_theta_separation = ((2 * np.pi) / self.num_agents) self.arena_size = arena_size self.dist_thres ...
def gaussian(birth, pers, mu=None, sigma=None): if (mu is None): mu = np.array([0.0, 0.0], dtype=np.float64) if (sigma is None): sigma = np.array([[1.0, 0.0], [0.0, 1.0]], dtype=np.float64) if (sigma[0][1] == 0.0): return sbvn_cdf(birth, pers, mu_x=mu[0], mu_y=mu[1], sigma_x=sigma[0]...
def _evaluate_predictions_on_coco(coco_gt, coco_results, min_threshold=0.5): metrics = ['AP'] if (min_threshold <= 0.201): metrics += ['AP20'] if (min_threshold <= 0.301): metrics += ['AP30'] if (min_threshold <= 0.401): metrics += ['AP40'] metrics.extend(['AP50', 'AP75', 'AP...
class AdamWClonedWeightPrediction(WeightPredictor): def __init__(self, *args, **kw): super().__init__(*args, **kw) adam_init(self.optimizer) def forward(self): if (not self.n_steps): return self.true_weights_storage.create_cloned_if_needed() self.true_weights_...
def _is_equal_tensor_proto(a, b): name_a = a.name name_b = b.name a.name = '' b.name = '' res = (a == b) a.name = name_a b.name = name_b return res
class PrimitiveLocalComponent(LocalComponentBase): def is_primitive(self): return True def minimal_twist(self): return self
def cross_entropy(*, estimated: Tensor, target: Tensor, axis: Dim, estimated_type: str) -> Tensor: if (estimated_type == 'logits'): return estimated._raw_backend.softmax_cross_entropy_with_logits(logits=estimated, targets=target, axis=axis) if (estimated_type == 'probs'): log_prob = rf.log(estim...
def main(args, dataspecs, **kw): runner = EasyTorch(dataspecs, args, load_sparse=True, **kw) runner.run(VesselSegTrainer, BinarySemSegImgPatchDatasetCustomTransform)
_module() class Compose(object): def __init__(self, transforms): assert isinstance(transforms, Sequence) self.transforms = [] for transform in transforms: if isinstance(transform, dict): transform = build_from_cfg(transform, PIPELINES) self.transfo...
def benchmark(ws, net, warmups=5, iters=100): for _ in range(warmups): ws.run(net) plan = core.Plan('plan') plan.AddStep(core.ExecutionStep('test-step', net, iters)) before = time.time() ws.run(plan) after = time.time() print('Timing network, time taken per-iteration: {:.6f}ms'.forma...
def loads(s, _dict=dict, decoder=None): implicitgroups = [] if (decoder is None): decoder = TomlDecoder(_dict) retval = decoder.get_empty_table() currentlevel = retval if (not isinstance(s, basestring)): raise TypeError('Expecting something like a string') if (not isinstance(s, u...
def read_table_csv(table_obj, csv_seperator=','): df_rows = pd.read_csv(table_obj.csv_file_location, escapechar='\\', encoding='utf-8', quotechar='"', sep=csv_seperator) df_rows.columns = [((table_obj.table_name + '.') + attr) for attr in table_obj.attributes] for attribute in table_obj.irrelevant_attribute...
def parameter_count(model: PyTree): leaves = {id(x): x for x in jax.tree_util.tree_leaves(model) if is_jax_array_like(x)} return sum((x.size for x in leaves.values()))
class PcgrlCtrlEnv(PcgrlEnv): def __init__(self, cfg: Config, prob='binary_ctrl', rep='narrow'): super(PcgrlCtrlEnv, self).__init__(cfg, prob, rep) self.cond_bounds = self._prob.cond_bounds self.static_trgs = self._prob.static_trgs def set_map(self, init_map): self._rep._random_s...
def get_preprocessor(imsize): def vgg_preprocess(tensor): (r, g, b) = torch.chunk(tensor, 3, dim=0) bgr = torch.cat((b, g, r), 0) out = ((bgr * 255) - vgg_mean.type(tensor.type()).expand_as(bgr)) return out preprocess = transforms.Compose([transforms.Resize(imsize), transforms.To...
def show_img(img_id): img_map = get_img_map(img_folder_list) img_path = img_map[img_id] print('Reading image from: ', img_path) plt.imshow(plt.imread(img_path))
def canonicalize_sql_example(query, sql, ast): query = re.sub('<.*?>', '', query) query_tokens = nltk.word_tokenize(query) parse_tree = parse_raw(ast) return (query_tokens, sql, parse_tree)
def create_logger(app): logger = logging.getLogger(app.name) for old_name in ('flask.app', 'flask'): old_logger = logging.getLogger(old_name) if (_has_config(old_logger) and (not _has_config(logger))): warnings.warn("'app.logger' is named '{name}' for this application, but configurat...
def l2_promote(): import ctypes _libcudart = ctypes.CDLL('libcudart.so') pValue = ctypes.cast((ctypes.c_int * 1)(), ctypes.POINTER(ctypes.c_int)) _libcudart.cudaDeviceSetLimit(ctypes.c_int(5), ctypes.c_int(128)) _libcudart.cudaDeviceGetLimit(pValue, ctypes.c_int(5)) assert (pValue.contents.value...
class recursive(object): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): return self.func(self, *args, **kwargs)
class ListModule(nn.Module): def __init__(self, *args): super(ListModule, self).__init__() idx = 0 for module in args: self.add_module(str(idx), module) idx += 1 def __getitem__(self, idx): if ((idx < 0) or (idx >= len(self._modules))): raise I...
class pAdicFieldFloatingPoint(pAdicFieldBaseGeneric, pAdicFloatingPointFieldGeneric): def __init__(self, p, prec, print_mode, names): pAdicFieldBaseGeneric.__init__(self, p, prec, print_mode, names, pAdicFloatingPointElement) def _coerce_map_from_(self, R): if (isinstance(R, (pAdicRingFixedMod, ...
def _check_PSK(state: GameState): not_passed = (state.consecutive_pass_count == 0) is_psk = (not_passed & (jnp.abs((state.board_history[0] - state.board_history[1:])).sum(axis=1) == 0).any()) return is_psk
def load_train_data(csv_file, n_items): tp = pd.read_csv(csv_file) n_users = (tp['uid'].max() + 1) (rows, cols) = (tp['uid'], tp['sid']) data = sparse.csr_matrix((np.ones_like(rows), (rows, cols)), dtype='float64', shape=(n_users, n_items)) return data
def _wrap_reader_for_text(fp, encoding): if isinstance(fp.read(0), bytes): fp = io.TextIOWrapper(io.BufferedReader(fp), encoding) return fp
class MT10(Benchmark): def __init__(self): super().__init__() self._train_classes = _env_dict.EASY_MODE_CLS_DICT self._test_classes = OrderedDict() train_kwargs = _env_dict.EASY_MODE_ARGS_KWARGS self._train_tasks = _make_tasks(self._train_classes, train_kwargs, _MT_OVERRIDE) ...
def harness(policy, throughputs, scale_factors, priority_weights, cluster_spec, num_sub_clusters=1, random_cluster_assignment=False): start_time = time.time() sub_cluster_throughputs = [] sub_cluster_scale_factors = [] sub_cluster_priority_weights = [] job_to_sub_cluster_assignment = {} job_ids ...
class PassageDB(): def __init__(self, input_file: str): self._input_file = input_file self._db = lmdb.open(input_file, subdir=False, readonly=True) def __reduce__(self): return (self.__class__, (self._input_file,)) def __len__(self): return self._db.stat()['entries'] def ...
def collate_batch(batch): input_patches = [] for input_patch in batch: input_patches.append(input_patch.reshape((- 1))) input_patches = torch.nn.utils.rnn.pad_sequence(input_patches, batch_first=True, padding_value=0) return input_patches.to(device)
_module() class DetectoRS_ResNeXt(DetectoRS_ResNet): arch_settings = {50: (Bottleneck, (3, 4, 6, 3)), 101: (Bottleneck, (3, 4, 23, 3)), 152: (Bottleneck, (3, 8, 36, 3))} def __init__(self, groups=1, base_width=4, **kwargs): self.groups = groups self.base_width = base_width super(DetectoR...
def standardize_constraints(constraints, x0, meth): all_constraint_types = (NonlinearConstraint, LinearConstraint, dict) new_constraint_types = all_constraint_types[:(- 1)] if isinstance(constraints, all_constraint_types): constraints = [constraints] constraints = list(constraints) if (meth ...
def test_langlower(): assert (lang_to_langcode('WOLOF') == 'wo') assert (lang_to_langcode('nOrWeGiAn') == 'nb') assert ('soj' == langlower2lcode['soi']) assert ('soj' == langlower2lcode['sohi'])
class PickleCache(): def __init__(self, cache_name, overwrite=False): self.cache_name = cache_name self.exists = os.path.exists(cache_name) self.overwrite = overwrite self.v = None def __enter__(self): if self.exists: print(f'loading from cache: {self.cache_na...
def get_fans_or_followers_ids(user_id, crawl_type): if (crawl_type == 1): fans_or_follows_url = ' else: fans_or_follows_url = ' cur_page = 1 max_page = 6 user_ids = list() while (cur_page < max_page): url = fans_or_follows_url.format(user_id, cur_page) page = get_...
class ASPP(nn.Module): def __init__(self, in_channels, out_channels, dilations, *, norm, activation, pool_kernel_size=None, dropout: float=0.0, use_depthwise_separable_conv=False): super(ASPP, self).__init__() assert (len(dilations) == 3), 'ASPP expects 3 dilations, got {}'.format(len(dilations)) ...
def register_Ns3SimpleRefCount__Ns3RadvdInterface_Ns3Empty_Ns3DefaultDeleter__lt__ns3RadvdInterface__gt___methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::SimpleRefCount< ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter< ns3::RadvdInterface > > const &', 'o')]) return
def _seg_11(): return [(2652, 'V'), (2653, 'X'), (2654, 'M', u''), (2655, 'X'), (2662, 'V'), (2679, 'X'), (2689, 'V'), (2692, 'X'), (2693, 'V'), (2702, 'X'), (2703, 'V'), (2706, 'X'), (2707, 'V'), (2729, 'X'), (2730, 'V'), (2737, 'X'), (2738, 'V'), (2740, 'X'), (2741, 'V'), (2746, 'X'), (2748, 'V'), (2758, 'X'), (2...
def prepara_inference_dict(pos_batch, neg_batch): (pos_pre_input_ids, pos_pre_attention_mask, pos_pre_type_ids, pos_hyp_input_ids, pos_hyp_attention_mask, pos_hyp_type_ids, neg_pre_input_ids, neg_pre_attention_mask, neg_pre_type_ids, neg_hyp_input_ids, neg_hyp_attention_mask, neg_hyp_type_ids) = prepare_inference_b...
class ParameterList(Module): _parameters: Dict[(str, 'Parameter')] def __init__(self, parameters: Optional[Iterable['Parameter']]=None) -> None: super(ParameterList, self).__init__() self._initialized = True if (parameters is not None): self += parameters def __setstate__...
def train(train_loader, model, criterion, optimizer, epoch, args): batch_time = AverageMeter('Time', ':6.3f') data_time = AverageMeter('Data', ':6.3f') losses = AverageMeter('Loss', ':.4e') top1 = AverageMeter('', ':6.2f') top5 = AverageMeter('', ':6.2f') progress = ProgressMeter(len(train_loade...
def extract_czeng17(extract_folder, debug=False): url = ' filename = f'{download_to}/convert_czeng16_to_17.pl.zip' extract_to = f'{extract_folder}/{get_extract_name(filename)}' script_path = f'{extract_to}/convert_czeng16_to_17.pl' if (not os.path.exists(script_path)): wget.download(url, fil...
def str_format_dynamic_dtype(op): fmt_str = '\n OpInfo({name},\n dtypes={dtypesIfCPU},\n dtypesIfCUDA={dtypesIfCUDA},\n )\n '.format(name=op.name, dtypesIfCPU=dtypes_dispatch_hint(op.dtypesIfCPU).dispatch_fn_str, dtypesIfCUDA=dtypes_dispatch_hint(op.dtypesIfCUDA).dis...
def spantemplate6(text_w_pairs): (cause, effect) = get_cause_effect_spans(text_w_pairs) question = f'What resulted from "{cause}"?' answers = {'text': effect} return (question, answers)
def add_text_generate_args(parser): group = parser.add_argument_group('Text generation', 'configurations') group.add_argument('--temperature', type=float, default=1.0) group.add_argument('--greedy', action='store_true', default=False) group.add_argument('--top_p', type=float, default=0.0) group.add_...
def _get_mangled_gpu_name(): name = torch.cuda.get_device_name().lower() out = [] for c in name: if re.match('[a-z0-9_-]+', c): out.append(c) else: out.append('-') return ''.join(out)
.parametrize('size, actions, expected_reward, random_state, expected_delays', [(2, 2, np.asarray([[1, 0.01], [0.5, 0.5]]), 12344, np.asarray([[2.0, 55.0], [3.0, 27.0]])), (2, 2, np.asarray([[0.1, 0.2], [0.3, 0.4]]), 12345, np.asarray([[242.0, 32.0], [15.0, 15.0]]))]) def test_exponential_delay_function_conditioned_on_e...
class SetPartitionsBkhalf_k(SetPartitionsAkhalf_k): def _repr_(self): return (SetPartitionsAkhalf_k._repr_(self) + ' and with block size 2') def __contains__(self, x): if (not SetPartitionsAkhalf_k.__contains__(self, x)): return False for part in x: if (len(part) ...
.parametrize('through', [through_arrow, through_parquet]) .parametrize('extensionarray', [False, True]) def test_unmaskedarray_numpyarray(tmp_path, through, extensionarray): akarray = ak.contents.UnmaskedArray(ak.contents.NumpyArray(np.array([1.1, 2.2, 3.3]), parameters={'which': 'inner'})) (schema_arrow, array...
class UnitNormLayer(tf.keras.layers.Layer): def __init__(self): super(UnitNormLayer, self).__init__() def call(self, input_tensor): norm = tf.norm(input_tensor, axis=1) return (input_tensor / tf.reshape(norm, [(- 1), 1]))
def inference(image, prompt, min_len=1, max_len=250, beam_size=5, len_penalty=(- 1), repetition_penalty=1, top_p=0.9, decoding_method='Beam Search', num_captions=1, temperature=1.0, video=False): use_nucleus_sampling = (decoding_method == 'Nucleus sampling') print(image, prompt, min_len, max_len, beam_size, len...
_module(name='Normal') class NormalInit(BaseInit): def __init__(self, mean: float=0, std: float=1, **kwargs): super().__init__(**kwargs) self.mean = mean self.std = std def __call__(self, module: nn.Module) -> None: def init(m): if self.wholemodule: no...
def get_margin(transcript, agent=None, role=None): if (role is not None): scenario = transcript['scenario'] roles = {scenario['kbs'][0]['personal']['Role']: 0, scenario['kbs'][1]['personal']['Role']: 1} agent = roles[role] if (agent is None): winner = get_winner(transcript) ...
_test() def test_gemv_fpga_tiles_by_column(): return run_gemv('tiles_by_column', 256, 512, transposed=True, vectorize=4)
def test_float(): plt.figure() with expected_warnings((imshow_expected_warnings + ['CObject type is marked|\\A\\Z'])): ax_im = io.imshow(imf) assert (ax_im.cmap.name == 'gray') assert (ax_im.get_clim() == (0, 1)) assert (n_subplots(ax_im) == 1) assert (ax_im.colorbar is None)
class Profile(): def __init__(self, sc, job_id, load_threads=8, subsample=None): self._storage = sc._storage job = sc._load_descriptor(protobufs.BulkJobDescriptor, 'jobs/{}/descriptor.bin'.format(job_id)) def get_prof(path, worker=True): file_info = self._storage.get_file_info(pa...
def filter_var_wo_type(df_vars: pd.DataFrame) -> pd.DataFrame: df_var_len = len(df_vars) logger.info(f'Variables before dropping: {len(df_vars):,}') df_vars = df_vars[df_vars['var_type'].notnull()] logger.info(f'Variables after dropping dropping: {len(df_vars):,}') logger.info(f'Filtered out {(df_va...
class ResponseStreamMixin(object): _property def stream(self): return ResponseStream(self)
def IsInt(a): if z3_debug(): _z3_assert(a.is_real(), 'Z3 real expression expected.') ctx = a.ctx return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
class CFExplanation(ExplanationBase): def __init__(self): super().__init__() self.explanations = [] def __repr__(self): return repr(self.explanations) def add(self, query, cfs, **kwargs): e = {'query': query, 'counterfactual': cfs} e.update(kwargs) self.explan...
def calc_mean_rank(src, pred): rank = [] for (s, p) in zip(src, pred): cur_rank = [] cmd_name = s['cmd_name'] pred_man = p['pred'] oracle_man = get_oracle(s, cmd_name) for o in oracle_man: if (o in pred_man): cur_rank.append(oracle_man.index(o)...
def set_blob_potential(implementation): if (implementation == 'None'): def default_zero_r_vectors(*args, **kwargs): return 0 return default_zero elif (implementation == 'python'): return calc_blob_potential_python elif (implementation == 'C++'): return calc_blob_p...
def diff_str(first, second): firstlines = first.splitlines(keepends=True) secondlines = second.splitlines(keepends=True) if ((len(firstlines) == 1) and (first.strip('\r\n') == first)): firstlines = [(first + '\n')] secondlines = [(second + '\n')] return ''.join(difflib.unified_diff(first...
class FiniteDiffGradient(ApproxGradientBase): def __init__(self, fun: callable, eps: float=0.01, formula: str='central') -> None: self.fun = fun self.eps = eps self.formula = formula if (formula not in ('central', 'forward', 'backwards', 'five-point')): raise ValueError((...
def main(args): if args.paint: import matplotlib matplotlib.use('Agg') enable_notify = args.enable_notify enable_tensorboard = args.enable_tensorboard enable_attention_check = args.enable_attention_check enable_visualize_check = args.enable_visualize_check enable_sam = args.enabl...
class ETSDetectorParams(Config): max_forecast_steps: int = None target_seq_index: int = None error: str = 'add' trend: str = 'add' damped_trend: bool = True seasonal: str = 'add' seasonal_periods: str = None refit: bool = True kwargs: dict = {}
def add_train_opts(parser): parser.add_argument('--manual_seed', default=0, type=int, help='manual seed') parser.add_argument('-j', '--workers', default=16, type=int, help='number of workers') parser.add_argument('--epochs', default=35, type=int, help='number epochs') parser.add_argument('--batch_size',...
def test_lora_scan_layers(): class Module(eqx.Module): first: hnn.Linear second: hnn.Linear def __call__(self, x): return self.second(self.first(x)) def init(*, key): (k1, k2) = jax.random.split(key) first = hnn.Linear.init(In, Mid, key=k1) ...
def load_data(args, tasks): logging.info('loading data') train_queries = pickle.load(open(os.path.join(args.data_path, 'train-queries.pkl'), 'rb')) train_answers = pickle.load(open(os.path.join(args.data_path, 'train-answers.pkl'), 'rb')) valid_queries = pickle.load(open(os.path.join(args.data_path, 'va...
class BiFpnLayer(nn.Module): def __init__(self, feature_info, feat_sizes, fpn_config, fpn_channels, num_levels=5, pad_type='', downsample=None, upsample=None, norm_layer=nn.BatchNorm2d, act_layer=_ACT_LAYER, apply_resample_bn=False, pre_act=True, separable_conv=True, redundant_bias=False): super(BiFpnLayer,...
def build_keras_ensemble(data: Dataset, ensemble_size: int=5, num_hidden_layers: int=2, units: int=25, activation: Union[(str, tf.keras.layers.Activation)]='relu', independent_normal: bool=False) -> KerasEnsemble: (input_tensor_spec, output_tensor_spec) = get_tensor_spec_from_data(data) hidden_layer_args = [] ...
_function_dispatch(_ix__dispatcher) def ix_(*args): out = [] nd = len(args) for (k, new) in enumerate(args): if (not isinstance(new, _nx.ndarray)): new = asarray(new) if (new.size == 0): new = new.astype(_nx.intp) if (new.ndim != 1): raise ...
def _make_features(n_samples, n_features, seed): rnd = np.random.RandomState(seed) return rnd.randn(n_samples, n_features)
def test_fastica_whiten_unit_variance(): rng = np.random.RandomState(0) X = rng.random_sample((100, 10)) n_components = X.shape[1] ica = FastICA(n_components=n_components, whiten='unit-variance', random_state=0) Xt = ica.fit_transform(X) assert (np.var(Xt) == pytest.approx(1.0))
class SimpleStructuresWrapper(SpeciesWrapper): def __init__(self, species, labels, structure_class): SpeciesWrapper.__init__(self, species, labels, '_simple_structures_selector', 'generating_series', 'Simple structures', structure_class)
class DeiTConfig(PretrainedConfig): model_type = 'deit' def __init__(self, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, initializer_range=0.02, layer_norm_eps=1e-12, image_size=224, patch_size...
_utils.test() def test_atomic_max_expr_evaled(): c = ti.field(ti.i32) step = 42 ti.root.place(c) def func(): for i in range(n): ti.atomic_max(c[None], (i * step)) func() assert (c[None] == ((n - 1) * step))
.experimental def test_drop_duplicates(spark, duplicate_recs): recs = drop_duplicates(duplicate_recs) gt = spark.createDataFrame(data=[[0, 0, 3.0], [0, 1, 2.0], [0, 2, 1.0], [1, 0, 3.0], [1, 1, 4.0], [1, 4, 1.0], [2, 0, 5.0], [2, 2, 1.0], [2, 3, 2.0]], schema=REC_SCHEMA) sparkDataFrameEqual(recs, gt)
def specht_module_spanning_set(D, SGA=None): n = len(D) if (SGA is None): from sage.combinat.symmetric_group_algebra import SymmetricGroupAlgebra SGA = SymmetricGroupAlgebra(QQ, n) elif (SGA.group().rank() != (n - 1)): raise ValueError('the rank does not match the size of the diagram...
def main(): config = bootstrap() config[MODEL][ENV] = CARTPOLE config[MODEL][AGENT] = REINFORCE config[MODEL][USE_BASELINE] = True run(config=config)
def evaluate(model, test_idxs, fold, train_idxs_tmp, train_idxs): model.eval() batch_idx = 1 total_loss = 0 global max_f1, max_acc, min_mae, X_test_lens, max_prec, max_rec pred = np.array([]) with torch.no_grad(): if config['cuda']: (x, y) = (Variable(torch.from_numpy(audio_f...
def _create_entry(question, answer): answer.pop('image_id') answer.pop('question_id') entry = {'question_id': question['question_id'], 'image_id': question['image_id'], 'question': question['question'], 'answer': answer} return entry
def all_newer(src_files, dst_files): return all(((os.path.exists(dst) and newer(dst, src)) for dst in dst_files for src in src_files))
class TestNegateGradient(serial.SerializedTestCase): (X=hu.tensor(), inplace=st.booleans(), **hu.gcs) (deadline=10000) def test_forward(self, X, inplace, gc, dc): def neg_grad_ref(X): return (X,) op = core.CreateOperator('NegateGradient', ['X'], [('Y' if (not inplace) else 'X')])...
def launch(): TIME_TO_WAKE = 2 args = ['ciao', 'mare'] core.callDelayed(TIME_TO_WAKE, timeout_handler, args) t = Timer(TIME_TO_WAKE, timeout_handler, args='t1') t2 = Timer(TIME_TO_WAKE, timeout_handler, absoluteTime=True, args='t2') tr = Timer(TIME_TO_WAKE, timeout_handler, absoluteTime=False, r...
class Infinite(object): file = stderr sma_window = 10 check_tty = True hide_cursor = True def __init__(self, message='', **kwargs): self.index = 0 self.start_ts = monotonic() self.avg = 0 self._avg_update_ts = self.start_ts self._ts = self.start_ts sel...
class SnowballStemmer(): languages = ('arabic', 'danish', 'dutch', 'english', 'finnish', 'french', 'german', 'hungarian', 'italian', 'norwegian', 'polish', 'portuguese', 'romanian', 'russian', 'spanish', 'swedish') def __init__(self, language): if (language not in self.languages): raise Valu...
def build_sparse_features(data): side_information_data = data.side_information_data sp_i_f = [] for (key_side_feature_type, value) in vars(side_information_data).items(): rows_cols = [(data.public_items[item], data.public_features[f]) for (item, features) in value.items() for f in features] ...