code
stringlengths
101
5.91M
class ResidualBlock(nn.Module): def __init__(self, dim_in, dim_out): super(ResidualBlock, self).__init__() self.main = nn.Sequential(nn.Conv2d(dim_in, dim_out, kernel_size=3, stride=1, padding=1, bias=False), nn.InstanceNorm2d(dim_out, affine=True), nn.ReLU(inplace=True), nn.Conv2d(dim_out, dim_out,...
def frame_ans(question_utter, ques_string, dialogUtterance, ans_string, wh): article = (question_utter.speaker + ' asked ') article += ques_string if wh: article += ((' and ' + dialogUtterance.speaker) + ' replied ') article += ans_string print('answer->') print(article) ...
def create_objective(sim_space: optplan.SimulationSpace) -> Tuple[(optplan.Function, List[optplan.Monitor])]: wg_source = optplan.WaveguideModeSource(center=[(- 1770), 0, 0], extents=[GRID_SPACING, 1500, 600], normal=[1, 0, 0], mode_num=0, power=1.0) overlap_1550 = optplan.WaveguideModeOverlap(center=[1730, (- ...
def test_estimate_competence_ratio_batch(): n_samples = 10 x = np.array([0, 1, 2, 3, 4, 5, 6]).reshape((- 1), 1) y = np.array([0, 0, 0, 0, 1, 1, 1]) clf1 = create_base_classifier(np.array([1, 0, 1, 0, 0, 0, 0])) clf2 = create_base_classifier(np.array([1, 0, 0, 0, 1, 0, 0])) clf3 = create_base_cl...
class Pool(multiprocessing.pool.Pool): def _setup_queues(self): self._inqueue = SimpleQueue() self._outqueue = SimpleQueue() self._quick_put = self._inqueue._writer.send self._quick_get = self._outqueue._reader.recv def _repopulate_pool(self): for i in range((self._proces...
def RandomNewmanWattsStrogatz(n, k, p, seed=None): if (seed is None): seed = int((current_randstate().long_seed() % sys.maxsize)) import networkx return Graph(networkx.newman_watts_strogatz_graph(n, k, p, seed=seed))
def _ignore_torch_cuda_oom(): try: (yield) except RuntimeError as e: if ('CUDA out of memory. ' in str(e)): pass else: raise
class FlaxBertModelTester(unittest.TestCase): def __init__(self, parent, batch_size=13, seq_length=7, is_training=True, use_attention_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37, hidden_act='gelu', hidden_dropou...
def register_Ns3GammaRandomVariable_methods(root_module, cls): cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) cls.add_constructor([]) cls.add_method('GetAlpha', 'double', [], is_const=True) cls.add_method('GetBeta', 'double', [], is_const=True) cls.add_method('GetValue', 'double', [p...
def _parent_name(target): r = target.rsplit('.', 1) if (len(r) == 1): return ('', r[0]) else: return (r[0], r[1])
def get_running_cuda_version(run_lambda): return run_and_parse_first_match(run_lambda, 'nvcc --version', 'release .+ V(.*)')
class MobileNetV2(nn.Module): def __init__(self, variant: str=None): super().__init__() self.out_indices = [3, 6, 13, 17] self.channels = [24, 32, 96, 320] input_channel = 32 inverted_residual_setting = [[1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 2], [6, 64, 4, 2], [6, 96, 3, 1...
def gamma_list_to_cyclotomic(galist): resu = defaultdict(int) for n in galist: eps = sgn(n) for d in divisors(abs(n)): resu[d] += eps return (sorted((d for d in resu for k in range(resu[d]))), sorted((d for d in resu for k in range((- resu[d])))))
def create_differentiability_info(signature, non_differentiable_arg_names, output_differentiability, autograd_fn): return {'signature': signature, 'non_differentiable_arg_names': non_differentiable_arg_names, 'output_differentiability': output_differentiability, 'autograd_fn': autograd_fn}
def resblock(x_init, channels, use_bias=True, scope='resblock'): with tf.variable_scope(scope): with tf.variable_scope('res1'): x = conv(x_init, channels, kernel=3, stride=1, pad=1, pad_type='reflect', use_bias=use_bias) x = instance_norm(x) x = relu(x) with tf.va...
def extract_tags(title: str) -> List[str]: tags: List[str] = [] for x in title.split('] ')[:(- 1)]: if (x[0] != '['): raise ValueError(f'No starting [ for tag: {x}]') tags.append(x[1:].lower()) return tags
def test_poiless_model_empty_string(backend): spec = {'channels': [{'name': 'channel', 'samples': [{'name': 'goodsample', 'data': [10.0], 'modifiers': [{'type': 'normsys', 'name': 'shape', 'data': {'hi': 0.5, 'lo': 1.5}}]}]}]} model = pyhf.Model(spec, poi_name='') data = ([12] + model.config.auxdata) py...
def main(backbone: str, checkpoint: Path, dataset: str, split: str='test', device: str='cuda', batch_size: int=128, num_workers: int=0, output_parquet: Optional[Path]=None) -> None: model = build_backbone(backbone, checkpoint, device) logger.info(f'Loaded backbone {backbone} from {checkpoint}') dataset_tran...
def test_pickle(): obj = DemoClass() s = pickle_dumps(obj.method) inst = pickle_loads(s) assert_equal(inst(), 42)
def reduce_paramsets_requirements(paramsets_requirements, paramsets_user_configs): reduced_paramsets_requirements = {} paramset_keys = ['paramset_type', 'n_parameters', 'is_scalar', 'inits', 'bounds', 'auxdata', 'factors', 'sigmas', 'fixed'] for paramset_name in list(paramsets_requirements): paramse...
def train(solver, snapshot, gpus, timing=False): uid = caffe.NCCL.new_uid() caffe.init_log() caffe.log(('Using devices %s' % str(gpus))) procs = [] for rank in range(len(gpus)): p = Process(target=solve, args=(solver, snapshot, gpus, timing, uid, rank)) p.daemon = True p.star...
def test_results(): results = glob.glob('test_predictor_outputs/X_prediction_results.csv') assert (len(results) == 1)
def image_augmentation_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, shape=None, pad=(0, 0), min_scale=1.0, max_scale=1.0, angle=0.0, aspect_ratio=1.0, distortion=0.0, flip_lr=False, flip_ud=False, brightness=0.0, brightness_each=False, contrast=1.0, contrast_center=0.0, contrast_each=False, noise...
class RGBArrayAsObservationWrapper(dm_env.Environment): '\n\tUse env.render(rgb_array) as observation\n\trather than the observation environment provides\n\n\tFrom: def __init__(self, env, ml1, width=84, height=84, max_path_length=125, camera_name='corner'): self._env = env self.ml1 = ml1 ...
def pythonify(tensor): array = tensor.numpy() if isinstance(array, np.ndarray): return array.tolist() elif isinstance(array, bytes): return array.decode() elif isinstance(array, (int, np.int32, np.int64)): return int(array) else: raise ValueError(array)
class FiniteFields(CategoryWithAxiom): def extra_super_categories(self): return [EnumeratedSets().Finite()] def __contains__(self, x): from sage.categories.fields import Fields return ((x in Fields()) and x.is_finite()) def _call_(self, x): raise TypeError(('unable to canonic...
def make_sdfg(implementation, dtype, storage=dace.StorageType.Default): n = dace.symbol('n', dace.int64) sdfg = dace.SDFG('linalg_cholesky_{}_{}'.format(implementation, dtype)) state = sdfg.add_state('dataflow') inp = sdfg.add_array('xin', [n, n], dtype) out = sdfg.add_array('xout', [n, n], dtype) ...
def _jump_lengths_individual(traj): if (len(traj) == 1): return [] lats_lngs = traj.sort_values(by=constants.DATETIME)[[constants.LATITUDE, constants.LONGITUDE]].values lengths = np.array([getDistanceByHaversine(lats_lngs[i], lats_lngs[(i - 1)]) for i in range(1, len(lats_lngs))]) return lengths
class _AvgPoolNd(Module): def extra_repr(self): return 'kernel_size={}, stride={}, padding={}'.format(self.kernel_size, self.stride, self.padding)
def ssim_exact(img1, img2, sd=1.5, C1=(0.01 ** 2), C2=(0.03 ** 2)): mu1 = ndimage.gaussian_filter(img1, sd) mu2 = ndimage.gaussian_filter(img2, sd) mu1_sq = np.multiply(mu1, mu1) mu2_sq = np.multiply(mu2, mu2) mu1_mu2 = np.multiply(mu1, mu2) sigma1_sq = (ndimage.gaussian_filter((img1 * img1), sd...
class QueryResponseDataset(Dataset): def __init__(self, tokenizer: transformers.PreTrainedTokenizer, queries: Sequence[str], responses: Sequence[str], query_len: int, response_len: int): super(QueryResponseDataset, self).__init__() def tokenize_without_truncation(strings): return [tokeni...
class XLMRobertaTokenizerFast(PreTrainedTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ['input_ids', 'attention_mask'] slow_tokenizer_class = XLMRobertaTo...
class Op(): def __init__(self, kind, inputs, attribs=None): self.kind = kind self.inputs = inputs self.output = None self.attribs = attribs def __repr__(self): attribs = ((' %r' % self.attribs) if self.attribs else '') return ('<Dim.Op %r %s%s>' % (self.kind, self...
def parse_multipart_headers(iterable): result = [] for line in iterable: line = to_native(line) (line, line_terminated) = _line_parse(line) if (not line_terminated): raise ValueError('unexpected end of line in multipart header') if (not line): break ...
def write_sample_to_java_file(sample, java_func_dir): couple = sample['url'].split('/')[(- 1)].split('#') class_name = couple[0].split('.java')[0] start = couple[1].split('-')[0].replace('L', '') end = couple[1].split('-')[1].replace('L', '') if ('repo' in sample.keys()): project = sample['r...
class LocalTFRunner(LocalRunner): def __init__(self, snapshot_config, sess=None, max_cpus=1): super().__init__(snapshot_config=snapshot_config, max_cpus=max_cpus) self.sess = (sess or tf.compat.v1.Session()) self.sess_entered = False def __enter__(self): if (tf.compat.v1.get_defa...
_LAYERS.register_module(name='PConv') class PartialConv2d(nn.Conv2d): def __init__(self, *args, multi_channel=False, eps=1e-08, **kwargs): super().__init__(*args, **kwargs) self.multi_channel = multi_channel self.eps = eps if self.multi_channel: (out_channels, in_channels...
class ListCompose(object): def __init__(self, transforms): self.transforms = transforms def __call__(self, coord, feat, label): for t in self.transforms: (coord, feat, label) = t(coord, feat, label) return (coord, feat, label)
def dist_location(dist): egg_link = egg_link_path(dist) if egg_link: return egg_link return dist.location
def make(domain, task, task_kwargs=None, environment_kwargs=None, visualize_reward=False): if (domain == 'cheetah'): return cheetah.make(task, task_kwargs=task_kwargs, environment_kwargs=environment_kwargs, visualize_reward=visualize_reward) elif (domain == 'quadruped'): return quadruped.make(ta...
_REGISTRY.register() class LEDNetModel(BaseModel): def __init__(self, opt): super(LEDNetModel, self).__init__(opt) self.net_g = build_network(opt['network_g']) self.init_weights = self.opt['train'].get('init_weights', False) if self.init_weights: self.initialize_weights(s...
def replace_return_docstrings(output_type=None, config_class=None): def docstring_decorator(fn): func_doc = fn.__doc__ lines = func_doc.split('\n') i = 0 while ((i < len(lines)) and (re.search('^\\s*Returns?:\\s*$', lines[i]) is None)): i += 1 if (i < len(lines)):...
.parametrize('supports_correct, expected', [(np.array([0.33]), (- 0.01)), (np.array([0.0]), (- 1.0)), (np.array([1.0]), 1.0)]) def test_exponential_func_multi_class(supports_correct, expected): n_classes = 3 result = exponential_func(n_classes, supports_correct) assert np.isclose(result, expected, atol=0.01...
class ChineseCLIPOnnxConfig(OnnxConfig): def inputs(self) -> Mapping[(str, Mapping[(int, str)])]: return OrderedDict([('input_ids', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('attention_mask', {0: 'batch', 1: 'sequence'})]) def outputs(self...
class ImagePool(): def __init__(self, pool_size): self.pool_size = pool_size if (self.pool_size > 0): self.num_imgs = 0 self.images = [] def query(self, images): if (self.pool_size == 0): return images return_images = [] for image in im...
def make_mlp(conf, d_in, d_latent=0, allow_empty=False, **kwargs): mlp_type = conf.get_string('type', 'mlp') if (mlp_type == 'mlp'): net = ImplicitNet.from_conf(conf, (d_in + d_latent), **kwargs) elif (mlp_type == 'resnet'): net = ResnetFC.from_conf(conf, d_in, d_latent=d_latent, **kwargs) ...
def get_time_stamp(): ct = time.time() local_time = time.localtime(ct) data_head = time.strftime('%Y-%m-%d %H:%M:%S', local_time) data_secs = ((ct - int(ct)) * 1000) time_stamp = ('%s.%03d' % (data_head, data_secs)) return time_stamp
def _parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--split', required=True, help='split to operate on') parser.add_argument('--pred_file', default=None, help='prediction file') args = parser.parse_args() if (args.split != 'train'): if (args.pred_file is None): ...
def schedule(func: Optional[object]=None, wait: int=2, warmup: int=2, active: int=2, repeat: int=1, skip_first: int=0): torch_scheduler = profiler.schedule(wait=wait, warmup=warmup, active=active, repeat=repeat, skip_first=skip_first) return set_profiler_attr(func=func, set_attr='schedule', handler=torch_schedu...
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--infile', required=True, type=str) parser.add_argument('--outdir') parser.add_argument('--nfold', default=10, type=int) parser.add_argument('--nchar', default=4, type=int) parser.add_argument('--seed', default=42, type=int)...
def create_plot(all_data, raw, x_scale, y_scale, xn, yn, fn_out, linestyles, batch): (xm, ym) = (metrics[xn], metrics[yn]) xm['description'] = '' hardcode_linestyles = {'USR-LSH': ('orangered', '-', 'o'), 'SB-LSH(Faiss)': ('mediumpurple', '--', 'x'), 'simHash': ('Skyblue', '--', '^')} handles = [] l...
def ndcg_score(ground_truth, predictions, k=1): lb = LabelBinarizer() lb.fit(range((len(predictions) + 1))) T = lb.transform(ground_truth) scores = [] for (y_true, y_score) in zip(T, predictions): actual = dcg_score(y_true, y_score, k) best = dcg_score(y_true, y_true, k) scor...
def write_avg_to_interm_file(out_path, intermediate_file, fold_num, train_scores_list, valid_scores_list, tasks, dataset, h='CV_average'): model_name = list(train_scores_list[0].keys())[0] num_iteration = len(valid_scores_list) if (num_iteration != fold_num): return train_metric_name_to_value_su...
() ('backbone', type=str) ('--imagenet-dir', type=str) ('-bs', '--batch-size', default=32, type=int) ('-nw', '--num-workers', default=10, type=int) ('-gpu', '--gpu/--no-gpu', default=True, is_flag=True) def main(backbone, imagenet_dir, batch_size, num_workers, gpu): ptu.set_gpu_mode(gpu) cfg = config.load_confi...
def test_strings_dtype(): clf = SelfTrainingClassifier(KNeighborsClassifier()) (X, y) = make_blobs(n_samples=30, random_state=0, cluster_std=0.1) labels_multiclass = ['one', 'two', 'three'] y_strings = np.take(labels_multiclass, y) with pytest.raises(ValueError, match='dtype'): clf.fit(X, y_...
class GradientsInputsCallback(VanillaGradientsCallback): explainer = GradientsInputs() default_output_subdir = 'gradients_inputs'
def override_qengines(qfunction): def test_fn(*args, **kwargs): for qengine in supported_qengines: with override_quantized_engine(qengine): qfunction(*args, **kwargs) return test_fn
def train_model(model, criterion, optimizer, scheduler, num_epochs=25): since = time.time() for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, (num_epochs - 1))) print(('-' * 10)) for phase in ['train', 'val']: if (phase == 'train'): scheduler.s...
def CossidentePenttilaGraph(q): (p, k) = is_prime_power(q, get_data=True) if ((not k) or (p == 2)): raise ValueError('q(={}) must be an odd prime power'.format(q)) from sage.features.gap import GapPackage GapPackage('grape', spkg='gap_packages').require() from sage.libs.gap.libgap import lib...
def find_modules(lib: str) -> Tuple[(str, str)]: folder_name = LIB2FOLDER_DICT[lib] if (importlib.util.find_spec(('pytorch_fw.' + folder_name)) is not None): model_lib_module = (('pytorch_fw.' + folder_name) + '.model_lib') quant_module = 'pytorch_fw.quant' elif (importlib.util.find_spec(('k...
def test_is_duplicate_operation(agent: Agent, mocker: MockerFixture): state = {'path/to/file1.txt': 'checksum1', 'path/to/file2.txt': 'checksum2'} mocker.patch.object(file_ops, 'file_operations_state', (lambda _: state)) assert (file_ops.is_duplicate_operation('write', 'path/to/file1.txt', agent.config, 'ch...
def rows_tags(obj): if isinstance(obj, dict): obj = obj.items() results = [] results.append('<table style="display:inline-table">') for row in obj: results.append('<tr style="padding:0">') for item in row: results.append(('<td style="text-align:left; vertical-align:to...
def get_secrets(num): secrets = [Secret() for _ in range(num)] secret_values = list(range(num)) secret_dict = {x: v for (x, v) in zip(secrets, secret_values)} return (secrets, secret_values, secret_dict)
class TextTransform(): def __init__(self): char_map_str = "\n ' 0\n <SPACE> 1\n a 2\n b 3\n c 4\n d 5\n e 6\n f 7\n g 8\n h 9\n i 10\n j 11\n k 12\n l 13\n m 14\n n 15\n o 16\n p 17\...
class TestCEM(TfGraphTestCase): .large def test_cem_cartpole(self): with LocalTFRunner(snapshot_config) as runner: env = GarageEnv(env_name='CartPole-v1') policy = CategoricalMLPPolicy(name='policy', env_spec=env.spec, hidden_sizes=(32, 32)) baseline = LinearFeatureBa...
def _softmax(raw, input, dim=None, _stacklevel=3): x = raw(input, dim=dim) if (dim is None): dim = F._get_softmax_dim('softmax', input.dim(), _stacklevel) bottom_blobs = [log.blobs(input)] name = log.add_layer(name='softmax') log.add_blobs([x], name='softmax_blob') layer = caffe_net.Laye...
class Tarball(object): def __init__(self, tarball_name, package=None): self.__filename = tarball_name if (package is None): self.__package = None for pkg in Package.all(): if (pkg.tarball_filename == tarball_name): self.__package = pkg.tarb...
_utils.test() def test_nested_loops(): x = ti.field(ti.i32) n = 2048 ti.root.dense(ti.ij, n).place(x) def paint(): for i in range(n): for j in range(n): x[(0, 0)] = i paint()
class DummyDataset(torch.utils.data.Dataset): def __init__(self): self.data = list(range(10)) def __len__(self): return len(self.data) def __getitem__(self, idx): if torch.is_tensor(idx): idx = idx.tolist() assert (self.start == 0) return self.data[idx]
.skipif((not require_gpu), reason='STELLARGRAPH_MUST_USE_GPU is not set to 1, so a GPU does not have to be used') def test_on_gpu_when_requested(): tf.debugging.set_log_device_placement(True) a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6....
class SolcError(Exception): message = 'An error occurred during execution' def __init__(self, message: str=None, command: List=None, return_code: int=None, stdin_data: str=None, stdout_data: str=None, stderr_data: str=None, error_dict: Dict=None) -> None: if (message is not None): self.messa...
def main(): config = get_config() experiment = ExperimentHandler(config) print(('\x1b]2;%s\x1b\\' % config['experiment_name'])) experiment.run() print('Experiment concluded.')
class QuantizePerTensorBenchmark(op_bench.TorchBenchmarkBase): def init(self, C, M, N, dtype, mode): assert (mode in ('Q', 'D')) self.input = torch.rand(C, M, N) self.dtype = dtype self.op = nnq.Quantize(scale=1.0, zero_point=0, dtype=dtype) self.set_module_name('QuantizePerT...
def add_flops_counter_variable_or_reset(module): if is_supported_instance(module): module.__flops__ = 0
class SkylineServer(): def __init__(self, host, port): self._requested_host = host self._requested_port = port self._connection_acceptor = ConnectionAcceptor(self._requested_host, self._requested_port, self._on_new_connection) self._connection_manager = ConnectionManager(self._on_mes...
def update_params(batch, i_iter): states = torch.from_numpy(np.stack(batch.state)).to(dtype).to(device) actions = torch.from_numpy(np.stack(batch.action)).to(dtype).to(device) rewards = torch.from_numpy(np.stack(batch.reward)).to(dtype).to(device) masks = torch.from_numpy(np.stack(batch.mask)).to(dtype)...
(frozen=True) class MetricInfo(): canonical_name: str aka: set[str] dist_func: Callable cdist_func: Callable pdist_func: Callable validator: Optional[Callable] = None types: list[str] = dataclasses.field(default_factory=(lambda : ['double'])) requires_contiguous_out: bool = True
def register_Ns3SimpleOfdmSendParam_methods(root_module, cls): cls.add_constructor([param('ns3::simpleOfdmSendParam const &', 'arg0')]) cls.add_constructor([]) cls.add_constructor([param('ns3::bvec const &', 'fecBlock'), param('uint32_t', 'burstSize'), param('bool', 'isFirstBlock'), param('uint64_t', 'Frequ...
def ocp_ksp(F, bcs, J, y, u, p, config_ocp, ksp_options): return cashocs.OptimalControlProblem(F, bcs, J, y, u, p, config=config_ocp, ksp_options=ksp_options)
.parametrize('observation_shape', [(4, 84, 84)]) def test_pixel_observation_scaler(observation_shape: Sequence[int]) -> None: scaler = PixelObservationScaler() x = torch.randint(high=255, size=observation_shape) y = scaler.transform(x) assert torch.all((y == (x.float() / 255.0))) assert (scaler.get_...
def check_kind_cluster() -> None: try: kind_clusters_process = subprocess.run('kind get clusters'.split(), check=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) kind_clusters = set(kind_clusters_process.stdout.decode('utf-8').split()) if ('kind' not in kind_clusters): lo...
def convert_datasets(train: List, valid: List, test: List, subj_index_mapper: IndexMapper, obj_index_mapper: IndexMapper, rel_index_mapper: IndexMapper, triple_format_parser=(lambda x: x.strip().split('\t')), subj_slot=0, rel_slot=1, obj_slot=2, filter_unseen=False, filter_func=None, segment=False): if (not filter_...
def call_intersphinx(app, env, node, contnode): debug_inf(app, ('???? Trying intersphinx for %s' % node['reftarget'])) builder = app.builder res = intersphinx.missing_reference(app, env, node, contnode) if res: if res['refuri'].startswith(SAGE_DOC): here = os.path.dirname(os.path.joi...
class KleshchevCrystalMixin(): def epsilon(self, i): return len(self.normal_cells(i)) def phi(self, i): return len(self.conormal_cells(i)) def Epsilon(self): P = self.parent() WLR = P.weight_lattice_realization() La = WLR.fundamental_weights() n = self.normal_...
(Output('topic-table', 'data'), [Input('topic-data', 'data')]) def get_topic_words(data): topic_words = get_top_n_words(data['topics'], n=15) topic_names = [topic['name'] for topic in data['topics'].values()] topic_dict = {} topic_dict['topic_names'] = topic_names topic_dict['topic_words'] = topic_w...
class ReversePseudoFP16Initializer(Initializer): def update(self, operator_name, kwargs): if (self.operator_name is not None): raise Exception('Operator name overwrites are not allowed') self.operator_name = operator_name self.operator_kwargs = kwargs def create_param(self, p...
def register_functions(root_module): module = root_module module.add_function('MakePriomapChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) register_functions_ns3_FatalImpl(module.add_cpp_namespace('FatalImpl'), root_module) register_functions_ns3_Hash(module.add_cpp_namespace('Hash'), root_modul...
def gather_metadata() -> Dict: date_start = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') try: repo = git.Repo(search_parent_directories=True) git_sha = repo.commit().hexsha git_data = dict(commit=git_sha, branch=repo.active_branch.name, is_dirty=repo.is_dirty(), path=repo.git...
def get_examples(data_dir, set_type): examples = [] levels = ['middle', 'high'] set_type_c = set_type.split('-') if (len(set_type_c) == 2): levels = [set_type_c[1]] set_type = set_type_c[0] for level in levels: cur_dir = os.path.join(data_dir, set_type, level) for fil...
def hash_file(path, blocksize=(1 << 20)): h = hashlib.sha256() length = 0 with open(path, 'rb') as f: for block in read_chunks(f, size=blocksize): length += len(block) h.update(block) return (h, length)
class ResNet_Atrous(nn.Module): def __init__(self, block, layers, atrous=None, os=16): super(ResNet_Atrous, self).__init__() stride_list = None if (os == 8): stride_list = [2, 1, 1] elif (os == 16): stride_list = [2, 2, 1] else: raise Value...
class Adagrad(Optimizer): def __init__(self, lr=0.01, epsilon=1e-06, *args, **kwargs): super(Adagrad, self).__init__(**kwargs) self.__dict__.update(locals()) self.lr = shared_scalar(lr) def get_updates(self, params, constraints, loss): grads = self.get_gradients(loss, params) ...
.operations('success') .openapi_version('3.0') def test_forbid_simultaneous_use_of_deprecated_and_new_options(cli, schema_url, cassette_path, snapshot_cli): assert (cli.run(schema_url, f'--store-network-log={cassette_path}', f'--cassette-path={cassette_path}') == snapshot_cli)
def get_label2prevalence(df, tasks): label2prevalence = {} for task in tasks: num_labeled = ((df[task] == 1) | (df[task] == 0)).sum() num_positive = (df[task] == 1).sum() prevalence = (num_positive / num_labeled) label2prevalence[task] = prevalence return label2prevalence
def eval_success(sessions) -> list: success = [] for sess in sessions: r = get_reward(sess) if (r >= 1): success.append(1) else: success.append(0) return success
def resnet34(pretrained=False, progress=True, device='cpu', **kwargs): return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress, device, **kwargs)
def generate_result(dataset, ground_truth, prediction): activity_map = json.load(open(os.path.join('configs', 'activity_maps', (dataset + '.json')))) activity_names = list(activity_map.values()) print('\n[CLASSIFICATION REPORT]') print(classification_report(np.argmax(ground_truth, axis=1), np.argmax(pre...
def norm2(x: Tensor, axis=[(- 2), (- 1)]) -> Tensor: n = tf.math.real(tf.math.multiply(tf.math.conj(x), x)) if (len(axis) == 0): return n return tf.math.reduce_sum(n, axis=axis)
class MIOAlgorithm(GenerationAlgorithm[arch.MIOArchive]): _logger = logging.getLogger(__name__) def __init__(self) -> None: super().__init__() self._solution: (tcc.TestCaseChromosome | None) = None self._parameters = Parameters() self._current_mutations = 0 self._focused ...
def rot_ply_loss(gt, pred, num_samples, img_size=256): rotate_gt = (rotate_to_horizon(gt, img_size) - (img_size / 2)) rotate_pred = (rotate_to_horizon(pred, img_size) - (img_size / 2)) rotate_gt = (rotate_gt / torch.max(torch.abs(rotate_gt), dim=1).values.unsqueeze(1)) rotate_pred = (rotate_pred / torch...