code
stringlengths
101
5.91M
class SphereBivariateSpline(_BivariateSplineBase): def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True): theta = np.asarray(theta) phi = np.asarray(phi) if ((theta.size > 0) and ((theta.min() < 0.0) or (theta.max() > np.pi))): raise ValueError('requested theta out of bound...
def get_boomerang_r_vectors_15(location, orientation): initial_configuration = [np.array([2.1, 0.0, 0.0]), np.array([1.8, 0.0, 0.0]), np.array([1.5, 0.0, 0.0]), np.array([1.2, 0.0, 0.0]), np.array([0.9, 0.0, 0.0]), np.array([0.6, 0.0, 0.0]), np.array([0.3, 0.0, 0.0]), np.array([0.0, 0.0, 0.0]), np.array([0.0, 0.3, ...
def is_test_file(filenum): if (filenum in TEST_FILES): return True if ((filenum >= 1) and (filenum <= 43)): return True if ((filenum >= 144) and (filenum <= 169)): return True if ((filenum >= 900) and (filenum <= 931)): return True return False
def test_vfi_dataset(): test_ = TestVFIDataset() test_.test_base_vfi_dataset() test_.test_vfi_vimeo90k_dataset()
def _list_categories(tag): url = (' + tag) f = urllib.request.urlopen(url) return json.loads(f.read())
def tally_parameters(model): n_params = sum([p.nelement() for p in model.parameters()]) print(('* number of parameters: %d' % n_params)) enc = 0 dec = 0 for (name, param) in model.named_parameters(): if ('encoder' in name): enc += param.nelement() elif ('decoder' or ('gen...
() def lamldataset_30_2(): return NumpyDataset(data=np.array([[(- 0.), 0.], [0., 0.], [0., 0.], [0., 0.], [0., 0.], [0., 0.], [0., 0.], [0., 0.], [0., 0.], [0., 0.], [0.4031683, 0.], [0., 0.], [0., 0.], [0., 0.4621607], [0., 0.], [0., 0.], [0., 0.], [0., 0.], [0., 0.], [0., 0.], [0., 0.6000393], [0., 0.], [0.737522...
class FGSM(DenseAttack): def __init__(self, **kwargs): super().__init__(**kwargs) assert self.make_undirected, 'Attack only implemented for undirected graphs' self.adj_perturbed = self.adj.clone().requires_grad_(True).to(self.device) self.n_perturbations = 0 self.adj = self.a...
def loading_data(datasetname, val_interval): datasetname = datasetname.upper() cfg_data = getattr(setting, datasetname).cfg_data Dataset = dataset.Dataset train_loader = createTrainData(datasetname, Dataset, cfg_data) restore_transform = createRestore(cfg_data.MEAN_STD) Dataset = dataset.TestDat...
_torch class XLMModelTest(ModelTesterMixin, unittest.TestCase): all_model_classes = ((XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple) if is_torch_available() else ()) class XLMModelTester(object): def __init__(self, parent, batch_size=1...
def patch(model, target, updater, *args, **kwargs): for (name, module) in model.named_children(): model._modules[name] = patch(module, target, updater, *args, **kwargs) if isinstance(model, target): return updater.create_from(model, *args, **kwargs) return model
def check_named_results(res, attributes, ma=False): for (i, attr) in enumerate(attributes): if ma: ma_npt.assert_equal(res[i], getattr(res, attr)) else: npt.assert_equal(res[i], getattr(res, attr))
def train_loader(args): traindir = os.path.join(args.data, 'train') train_loader = torch.utils.data.DataLoader(datasets.ImageFolder(traindir, train_transforms(args.inpSize, scale=args.scale)), batch_size=args.batch_size, shuffle=True, num_workers=args.workers, pin_memory=True) return train_loader
def load_generated_images(path): images = [] for i in range(N_imgs): f = '{:04d}_rgb.png'.format(i) images.append(trn(Image.open(os.path.join(path, f)))) return torch.stack(images)
class MLP(Layer): def __init__(self, hidden_units, activation=tf.nn.tanh, name='mlp'): super(MLP, self).__init__(name) self.activation = activation self.projecting_layers = [tf.keras.layers.Dense(hidden_units, activation=None) for _ in range(2)] self.score_layer = tf.keras.layers.Den...
def add_img(img, all_imgs): if (all_imgs is None): all_imgs = [] all_imgs.append(img) return (None, all_imgs, all_imgs)
class LazyConv3d(_LazyConvXdMixin, Conv3d): cls_to_become = Conv3d def __init__(self, out_channels: int, kernel_size: _size_3_t, stride: _size_3_t=1, padding: _size_3_t=0, dilation: _size_3_t=1, groups: int=1, bias: bool=True, padding_mode: str='zeros', device=None, dtype=None) -> None: factory_kwargs =...
def compute_effective_axis_dimension(dimension: int, fixed_dimension: int, num_token_to_add: int=0) -> int: if (dimension <= 0): dimension = fixed_dimension dimension -= num_token_to_add return dimension
def parse_domain_pddl(domain_pddl): iterator = iter(domain_pddl) define_tag = next(iterator) assert (define_tag == 'define') domain_line = next(iterator) assert ((domain_line[0] == 'domain') and (len(domain_line) == 2)) (yield domain_line[1]) requirements = pddl.Requirements([':strips']) ...
class Dispatch(): def __init__(self, kernel: Kernel, args: List[NamedArgument]): self.kernel = kernel self.args = args
def test_random_df(random_df: pd.DataFrame) -> None: plot(random_df) plot(random_df, display=['Bar Chart'])
_params def test_quad_vec_simple(quadrature): n = np.arange(10) def f(x): return (x ** n) for epsabs in [0.1, 0.001, 1e-06]: if ((quadrature == 'trapezoid') and (epsabs < 0.0001)): continue kwargs = dict(epsabs=epsabs, quadrature=quadrature) exact = ((2 ** (n + 1)...
def log_bernoulli(x, mean, average=False, dim=None): probs = torch.clamp(mean, min=min_epsilon, max=max_epsilon) log_bernoulli = ((x * torch.log(probs)) + ((1.0 - x) * torch.log((1.0 - probs)))) if average: return torch.mean(log_bernoulli, dim) else: return torch.sum(log_bernoulli, dim)
def run(task: Task, num_samples: int, num_simulations: int, num_observation: Optional[int]=None, observation: Optional[torch.Tensor]=None, population_size: Optional[int]=None, distance: str='l2', epsilon_decay: float=0.2, distance_based_decay: bool=True, ess_min: Optional[float]=None, initial_round_factor: int=5, batch...
class _BaseNetwork(_IPAddressBase): def __init__(self, address): self._cache = {} def __repr__(self): return ('%s(%r)' % (self.__class__.__name__, _compat_str(self))) def __str__(self): return ('%s/%d' % (self.network_address, self.prefixlen)) def hosts(self): network = i...
class FeatureExtraction(torch.nn.Module): def __init__(self, train_fe=False, feature_extraction_cnn='vgg19', normalization=True, last_layer='', weights=None, use_cuda=True, gpu=0, ref_backbone=None): super(FeatureExtraction, self).__init__() self.normalization = normalization print(f'layer: ...
class HighwayExitSample(): def __init__(self): curvature_range = [(- 0.03), 0.03] self.c1 = world.world.rng_road_network.uniform(low=curvature_range[0], high=curvature_range[1]) self.c2 = world.world.rng_road_network.uniform(low=(- 0.005), high=0.005) self.c3 = world.world.rng_road_n...
def test_petsc_error(ocp_ksp, u, rng): with pytest.raises(PETScKSPError) as e_info: u.vector().set_local(rng.rand(u.vector().local_size())) u.vector().apply('') ocp_ksp.compute_state_variables() MPI.barrier(MPI.comm_world) assert ('PETSc linear solver did not converge.' in str(e_info...
def patch_os_environ_helper(custom_environ: dict, excludes: dict): environ = {} for key in os.environ.keys(): if (key not in excludes): environ[key] = os.environ[key] for key in custom_environ.keys(): environ[key] = custom_environ[key] try: cached_environ = os.environ...
class ModulusLikelihood(Likelihood): def __init__(self, y, y_name='y', isotropic=True): self.y_name = y_name self.size = self.get_size(y) self.isotropic = isotropic self.repr_init() self.y = y def sample(self, Z): Z = array2complex(Z) return np.absolute(Z)...
class InstancesSchema(DictSchema): def __call__(self, values): (image_size, fields) = (values[(- 1)], values[:(- 1)]) fields = super().__call__(fields) return Instances(image_size, **fields) def flatten(cls, obj): (ret, schema) = super().flatten(obj.get_fields()) size = o...
class ConvTemporalGraphical(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, t_kernel_size=1, t_stride=1, t_padding=0, t_dilation=1, bias=True): super().__init__() self.kernel_size = kernel_size self.conv = nn.Conv2d(in_channels, (out_channels * kernel_size), kernel_siz...
_quantizer(quantization_target=QuantizationTarget.Activation, quantization_method=[QuantizationMethod.POWER_OF_TWO, QuantizationMethod.SYMMETRIC], identifier=TrainingMethod.STE) class STEActivationQATQuantizer(BaseKerasQATTrainableQuantizer): def __init__(self, quantization_config: TrainableQuantizerActivationConfi...
def get_nonzero_len_instance_inds_by_class(data_filename): class_inds_dict = {} instance_ind = 0 with open(data_filename, 'r') as f: first_line = True for line in f: if first_line: temp_line = line category_ind = 0 while (not (temp_...
def test_process_text(): result = process_text(words, tags) lemma = [x.lemma for x in result.words] print(lemma) assert (lemma == expected)
_sentencepiece _tokenizers class XLNetTokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = XLNetTokenizer rust_tokenizer_class = XLNetTokenizerFast test_rust_tokenizer = True test_sentencepiece = True def setUp(self): super().setUp() tokenizer = XLNetTokenizer...
def SubstituteTemplate(template, values): text = template changed = True while changed: changed = False for (key, value) in values.items(): regex = ('\\$\\{%s\\}' % key) newtext = re.sub(regex, value, text) if (newtext != text): changed = T...
def get_edge_label(dataset, current, horizon, mode): if (mode == 'before'): edge_label = torch.cat([dataset[(current + i)].edge_label for i in range(1, (horizon + 1))], dim=0) edge_label_index = torch.cat([dataset[(current + i)].edge_label_index for i in range(1, (horizon + 1))], dim=1) elif (mo...
def yawVsPowerContour(yws, ws, ti, xs, ys, res=30, saveas=None): from mpl_toolkits import mplot3d x = np.linspace(0, res, res) y = np.linspace(0, res, res) (X, Y) = np.meshgrid(x, y) powerNeural = np.zeros((res, res)) powerFloris = np.zeros((res, res)) cnt = 0 for i in range(res): ...
def interpolate_data_grad_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, output_size, mode, align_corners=True, half_pixel=False, half_pixel_for_nn=False, channel_last=False): gdx = grad_inputs[0] gdy = F.interpolate(gdx, None, output_size, mode, align_corners, half_pixel, half_pixel_for_nn...
class VoxelGenerator(): def __init__(self, voxel_size, point_cloud_range, max_num_points, max_voxels=20000): point_cloud_range = np.array(point_cloud_range, dtype=np.float32) voxel_size = np.array(voxel_size, dtype=np.float32) grid_size = ((point_cloud_range[3:] - point_cloud_range[:3]) / vo...
def idx_for_value(value: Union[(int, float, complex)], param_vals: ndarray) -> int: location = int(np.abs((param_vals - value)).argmin()) selected_value = param_vals[location] if cmath.isclose(param_vals[location], value): return location if (not settings.FUZZY_SLICING): raise ValueError...
def test_clean_up(digraph_multiple_roots): digraph_multiple_roots._clean_up() with pytest.raises(AttributeError): assert (digraph_multiple_roots.X_ is None) with pytest.raises(AttributeError): assert (digraph_multiple_roots.y_ is None)
class Ui_Form(object): def setupUi(self, Form): Form.setObjectName('Form') Form.resize(1800, 660) self.pushButton = QtWidgets.QPushButton(Form) self.pushButton.setGeometry(QtCore.QRect(1160, 360, 81, 27)) self.pushButton.setObjectName('pushButton') self.pushButton_2 =...
def test_should_explain_output(convolutional_model, random_data, mocker): mocker.patch('tf_explain.core.smoothgrad.grid_display', side_effect=(lambda x: x)) (images, labels) = random_data explainer = SmoothGrad() grid = explainer.explain((images, labels), convolutional_model, 0) assert (grid.shape =...
def read_tfrecord(example): features = {'image': tf.io.FixedLenFeature([], tf.string), 'class': tf.io.FixedLenFeature([], tf.int64), 'one_hot_class': tf.io.VarLenFeature(tf.float32)} example = tf.io.parse_single_example(example, features) image = tf.image.decode_jpeg(example['image'], channels=3) image ...
def create_model(hparams, model, length=22): train_graph = tf.Graph() with train_graph.as_default(): train_model = model(hparams, tf.contrib.learn.ModeKeys.TRAIN) eval_graph = tf.Graph() with eval_graph.as_default(): eval_model = model(hparams, tf.contrib.learn.ModeKeys.EVAL) infer_g...
def sample_elite_steps(dataset: Dict[(str, np.ndarray)], elite_property: str='length', elite_traj_fraction: float=0.2, elite_step_fraction: float=0.2, samples: int=200, reverse: bool=False) -> Tuple[(np.ndarray, np.ndarary)]: (starts, ends, lengths) = util.extract_traj_markers(dataset) if (elite_property == 'le...
def is_explicitly_view_dependent(df): target_words = {'front', 'behind', 'back', 'right', 'left', 'facing', 'leftmost', 'rightmost', 'looking', 'across'} return df.tokens.apply((lambda x: (len(set(x).intersection(target_words)) > 0)))
class open_index_h5(object): def __init__(self, f_name, mode, num_points_per_sample=None): self.f_name = f_name self.mode = mode self.num_points_per_sample = num_points_per_sample self.saver = None def __enter__(self): if (not (isinstance(self.f_name, str) or isinstance(s...
def check_fft_version(): if (version.parse(torch.__version__) >= version.parse('1.7')): if ('torch.fft' not in sys.modules): raise RuntimeError('torch.fft module available but not imported')
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)) if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')): (model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: (model_args, data_arg...
def test_control_cg_pr_multiple(state_forms, bcs_list, J, states, controls, adjoints, config_ocp): config_ocp.set('AlgoCG', 'cg_method', 'PR') ocp = cashocs.OptimalControlProblem(state_forms, bcs_list, J, states, controls, adjoints, config=config_ocp) ocp.solve(algorithm='ncg', rtol=0.01, atol=0.0, max_iter...
class BaseProfilerTrainer(): def __init__(self, config, model, train_loader, test_loader=None, device=None): self.config = config if (device is None): device = (torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')) self.device = device self.model = m...
_utils.test(require=ti.extension.assertion, debug=True, gdb_trigger=False) def test_assert_ok(): def func(): x = 20 assert (10 <= x <= 20) func()
class MLP(nn.Module): def __init__(self, in_channels, out_channels, activation='relu', dropout=0): super().__init__() channels = ([in_channels] + out_channels) self.layers = nn.ModuleList() for i in range(1, len(channels)): if (dropout > 0.001): self.layer...
def multiple_inputs_outputs_resblock(x, maps, kernel=(3, 3), pad=(1, 1), stride=(1, 1), w_bias=False, test=False, name='mo-convblock'): h = x with nn.parameter_scope(name): h = PF.convolution(h, maps, kernel=kernel, pad=pad, stride=stride, with_bias=w_bias) h = PF.batch_normalization(h, axes=[1]...
def print_results(query, results, top_k): print(f'''Query: "{query}" ''') print(f'Top {top_k} most similar sentences in the corpus to the query (smallest score is most similar):') for i in range(top_k): print(f""" - {(i + 1)}: "{results['text'][i]}" with a similarity score of {top_k_results['score']...
class RandomLightTorsoHalfCheetah(RoboschoolXMLModifierMixin, ModifiableRoboschoolHalfCheetah): def randomize_mass(self): self.density = uniform_exclude_inner(self.np_random.uniform, self.EXTREME_LOWER_DENSITY, self.EXTREME_UPPER_DENSITY, self.RANDOM_LOWER_DENSITY, self.RANDOM_UPPER_DENSITY) with se...
_utils.test(arch=[ti.cpu, ti.cuda, ti.vulkan], exclude=[vk_on_mac], debug=True) def test_print_i64(): def func(i: ti.i64): print('i =', i) func(((- (2 ** 63)) + (2 ** 31))) ti.sync()
def raw_parse_dir(exps_path, prefix='predicts'): exps_path = Path(exps_path) glob_exp = '**/' if (prefix == 'predicts'): glob_file = 'predicts_*.tsv' elif (prefix == 'metrics'): glob_file = 'metrics_*.csv' else: raise ValueError(f"Get prefix = {prefix}, supports only ['predic...
.parametrize('att_layer_num,dnn_hidden_units,sparse_feature_num', [(1, (), 1), (1, (4,), 1)]) def test_AutoInt(att_layer_num, dnn_hidden_units, sparse_feature_num): if ((version.parse(tf.__version__) >= version.parse('1.14.0')) and (len(dnn_hidden_units) == 0)): return model_name = 'AutoInt' sample_...
class ThreadedWSGIServer(ThreadingMixIn, BaseWSGIServer): multithread = True daemon_threads = True
def test_construct_mean_function_Linear(): (num_data, input_dim, output_dim) = (11, 5, 7) X = np.random.randn(num_data, input_dim) mean_functions = construct_mean_function(X, input_dim, output_dim) assert isinstance(mean_functions, gpflow.mean_functions.Linear)
((device_cc() < 80), 'Device compute capability is insufficient for SM80 tests.') class Conv2dDgradImplicitGemmTF32nhwcTF32nhwcTF32nhwcTensorOpF32SM80(unittest.TestCase): def test_SM80_Device_Conv2d_Dgrad_Analytic_ImplicitGemm_tf32nhwc_tf32nhwc_f32nhwc_tensor_op_f32(self): math_inst = MathInstruction(instru...
def build_trainer(wordvec_pretrain_file, *args, treebank=TREEBANK): train_trees = tree_reader.read_trees(treebank) dev_trees = train_trees[(- 1):] silver_trees = [] args = (['--wordvec_pretrain_file', wordvec_pretrain_file] + list(args)) args = constituency_parser.parse_args(args) foundation_cac...
class VAE(PyTorchModule): def __init__(self, representation_size, input_size, hidden_sizes=list([64, 128, 64]), init_w=0.001, hidden_init=ptu.fanin_init, output_activation=identity, output_scale=1, layer_norm=False, normalize=True, train_data_mean=None, train_data_std=None, **kwargs): self.save_init_params(...
def _test_pow_float_base_int_exp(dt_base, dt_exp): z = ti.field(dt_base, shape=()) def func(x: dt_base, y: dt_exp): z[None] = (x ** y) for x in [(- 6.66), (- 2), (- 1.5), (- 1), (- 0.5), 0.5, 1, 1.5, 2, 6.66]: for y in range((- 10), 10): func(x, y) assert (z[None] == ...
def eval_list_fname(real_graph_filename, pred_graphs_filename, baselines, eval_every, epoch_range=None, out_file_prefix=None): if (out_file_prefix is not None): out_files = {'train': open((out_file_prefix + '_train.txt'), 'w+'), 'compare': open((out_file_prefix + '_compare.txt'), 'w+')} out_files['train...
def process_(original, input_, past_=False, kg_type='atomic'): original = nltk.tokenize.sent_tokenize(original) if (len(original) < 5): original = [(l + '.') for l in ' '.join(original).split('.')] saved = {} for sent in input_: if (not check_empty(sent[1])): sent_id = sent[0...
def _is_equivalent(first: data.Data, second: data.Data): if (not first.is_equivalent(second)): if any((((not isinstance(d, data.Scalar)) and (not (isinstance(d, data.Array) and (d.shape == (1,))))) for d in (first, second))): return False return True
def benchmark_to_markdown(benchmark: List[List[str]], columns: List[str], rows: List[str]): cell_width = max([len(x) for x in benchmark[0]]) fmt = ('{: >%d} ' % cell_width) out = ((('| ' + fmt.format('|')) + '| '.join([fmt.format(x) for x in columns])) + '|\n') sep = (('|:' + (cell_width * '-')) + ':'...
class SST(ClassificationTask): def __init__(self, config: configure_finetuning.FinetuningConfig, tokenizer): super(SST, self).__init__(config, 'sst', tokenizer, ['0', '1']) def _create_examples(self, lines, split): if ('test' in split): return self._load_glue(lines, split, 1, None, N...
def simGetOrientationOnPath(pathHandle, relativeDistance): orientation = ffi.new('float[3]') ret = lib.simGetOrientationOnPath(pathHandle, relativeDistance, orientation) _check_return(ret) return list(orientation)
class HTMLBinaryInputStream(HTMLUnicodeInputStream): def __init__(self, source, override_encoding=None, transport_encoding=None, same_origin_parent_encoding=None, likely_encoding=None, default_encoding='windows-1252', useChardet=True): self.rawStream = self.openStream(source) HTMLUnicodeInputStream....
def _should_count_towards_stop(event: events.ExecutionEvent) -> bool: return (isinstance(event, events.AfterExecution) and (event.status in (Status.error, Status.failure)))
def multiply(X: dace.float64[N], Y: dace.float64[N], Z: dace.float64[N]): (_[0:N]) def mult(i): (x << X[i]) (y << Y[i]) (z >> Z[i]) z = (y * x)
def print_net(model, namescope='gpu_0'): logger.info('Printing model: {}'.format(model.net.Name())) op_list = model.net.Proto().op for op in op_list: input_name = op.input output_name = str(op.output[0]) op_type = op.type op_name = op.name if ((namescope is None) or o...
class BitMaskTestSuite(unittest.TestCase): def test_set_with_mask(self): mask = 15 newval = 10 baseval = 207 self.assertEqual(util.setWithMask(baseval, newval, mask), 202, 'Problems keeping other bits untouched?') mask = 240 newval = 10 baseval = 252 s...
def octave_console(): from sage.repl.rich_output.display_manager import get_display_manager if (not get_display_manager().is_in_terminal()): raise RuntimeError('Can use the console only in the terminal. Try %%octave magics instead.') os.system('octave-cli')
def CalculateComposition(ProteinSequence, AAProperty, AAPName): TProteinSequence = StringtoNum(ProteinSequence, AAProperty) Result = {} Num = len(TProteinSequence) Result[((AAPName + 'C') + '1')] = round((float(TProteinSequence.count('1')) / Num), 3) Result[((AAPName + 'C') + '2')] = round((float(TP...
def test_bitmasked(): array = ak.Array(ak.contents.BitMaskedArray(ak.index.IndexU8(np.array([0, 1, 0, 1], dtype=np.int64)), tuple, valid_when=True, length=4, lsb_order=True)) assert ak.is_tuple(array) array = ak.Array(ak.contents.BitMaskedArray(ak.index.IndexU8(np.array([0, 1, 0, 1], dtype=np.int64)), recor...
def complete_episode_error_info(history, episode, dialog_error, ner_errors, customer_entities, target_intent, intent_success, classified_intent, error='Other_error'): if ('ner_errors' in dialog_error): error_message = '{}>>> {} >>> ({})'.format(episode['episode'], episode['error_turn'], dialog_error['error_...
def app(database): settings = {} with st.sidebar: (row0_1, row0_spacer1, row0_2) = st.columns((6.0, 0.05, 4.3)) with row0_1: bot_platform = st.selectbox('Bot Platform', ['Einstein Bot', 'DialogFlow CX']) bot_platform = bot_platform.replace(' ', '_') with row0_2: ...
def retrieve_tigge_data(): date1 = [(str(i) + '-01-01') for i in xrange(2007, 2017)] date2 = [(str(i) + '-12-31') for i in xrange(2007, 2017)] dates = date1 for j in range(0, 10): dates[j] = ((date1[j] + '/to/') + date2[j]) data_dir = '/media/sebastian/Elements/Postproc_NN/data/forecasts/' ...
_bpe('bert') class BertBPE(object): def add_args(parser): parser.add_argument('--bpe-cased', action='store_true', help='set for cased BPE', default=False) parser.add_argument('--bpe-vocab-file', type=str, help='bpe vocab file.') def __init__(self, args): try: from transformer...
def make_model(config): body_config = config['body'] fpn_config = config['fpn'] rpn_config = config['rpn'] roi_config = config['roi'] sem_config = config['sem'] general_config = config['general'] classes = {'total': (int(general_config['num_things']) + int(general_config['num_stuff'])), 'stu...
def clean_pl_regon(df: Union[(pd.DataFrame, dd.DataFrame)], column: str, output_format: str='standard', inplace: bool=False, errors: str='coerce', progress: bool=True) -> pd.DataFrame: if (output_format not in {'compact', 'standard'}): raise ValueError(f'output_format {output_format} is invalid. It needs to...
class QuoteStack(): def __init__(self): self._stack = [] self._single_quote_safe = True self._double_quote_safe = True def __len__(self): return len(self._stack) def __repr__(self): return repr(self._stack) def peek(self): return (self._stack[(- 1)] if sel...
def main(): args = parser.parse_args() all_models = list_models(pretrained=True) if (args.model == 'all'): for model_name in all_models: export_model(model_name, args.output) else: export_model(args.model, args.output)
.parametrize('seed', [412]) .parametrize('batch_size', [2, 16]) .parametrize('grid_size', [2, 8]) .parametrize('feature_size', [4]) .parametrize('m, M', [((- 1.0), 1.0)]) def test_query_on_triplane_double_backward(seed, batch_size, grid_size, feature_size, m, M): nn.clear_parameters() ctx = get_extension_contex...
_task('language_modeling') class LanguageModelingTask(FairseqTask): def add_args(parser): parser.add_argument('data', help='path to data directory') parser.add_argument('--sample-break-mode', choices=['none', 'complete', 'eos'], help='If omitted or "none", fills each sample with tokens-per-sample to...
class ValidationError(ValueError): def __init__(self, message='', *args, **kwargs): ValueError.__init__(self, message, *args, **kwargs)
def discrete_to_box_wrapper(env, bound=4.0): assert isinstance(env.action_space, Discrete), 'must pass a discrete environment!' old_step = env.step n = env.action_space.n env.action_space = Box(low=(- bound), high=bound, shape=(n,)) def step(action): action = np.clip(action, (- bound), bound...
class sCW_sBC_reg(atomic_reg): OP_NAME = 'sCW&sBC' _fields_ = [('cmd_short', ctypes.c_uint64, 1), ('op_code', ctypes.c_uint64, 16), ('cmd_id_dep', ctypes.c_uint64, 24), ('tsk_typ', ctypes.c_uint64, 4), ('tsk_eu_typ', ctypes.c_uint64, 5), ('opt_res0_prec', ctypes.c_uint64, 3), ('rsvd0', ctypes.c_uint64, 6), ('pw...
def draw_arc(image, arc, offset=(0, 0), color=(0, 0, 255), thickness=1): caa = ((cartesian_angle(arc.circle.center, arc.a) * 180) / np.pi) cab = ((cartesian_angle(arc.circle.center, arc.b) * 180) / np.pi) if (caa > cab): caa -= 360 center = tuple(round_vector((np.array(arc.circle.center) + offse...
class SahaFactor(ProcessingPlasmaProperty): outputs = ('phi_ik',) latex_name = ('\\Phi_{i,\\kappa}',) def calculate(self, thermal_phi_lte, thermal_lte_level_boltzmann_factor, thermal_lte_partition_function): boltzmann_factor = self._prepare_boltzmann_factor(thermal_lte_level_boltzmann_factor) ...
def get_actions_learned(pred_mentions, gt_clusters, max_ents): pred_mentions = [tuple(mention) for mention in pred_mentions] mention_to_cluster = get_mention_to_cluster_idx(gt_clusters) actions = [] cell_to_cluster = {} cell_to_last_used = [0 for cell in range(max_ents)] cluster_to_cell = {} ...
def cache_url(url, model_dir=None, progress=True): if (model_dir is None): torch_home = os.path.expanduser(os.getenv('TORCH_HOME', '~/.torch')) model_dir = os.getenv('TORCH_MODEL_ZOO', os.path.join(torch_home, 'models')) if (not os.path.exists(model_dir)): os.makedirs(model_dir) part...
def get_graph(text, language='english'): sentences = _clean_text_by_sentences(text, language) graph = _build_graph([sentence.token for sentence in sentences]) _set_graph_edge_weights(graph) return graph