code
stringlengths
101
5.91M
class Iron(ConsumedResource): def __init__(self, *args, **kwargs): super().__init__('Iron', *args, **kwargs)
def test_case46(): url = (discoveryIp + '/ngsi9/ngsi-ld/registration/urn:ngsi-ld:Vehicle:C001') r = requests.get(url) resp_content = r.content resInJson = resp_content.decode('utf8').replace("'", '"') resp = json.loads(resInJson) if (resp['ID'] == 'urn:ngsi-ld:Vehicle:C001'): print('\nVa...
class ConcatenationAggregator(Layer): def __init__(self, input_dim, output_dim, review_item_adj, review_user_adj, review_vecs, user_vecs, item_vecs, dropout=0.0, act=tf.nn.relu, name=None, concat=False, **kwargs): super(ConcatenationAggregator, self).__init__(**kwargs) self.review_item_adj = review_...
.parametrize('n_rounds, n_actions, dim_context, base_model_for_evaluation_policy, base_model_for_reg_model', offline_experiment_configurations) def test_offline_policy_learner_performance(n_rounds: int, n_actions: int, dim_context: int, base_model_for_evaluation_policy: str, base_model_for_reg_model: str) -> None: ...
def patch_nonscriptable_classes(): from detectron2.modeling.backbone import ResNet, FPN def prepare_resnet(self): ret = deepcopy(self) ret.stages = nn.ModuleList(ret.stages) for k in self.stage_names: delattr(ret, k) return ret ResNet.__prepare_scriptable__ = prep...
class ParallelScheduler(RunScheduler): def __init__(self, executor, seq_scheduler_class, ui, print_execution_plan): RunScheduler.__init__(self, executor, ui, print_execution_plan) self._seq_scheduler_class = seq_scheduler_class self._lock = RLock() self._num_worker_threads = self._nu...
def train_epoch(model, tokenizer, optimizer, scheduler, train_dataloader, tr_loss, logging_loss, global_step, steps_trained_in_current_epoch, tb_writer, best_dev_perp, args): if args.fp16: try: from apex import amp except ImportError: raise ImportError('Please install apex fr...
def eval_group(pred, label): pred_cols = [unit[1] for unit in pred['groupBy']] label_cols = [unit[1] for unit in label['groupBy']] pred_total = len(pred_cols) label_total = len(label_cols) cnt = 0 pred_cols = [(pred.split('.')[1] if ('.' in pred) else pred) for pred in pred_cols] label_cols ...
def unfold_segments(tensor, tgt_dur, sample_rate=16000): seg_len = int((tgt_dur * sample_rate)) src_len = len(tensor) hop_len = (seg_len // 4) tgt_len = (seg_len if (src_len <= seg_len) else (((src_len // hop_len) + 1) * hop_len)) pad_len = (tgt_len - src_len) front_pad_len = random.randint(0, p...
class PascalVOCDataset(torch.utils.data.Dataset): CLASSES = ('__background__ ', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor') def __init__(self, data_dir, split, u...
def check_task(task: str) -> Tuple[(Dict, Any)]: if (task in TASK_ALIASES): task = TASK_ALIASES[task] if (task in SUPPORTED_TASKS): targeted_task = SUPPORTED_TASKS[task] return (targeted_task, None) if task.startswith('translation'): tokens = task.split('_') if ((len(...
def test_MIMO_pipeline(): from speechbrain.utils.data_pipeline import DataPipeline, takes, provides ('text', 'other-text') ('reversed', 'concat') def text_pipeline(text, other): return (text[::(- 1)], (text + other)) ('reversed', 'concat') ('reversed_twice', 'double_concat') def seco...
def get_layer_id_for_vit(name, num_layers): if (name in ['cls_token', 'pos_embed']): return 0 elif name.startswith('patch_embed'): return 0 elif name.startswith('blocks'): return (int(name.split('.')[1]) + 1) else: return num_layers
class CorrelationFunction(Function): def forward(ctx, input1, input2, pad_size=3, kernel_size=3, max_displacement=20, stride1=1, stride2=2, corr_multiply=1): ctx.save_for_backward(input1, input2) ctx.pad_size = pad_size ctx.kernel_size = kernel_size ctx.max_displacement = max_displac...
def parse_file(task_name, log_dir, foldername): try: lines = result_parser_utils.read_rank0_lines(log_dir, foldername) return ((float(lines[5].split()[2]) / 1000) / 1000) except Exception: return None
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer=nn.BatchNorm2d): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = norm_layer(planes) self.relu = nn.ReLU(inplace=True)...
def strip_over_cont(text): sents = [] skip = False for line in text.split('\n'): if (line.strip() == '(Over)'): skip = True elif (line.strip() == '(Cont)'): skip = False continue if (not skip): sents.append(line) text = '\n'.join(se...
def k2s_matrix(kmatrix): dimensions = __array_dimensions__(kmatrix).python() kmatrix_list = __make_array_to_lists__(kmatrix).python() return matrix(dimensions[0], dimensions[1], kmatrix_list)
class CppInclude(object): def __init__(self, member=None, std=None, prefix=None): assert (member or std) self.member = member self.std = std self.prefix = prefix def relative_path(self): if self.std: return self.std return '{}.hpp'.format(os.path.join(...
def _spanning_type(type1, type2): if (type1.is_numeric and type2.is_numeric): return widest_numeric_type(type1, type2) elif (type1.is_builtin_type and (type1.name == 'float') and type2.is_numeric): return widest_numeric_type(c_double_type, type2) elif (type2.is_builtin_type and (type2.name =...
def create_banner(app): return html.Div(id='banner', className='banner', children=[html.Img(src=app.get_asset_url('logo_small.png')), html.Plaintext(' Powered by Salesforce AI Research')])
class JsonProgressBar(BaseProgressBar): def __init__(self, iterable, epoch=None, prefix=None, log_interval=1000): super().__init__(iterable, epoch, prefix) self.log_interval = log_interval self.i = None self.size = None def __iter__(self): self.size = len(self.iterable) ...
def _cycliclrloader(obj, path, end_of_epoch, device=None): del end_of_epoch state_dict = torch.load(path, map_location=device) if (state_dict.get('_scale_fn_ref') == WEAKREF_MARKER): if (not isinstance(obj._scale_fn_ref, weakref.WeakMethod)): MSG = 'Loading CyclicLR scheduler and the _sc...
class DoubleConv(nn.Module): def __init__(self, in_ch, out_ch): super(DoubleConv, self).__init__() self.in_ch = in_ch self.out_ch = out_ch self.conv = nn.Sequential(nn.Conv2d(in_ch, out_ch, 3, padding=1), nn.BatchNorm2d(out_ch), nn.ReLU(inplace=True), nn.Conv2d(out_ch, out_ch, 3, pad...
def copy_geometric_data(graph): (node_attr, edge_index, edge_attr, global_attr) = decompose_graph(graph) ret = Data(x=node_attr, edge_index=edge_index, edge_attr=edge_attr) ret.global_attr = global_attr return ret
class ChromosomeOutputVariableFactory(Generic[T], metaclass=ABCMeta): def __init__(self, variable: RuntimeVariable) -> None: self._variable = variable def get_data(self, individual: chrom.Chromosome) -> T: def get_variable(self, individual: chrom.Chromosome) -> sb.OutputVariable[T]: return s...
class MobileViTForImageClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def load_combined_train_data_woc(output_path: str): return (torch.cat((load_data_tensors_TW(join(output_path, 'vectors', 'train', 'identifiers_param_train_datapoints_x.npy')), load_data_tensors_TW(join(output_path, 'vectors', 'train', 'identifiers_ret_train_datapoints_x.npy')), load_data_tensors_TW(join(output_path...
def init(): a = [] for i in np.linspace(0, 1, n, False): for j in np.linspace(0, 1, n, False): a.append([i, j]) return np.array(a).astype(np.float32)
def kl_check(loader, model, device): (total, num_samples) = (0, 0) criterion = nn.KLDivLoss(reduction='sum') sm = nn.Softmax(dim=1) model.eval() with torch.no_grad(): for (images, labels, confs) in loader: (images, labels, confs) = (images.to(device), labels.to(device), confs.to(...
def __getattr__(name): return _sub_module_deprecation(sub_package='optimize', module='zeros', private_modules=['_zeros_py'], all=__all__, attribute=name)
class CocoDistEvalmAPHook(DistEvalHook): def evaluate(self, runner, results): tmp_file = osp.join(runner.work_dir, 'temp_0') result_files = results2json(self.dataset, results, tmp_file) res_types = (['bbox', 'segm'] if runner.model.module.with_mask else ['bbox']) cocoGt = self.datase...
def describe_token_expr(expr): if (':' in expr): (type, value) = expr.split(':', 1) if (type == TOKEN_NAME): return value else: type = expr return _describe_token_type(type)
def get_grad_norm_(parameters, norm_type: float=2.0) -> torch.Tensor: if isinstance(parameters, torch.Tensor): parameters = [parameters] parameters = [p for p in parameters if (p.grad is not None)] norm_type = float(norm_type) if (len(parameters) == 0): return torch.tensor(0.0) devic...
def get_reversed_add_exprs(expr: Expression, simplifier: LeanExprSimplifier) -> List[Tuple[(str, str)]]: if (isinstance(expr, ExprNeg) or isinstance(expr, ExprParentheses)): return get_reversed_add_exprs(expr.val, simplifier) if isinstance(expr, ExprCast): return get_reversed_add_exprs(expr.expr...
def sparse_categorical_crossentropy(y_true, y_pred): return K.sparse_categorical_crossentropy(y_true, y_pred)
def create_nmslib_index_instance(params: NmslibHnswParam): index = nmslib.init(method=params.method, space=params.space, data_type=nmslib.DataType.SPARSE_VECTOR) return index
class LinearAttention(nn.Module): def __init__(self, in_dim=300, mem_dim=300): super().__init__() self.linear = nn.Linear(in_dim, mem_dim) self.fc = nn.Linear((mem_dim * 2), 1) self.leakyrelu = nn.LeakyReLU(0.01) def forward(self, feature, aspect_v, dmask): Q = self.linea...
_tf class TFXLNetModelTest(TFModelTesterMixin, unittest.TestCase): all_model_classes = ((TFXLNetModel, TFXLNetLMHeadModel, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetForQuestionAnsweringSimple) if is_tf_available() else ()) test_pruning = False class TFXLNetModelTester(object): ...
def CLRNet50(input_shape, classes): return CLRNet(input_shape, classes, bottleneck, repetitions=[3, 4, 6, 3])
def _expand_onehot_labels(labels, label_weights, label_channels, ignore_index): bin_labels = labels.new_full((labels.size(0), label_channels), 0) valid_mask = ((labels >= 0) & (labels != ignore_index)) inds = torch.nonzero((valid_mask & (labels < label_channels)), as_tuple=False) if (inds.numel() > 0): ...
def validate_address_sdtypes(column_metadata, column_names): valid_sdtypes = ('country_code', 'administrative_unit', 'city', 'postcode', 'street_address', 'secondary_address', 'state', 'state_abbr') bad_columns = [] for column_name in column_names: if (column_name not in column_metadata): ...
def set_template(template, cfg): if ('srwarp-all' in template): cfg.model = 'srwarp.baseline' cfg.residual = True cfg.kernel_size_up = 3 cfg.kernel_net = True cfg.kernel_net_multi = True cfg.kernel_depthwise = True if ('down' in template): cfg.scale = 2 ...
class TestThread(object): def setup(self): self.seeds = range(4) def check_function(self, function, sz): from threading import Thread out1 = np.empty(((len(self.seeds),) + sz)) out2 = np.empty(((len(self.seeds),) + sz)) t = [Thread(target=function, args=(random.RandomStat...
def pipeline_archetype9(): ink_phase = [Letterpress(n_samples=(200, 300), n_clusters=(500, 680), std_range=(2500, 2500), value_range=(245, 255), value_threshold_range=(128, 128), blur=0), Geometric(scale=(2, 2), randomize=0), Faxify(scale_range=(1.0, 1.0), monochrome=1, monochrome_method='threshold_otsu', halftone=...
class RandomShortPendulum(ModifiablePendulumEnv): def __init__(self): super(RandomShortPendulum, self).__init__() self.length = uniform_exclude_inner(self.np_random.uniform, self.EXTREME_LOWER_LENGTH, self.EXTREME_UPPER_LENGTH, self.RANDOM_LOWER_LENGTH, self.RANDOM_UPPER_LENGTH) def reset(self, ...
def generate_anno(anno_dir, anno_id, split): anno_path_tmp = os.path.join(anno_dir, (anno_id + '_{}.txt')) anno_cls_path_tmp = os.path.join(txt_dir_voc2007, '{}_{}.txt') count = 0 annotations = [] for category in tqdm(categories_list): anno_path = anno_path_tmp.format(category['name']) ...
def gen_logger(name, file=None, copy_root=True, propagate=False): logger = logging.getLogger(name) logger.propagate = propagate if (file is not None): __add_file_handler(logger, file) if copy_root: for hdl in LOG.handlers: logger.addHandler(hdl) return logger
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(BasicBlock, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d if ((groups != 1) or (base...
def load_data(ds_dir, batch_size, n_cpu, cut_len): torchaudio.set_audio_backend('sox_io') train_dir = os.path.join(ds_dir, 'train') test_dir = os.path.join(ds_dir, 'test') train_ds = DemandDataset(train_dir, cut_len) test_ds = DemandDataset(test_dir, cut_len) train_dataset = torch.utils.data.Dat...
class AdobeDataset(data.Dataset): def __init__(self, opt): super(AdobeDataset, self).__init__() self.opt = opt self.interval_list = opt['interval_list'] self.random_reverse = opt['random_reverse'] logger.info('Temporal augmentation interval list: [{}], with random reverse is ...
def _seg_17(): return [(7737, 'V'), (7738, 'M', u'l'), (7739, 'V'), (7740, 'M', u'l'), (7741, 'V'), (7742, 'M', u'm'), (7743, 'V'), (7744, 'M', u'm'), (7745, 'V'), (7746, 'M', u'm'), (7747, 'V'), (7748, 'M', u'n'), (7749, 'V'), (7750, 'M', u'n'), (7751, 'V'), (7752, 'M', u'n'), (7753, 'V'), (7754, 'M', u'n'), (7755...
class attentionNet(nn.Module): def __init__(self, squeezeFilters=32, expandFilters=64, scailingFactor=2, numAttentionBlock=10): super(attentionNet, self).__init__() self.inputConv = nn.Conv2d(3, squeezeFilters, 3, 1, 1) self.inputConv_bn = nn.BatchNorm2d(squeezeFilters) self.featureA...
.parametrize('seed', [313]) .parametrize('shape_a, shape_b', [((), ()), ((), (2, 2, 2)), ((2, 2, 2), ())]) def test_backward_dot_have_scalar(seed, shape_a, shape_b): rng = np.random.RandomState(seed) inputs = [] func_args = [] if (not shape_a): a = rng.randn() func_args += [a] else: ...
def test_persistDockerImage1(): designerUrl = (designerIp + '/dockerimage') headers = {'Content-Type': 'application/json'} r = requests.post(designerUrl, data=json.dumps(data.test200), headers=headers) assert (r.status_code == 200)
def ref_grad_binary_tanh(x, dy, **kw): return (dy * (1 - np.floor(np.minimum(np.abs(x), 1)))).flatten()
def test_fv_e2e(): dim = 128 num_modes = 8 expected_dim = (((2 * num_modes) * dim) + num_modes) descriptors = [np.random.random((np.random.randint(5, 30), dim)) for _ in range(10)] gmm = learn_gmm(descriptors, n_modes=num_modes) fisher_vec = fisher_vector(descriptors[0], gmm) assert (len(fis...
def test_iterate_seqs_no_chunking_1(): dataset = DummyDataset(input_dim=2, output_dim=3, num_seqs=2, seq_len=11) dataset.chunk_step = 0 dataset.chunk_size = 0 dataset.init_seq_order(1) seqs = list(dataset.iterate_seqs()) assert_equal(len(seqs), 2) assert_equal(seqs[0], (0, 0, 11)) assert...
def _run_selection(args, data): res = [] for partition in data: (assignments, shard_names, filenames, clustering_types) = partition samples_list = run_greedy(args, assignments, shard_names, filenames, clustering_types, args.subset.size, args.subset.ratio, measure_name=args.measure_name, cluster_...
class CIFAR10(Dataset): def __init__(self, path): self.cifar10 = datasets.CIFAR10(root=path, download=True, train=True, transform=cifar10_transformer()) def __getitem__(self, index): if isinstance(index, numpy.float64): index = index.astype(numpy.int64) (data, target) = self....
def predict(): args = get_args() kwargs = args.__dict__ save_dir = kwargs['save_dir'] common.setup_logger(save_dir, log_name='inten_pred.log', debug=kwargs['debug']) pl.utilities.seed.seed_everything(kwargs.get('seed')) yaml_args = yaml.dump(kwargs) logging.info(f''' {yaml_args}''') with...
class Refiner(): def __init__(self, prompt, args): self.prompt = prompt self.temperature = args.temperature self.top_p = args.top_p def set_refinement_fields(self, object_dlg_history: List[DialogueTurn], new_dlg_turn: DialogueTurn, engine_dict): prompt_output = llm_generate(templ...
def get_op_loc(op): if isinstance(op, (OpView, Operation)): res = str(op.location).replace('loc(', '').strip(')') if ('fused' in res): res = match_fused_loc.search(res).group(1) return escape(res) elif isinstance(op, Value): return get_op_loc(op.owner) raise NotIm...
class SentenceTerScorer(Scorer): def __init__(self, argument_string): Scorer.__init__(self, argument_string='') self._reference = None self.additional_flags = argument_string def set_reference(self, reference_tokens): if hasattr(self._reference, 'extension'): self._re...
def _format_axis(fig: Figure, minv: int, maxv: int, axis: str) -> None: divisor = 4.5 if (np.isinf(minv) or np.isinf(maxv)): gap = 1.0 else: gap = ((maxv - minv) / divisor) (_, after) = f'{gap:.0e}'.split('e') round_to = ((- 1) * int(after)) minv = np.round(minv, round_to) ga...
class CSPDarknet(nn.Module): cfg = {'n': [0.33, 0.25], 't': [0.33, 0.375], 's': [0.33, 0.5], 'm': [0.67, 0.75], 'l': [1.0, 1.0], 'x': [1.33, 1.25]} def __init__(self, subtype='cspdark_s', out_channels=[64, 128, 256, 512, 1024], layers=[3, 9, 9, 3], spp_ksizes=(5, 9, 13), depthwise=False, conv_cfg=None, norm_cfg...
class idct_8x8(nn.Module): def __init__(self): super(idct_8x8, self).__init__() alpha = np.array(([(1.0 / np.sqrt(2))] + ([1] * 7))) self.alpha = nn.Parameter(torch.from_numpy(np.outer(alpha, alpha)).float()) tensor = np.zeros((8, 8, 8, 8), dtype=np.float32) for (x, y, u, v) ...
def extractIndexedLayers(sequence, x, indexes, detach): index = 0 output = [] indexes.sort() for (iSeq, layer) in enumerate(sequence): if (index >= len(indexes)): break x = layer(x) if (iSeq == indexes[index]): if detach: output.append(x.vi...
def quaternion_conv_op(input, r_weight, i_weight, j_weight, k_weight, bias, stride: int, padding: int, groups: int, dilation: int, conv1d: bool): cat_kernels_4_r = torch.cat([r_weight, (- i_weight), (- j_weight), (- k_weight)], dim=1) cat_kernels_4_i = torch.cat([i_weight, r_weight, (- k_weight), j_weight], dim...
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 image_processor_class_from_name(class_name: str): for (module_name, extractors) in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if (class_name in extractors): module_name = model_type_to_module_name(module_name) module = importlib.import_module(f'.{module_name}', 'transformers.models')...
def register_Ns3DesMetrics_methods(root_module, cls): cls.add_method('Initialize', 'void', [param('std::vector< std::string >', 'args'), param('std::string', 'outDir', default_value='""')]) cls.add_method('Trace', 'void', [param('ns3::Time const &', 'now'), param('ns3::Time const &', 'delay')]) cls.add_meth...
def run_failed_cases(fail_dir='failed'): for path in Path(fail_dir).glob('**/*'): result = run_case(path)[1] print(str(path), result)
class EGT(EGT_Base): def __init__(self, **kwargs): super().__init__(**kwargs) self.EGT_layers = nn.ModuleList([EGT_Layer(**self.layer_common_kwargs, edge_update=(not self.egt_simple)) for _ in range((self.model_height - 1))]) if ((not self.node_ended) and (not self.edge_ended)): ...
def test_malformed_quantity_error(): malformed_quantity_error = MalformedQuantityError('abcd') assert (malformed_quantity_error.malformed_quantity_string == 'abcd') assert (str(malformed_quantity_error) == 'Expecting a quantity string(e.g. "5 km/s") for keyword - supplied abcd')
class Runtime(metaclass=ABCMeta): def __init__(self) -> None: self._interrupted = False def add_run(self, run: Run) -> None: pass async def start(self) -> None: pass def interrupt_handler(self) -> None: pass def interrupt(self) -> None: if (not self._interrupt...
def pci_records(): records = [] command = shlex.split('lspci -vmm') output = subprocess.check_output(command).decode() for devices in output.strip().split('\n\n'): record = {} records.append(record) for row in devices.split('\n'): (key, value) = row.split('\t') ...
def test_code_object_executed_other_thread(): tracer = ExecutionTracer() tracer.current_thread_identifier = threading.current_thread().ident tracer.register_code_object(MagicMock()) def wrapper(*args): with pytest.raises(RuntimeError): tracer.executed_code_object(*args) thread = ...
def parallax_replica_prefix(replica_id): return ('%s%s' % (PARALLAX_REPLICA_PREFIX, str(replica_id)))
def conv_params(fn): params = fn.params.get('convolution_param', fn.params) axis = params.get('axis', 1) ks = np.array(params['kernel_size'], ndmin=1) dilation = np.array(params.get('dilation', 1), ndmin=1) assert (len(({'pad_h', 'pad_w', 'kernel_h', 'kernel_w', 'stride_h', 'stride_w'} & set(fn.para...
class CTupleBaseTypeNode(CBaseTypeNode): child_attrs = ['components'] def analyse(self, env, could_be_name=False): component_types = [] for c in self.components: type = c.analyse(env) if type.is_pyobject: error(c.pos, "Tuple types can't (yet) contain Pytho...
class MalnetDataset(Dataset): def __init__(self, args, root, files, labels, transform=None, pre_transform=None): self.args = args self.files = files self.labels = labels self.num_classes = len(np.unique(labels)) super(MalnetDataset, self).__init__(root, transform, pre_transfo...
def conjugate_gradients(Avp_f, b, nsteps, rdotr_tol=1e-10): x = zeros(b.size()) r = b.clone() p = b.clone() rdotr = torch.dot(r, r) for i in range(nsteps): Avp = Avp_f(p) alpha = (rdotr / torch.dot(p, Avp)) x += (alpha * p) r -= (alpha * Avp) new_rdotr = torch...
class Sampler(): def __init__(self, indexed_ratings, item_indices, cnn_features_path, epochs): self._indexed_ratings = indexed_ratings self._item_indices = item_indices self._users = list(self._indexed_ratings.keys()) self._nusers = len(self._users) self._items = list({k for ...
def test_RegularArray_NumpyArray(): v2a = ak.contents.regulararray.RegularArray(ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5])), 3) roundtrip(v2a) array = ak.highlevel.Array(v2a) memoryleak(array, swallow) memoryleak(array, passthrough) memoryleak(array, passthrough2)...
class DecGaussianMLPPolicy(GaussianMLPModule): def __init__(self, env_spec, hidden_sizes=(32, 32), hidden_nonlinearity=torch.tanh, hidden_w_init=nn.init.xavier_uniform_, hidden_b_init=nn.init.zeros_, output_nonlinearity=None, output_w_init=nn.init.xavier_uniform_, output_b_init=nn.init.zeros_, layer_normalization=F...
def query_ball_point(radius, nsample, xyz1, xyz2): return grouping_module.query_ball_point(xyz1, xyz2, radius, nsample)
def bar_interaction_plot(interaction_matrix, tokens, top_k=5, text_kwargs=None, pair_indices=None, zero_diagonals=True, **kwargs): if (text_kwargs is None): text_kwargs = {} if zero_diagonals: interaction_matrix = interaction_matrix.copy() np.fill_diagonal(interaction_matrix, 0.0) if...
class WnliProcessor(DataProcessor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) warnings.warn(DEPRECATION_WARNING.format('processor'), FutureWarning) def get_example_from_tensor_dict(self, tensor_dict): return InputExample(tensor_dict['idx'].numpy(), tensor_dic...
def test_special_constants(): assert (S.Zero == Integer(0)) assert (S.One == Integer(1)) assert (S.NegativeOne == Integer((- 1))) assert (S.Half == Rational(1, 2))
def densenet161_model(img_rows, img_cols, color_type=1, nb_dense_block=4, growth_rate=48, nb_filter=96, reduction=0.5, dropout_rate=0.0, weight_decay=0.0001, num_classes=None): eps = 1.1e-05 compression = (1.0 - reduction) global concat_axis if (K.image_dim_ordering() == 'tf'): concat_axis = 3 ...
def _remove_right_units(string: str) -> str: if ('\\text{ ' in string): splits = string.split('\\text{ ') assert (len(splits) == 2) return splits[0] else: return string
class MnliProcessor(DataProcessor): def get_example_from_tensor_dict(self, tensor_dict): return InputExample(tensor_dict['idx'].numpy(), tensor_dict['premise'].numpy().decode('utf-8'), tensor_dict['hypothesis'].numpy().decode('utf-8'), str(tensor_dict['label'].numpy())) def get_train_examples(self, data...
_tf _retrieval class TFRagDPRBartTest(TFRagTestMixin, unittest.TestCase): _property def config_and_inputs(self): question_encoder_tester = TFDPRModelTester(self) dpr_config_and_inputs = question_encoder_tester.prepare_config_and_inputs() generator_tester = TFBartModelTester(self) ...
class IBN(nn.Module): def __init__(self, planes): super(IBN, self).__init__() half1 = int((planes / 2)) self.half = half1 half2 = (planes - half1) self.IN = nn.InstanceNorm2d(half1, affine=True) self.BN = nn.BatchNorm2d(half2) def forward(self, x): split =...
def _cos_theta(ncut: int) -> csc_matrix: cos_op = (0.5 * (_exp_i_theta_operator(ncut) + _exp_i_theta_operator_conjugate(ncut))) return cos_op
.parametrize('ctx, func_name', ctxs) .parametrize('seed', [313]) .parametrize('inshape, kernel, outmaps, pad, stride, dilation', [((2, 2, 10), (1,), 4, (3,), (2,), (1,)), ((2, 2, 10), (3,), 2, (0,), (1,), (2,))]) .parametrize('group', [1, 2]) .parametrize('channel_last', [False, True]) .parametrize('with_bias', [True, ...
class TestDirac(unittest.TestCase): def test_dirac_property1d(self): (ni, no, k, pad) = (4, 4, 3, 1) module = DiracConv1d(in_channels=ni, out_channels=no, kernel_size=k, padding=pad, bias=False) module.alpha.data.fill_(1) module.beta.data.fill_(0) x = Variable(torch.randn(4, ...
.parametrize('traj,tolerance,output', [(trj_prob, 0.0, 1.0), (trj_prob, 1.0, (1.0 / 3.0))]) def test_location_probability_match(traj, tolerance, output): at = attacks.LocationProbabilityAttack(knowledge_length=1, tolerance=tolerance) results = [] for i in range(1, 5): results.append(at._match(single...
class IoTest(absltest.TestCase): def testProducesValidOutput(self): with tempfile.NamedTemporaryFile() as output_file: output_filename = output_file.name scorer = rouge_scorer.RougeScorer(['rouge1'], False) io.compute_scores_and_write_to_csv(test_util.TARGETS_FILE, test_u...