code
stringlengths
101
5.91M
def simple_while(A: dace.int32[10]): i = 0 while (i < 10): A[i] += (2 * i) i += 1
class GrailEntityDisambFeature(): def __init__(self, pid, input_ids, token_type_ids, target_idx): self.pid = pid self.candidate_input_ids = input_ids self.candidate_token_type_ids = token_type_ids self.target_idx = target_idx
def save_summary(epoch: int, global_step: int, accuracies: List[utils.AverageMeter], duration: timedelta, tracking_file: str, mode: str, top=(1,)): result: Dict[(str, Any)] = OrderedDict() result['timestamp'] = datetime.now() result['mode'] = mode result['epoch'] = epoch result['global_step'] = glob...
class ROCExplanation(ExplanationBase): def __init__(self): super().__init__() self.explanations = {} def add(self, fpr: Dict, tpr: Dict, auc: Dict): self.explanations = {'fpr': fpr, 'tpr': tpr, 'auc': auc} def get_explanations(self): return self.explanations def plot(self...
def numpy_to_hls_code(ndarray, dtype, hls_var_name, pack_innermost_dim=True, no_decl=False): hls_dtype = dtype.get_hls_datatype_str() if ((type(ndarray) != np.ndarray) or (ndarray.dtype != np.float32)): ndarray = np.asarray(ndarray, dtype=np.float32) if pack_innermost_dim: idimlen = ndarray....
def plot_avg_clustering(G_times, fname): max_time = len(G_times) t = list(range(0, max_time)) avg_clustering = [] for G in G_times: avg_clustering.append(nx.average_clustering(G)) plt.rcParams.update({'figure.autolayout': True}) plt.rc('xtick', labelsize='x-small') plt.rc('ytick', la...
class FiniteWordPath_all_iter_with_caching(WordDatatype_iter_with_caching, FiniteWordPath_all, FiniteWord_class): pass
def BetsyRoss(): E = 'abcdefghijk' CC = {2: ['acfg', 'bdgh', 'cehi', 'befj', 'adij', 'dfk', 'egk', 'ahk', 'bik', 'cjk'], 3: [E]} M = CircuitClosuresMatroid(groundset=E, circuit_closures=CC) M.rename(('BetsyRoss: ' + repr(M))) return M
def test_Detector_init(): (detector, parent, tl) = create_detector(dark_count=10) tl.init() assert (len(tl.events) == 2)
def Q_calc(TP, TN, FP, FN): try: OR = ((TP * TN) / (FP * FN)) result = ((OR - 1) / (OR + 1)) return result except (ZeroDivisionError, TypeError): return 'None'
class DateTimeField(fields.DateTimeField): def __init__(self, *args, **kwargs): if (not has_timezone): raise ImportError('DateTimeField requires Django >= 1.5') super(DateTimeField, self).__init__(*args, **kwargs) def process_formdata(self, valuelist): super(DateTimeField, se...
def get_params(argv='1'): print('SET: {}'.format(argv)) params = dict(quick_test=True, finetune_mode=False, pretrained_model_weights='models/1_1_foa_dev_split6_model.h5', dataset_dir='/scratch/asignal/partha/DCASE2022_SELD_dataset', feat_label_dir='/scratch/asignal/partha/DCASE2022_SELD_dataset/seld_feat_label'...
class Decoder(Network): def __init__(self, output_width, output_height, output_depth, stride=2, kernel=5, final_dim=64, scope_name='decoder', *args, **kwargs): super(Decoder, self).__init__(*args, scope_name=scope_name, **kwargs) self.output_width = output_width self.output_height = output_h...
def _launch_worker(exp_key, worker_id, host, port, result_db_name): command = 'hyperopt-mongo-worker --mongo={h}:{p}/{db} --poll-interval=10 --exp-key={key} > hyperopt_worker{id}.log 2>&1' command = command.format(h=host, p=port, db=result_db_name, key=exp_key, id=worker_id) fail = os.system(command) if...
def arg_str2bool(v): if isinstance(v, bool): return v elif (v.lower() in ('yes', 'true', 't', 'y', '1')): return True elif (v.lower() in ('no', 'false', 'f', 'n', '0')): return False else: raise argparse.ArgumentTypeError('Boolean value expected.')
class KaHFM_model(keras.Model): def __init__(self, user_factors, item_factors, learning_rate=0.001, l_w=0, l_b=0, name='NNBPRMF', **kwargs): super().__init__(name=name, **kwargs) tf.random.set_seed(42) self._learning_rate = learning_rate self.l_w = l_w self.l_b = l_b ...
def exec_command(command, execute_in='', use_shell=None, use_tee=None, _with_python=1, **env): warnings.warn('exec_command is deprecated since NumPy v1.17, use subprocess.Popen instead', DeprecationWarning, stacklevel=1) log.debug(('exec_command(%r,%s)' % (command, ','.join([('%s=%r' % kv) for kv in env.items()...
class AffineGroupElement(MultiplicativeGroupElement): def __init__(self, parent, A, b=0, convert=True, check=True): try: A = A.matrix() except AttributeError: pass if (is_Matrix(A) and (A.nrows() == A.ncols() == (parent.degree() + 1))): g = A d...
def gen_expr_simps(simps: LeanExprSimps, at_var: Optional[str]=None, indent: int=0) -> List[str]: lines = [] simp_at = (f' at {at_var}' if (at_var is not None) else '') if (0 < len(simps.const_div_rw)): lines.append(((' ' * indent) + f"try {{ simp only [{', '.join(simps.const_div_rw)}]{simp_at} }},"...
def test_sum_add_bad_node_raise_type_error(): var1 = optplan.Parameter() var2 = optplan.Parameter() sum1 = optplan.Sum(functions=[var1, var2]) with pytest.raises(TypeError, match='add a node'): (sum1 + optplan.SimulationSpace())
def get_key(paragraphs, question, reasoningType): return (paragraphs.replace('\n', '').replace(' ', '').lower(), question.lower(), reasoningType)
class Partition5(nn.Module): LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[decoder]/T5Block[3]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5Block[4]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5Block[5]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5LayerNorm[final_layer_norm]', 'T5ForConditionalGen...
def dump_example(dataset_name): print('Converting {:}.h5 ...'.format(dataset_name)) file = h5py.File(os.path.join(path, 'traindata', '{:}.h5'.format(dataset_name)), 'r') for (seq_idx, seq_name) in enumerate(file): if (dataset_name == 'scenes11_train'): scale = 0.4 else: ...
_mapper() def modify_in_place(x: DataPoint) -> DataPoint: x.d['my_key'] = 0 return Row(num=x.num, d=x.d, d_new=x.d)
class _Encoder(nn.Module): def __init__(self, imageSize): super(_Encoder, self).__init__() n = math.log2(imageSize) assert (n == round(n)), 'imageSize must be a power of 2' assert (n >= 3), 'imageSize must be at least 8' n = int(n) self.conv1 = nn.Conv2d((ngf * (2 ** ...
class TestParameters(unittest.TestCase): def test_parameters(self): gdb.execute('set cy_colorize_code on') assert libcython.parameters.colorize_code gdb.execute('set cy_colorize_code off') assert (not libcython.parameters.colorize_code)
_ENCODERS.register_module() class DarkNet53(nn.Module): def __init__(self, freeze_layer=2, pretrained='./data/weights/darknet.weights', out_layer=(6, 8, 13)): super(DarkNet53, self).__init__() self.fp16_enabled = False assert isinstance(out_layer, tuple) self.out_layer = out_layer ...
def batch_normalization(x, beta, gamma, mean, variance, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, n_outputs=None): from .function_bases import batch_normalization as batch_normalization_base n_outputs = (3 if output_stat else 1) axes = _force_list(axes) axes = [(a + (len(x...
def supersample(clip, d, nframes): def fl(gf, t): tt = np.linspace((t - d), (t + d), nframes) avg = np.mean((1.0 * np.array([gf(t_) for t_ in tt], dtype='uint16')), axis=0) return avg.astype('uint8') return clip.fl(fl)
def get_layers(in_index, in_channels, embed_dims, channels, embed_neck_cfg, embed_cfg, fusion_cfg): embed_layers = {} for (i, in_channels, embed_dim) in zip(in_index, in_channels, embed_dims): if (i == in_index[(- 1)]): embed_layers[str(i)] = build_layer(in_channels, embed_dim, **embed_neck_...
def cleaner_mimic(text, spacy=True): text = re.sub('\\s+', ' ', text.strip()) if spacy: text = [t.text.lower() for t in nlp(text)] else: text = [t.lower() for t in text.split()] text = ' '.join(text) text = re.sub('\\[\\s*\\*\\s*\\*(.*?)\\*\\s*\\*\\s*\\]', ' <DE> ', text) text = ...
class _ReBenchDB(_ConcretePersistence): def __init__(self, configurator, data_store, ui): super(_ReBenchDB, self).__init__(data_store, ui) self._configurator = configurator self._rebench_db = configurator.get_rebench_db_connector() self._lock = Lock() self._cache_for_seconds ...
class Experiment(): def __init__(self, experiment_id, params): self._experiment_id = experiment_id self._cluster_spec = params['cluster_spec'] self._policy = params['policy'] self._seed = int(params['seed']) self._lam = (- 1) self._num_total_jobs = (- 1) self....
('data.dmlab', 'class') class DmlabData(base.ImageTfdsData): def __init__(self, data_dir=None): dataset_builder = tfds.builder('dmlab:2.0.1', data_dir=data_dir) tfds_splits = {'train': 'train', 'val': 'validation', 'trainval': 'train+validation', 'test': 'test', 'train800': 'train[:800]', 'val200': ...
def _load_split_txt(path): with open(path, 'r') as f: return list(map((lambda s: str(s.split()[0])), f.readlines()))
class BlackBodySimpleSourceRelativistic(BlackBodySimpleSource): def from_model(cls, model, *args, **kwargs): return cls(model.time_explosion, model.r_inner[0], model.t_inner.value, *args, **kwargs) def __init__(self, time_explosion=None, **kwargs): self.time_explosion = time_explosion su...
def repo_list(recipe_folder='tests/recipes', field='HF_repo'): HF_repos = [] for recipe_csvfile in os.listdir(recipe_folder): if (recipe_csvfile in __skip_list): continue with open(os.path.join(recipe_folder, recipe_csvfile), newline='') as csvf: reader = csv.DictReader(c...
def test_case57(): url = (brokerIp + '/ngsi-ld/v1/entityOperations/upsert') headers = {'Content-Type': 'application/json', 'Link': '<{{link}}>; rel=" type="application/ld+json"'} r = requests.post(url, data=json.dumps(ld_data.subdata48), headers=headers) print(r.content) assert (r.status_code == 404...
def gaussian_measure_full(mean, cov, f): if (not is_pos_def(cov)): logger.warn(f'cov={cov} not positive definite') L = cholesky(cov) def integrand(x): y = ((L x) + mean) return (norm_pdf(x) * f(y)) K = mean.shape[0] lim = ([[(- 10), 10]] * K) integral = nquad(integrand, ...
def all_reduce_losses(losses): (names, values) = ([], []) for (k, v) in losses.items(): names.append(k) values.append(v) values = torch.cat([v.view(1) for v in values], dim=0) dist.all_reduce(values, dist.ReduceOp.SUM) values.div_(dist.get_world_size()) values = torch.chunk(value...
def test_ticket_701(): arr = numpy.arange(4).reshape((2, 2)) def func(x): return numpy.min(x) res = ndimage.generic_filter(arr, func, size=(1, 1)) res2 = ndimage.generic_filter(arr, func, size=1) assert_equal(res, res2)
def test_KMaxPooling(): with CustomObjectScope({'KMaxPooling': sequence.KMaxPooling}): layer_test(sequence.KMaxPooling, kwargs={'k': 3, 'axis': 1}, input_shape=(BATCH_SIZE, SEQ_LENGTH, EMBEDDING_SIZE, 2))
class BSNSNmat(SpectralMatrix): def assemble(self, method): (test, trial) = (self.testfunction, self.trialfunction) assert isinstance(test[0], SN) assert isinstance(trial[0], SN) N = test[0].N k = np.arange((N - 2), dtype=float) alpha = (((k * (k + 1)) / (k + 2)) / (k...
def seed_worker(worker_id): clear_logging() worker_seed = (torch.initial_seed() % (2 ** 32)) seed_everything(worker_seed)
def load_weight(sess, data, include=[]): for scope in include: for v in tf.compat.v1.global_variables(): if ((v.name in data.keys()) and (scope in v.name)): if (v.shape == data[v.name].shape): sess.run(v.assign(data[v.name])) print('load we...
def get_training_roidb(imdb): if cfg.TRAIN.USE_FLIPPED: print('Appending horizontally-flipped training examples...') imdb.append_flipped_images() print('done') print('Preparing training data...') rdl_roidb.prepare_roidb(imdb) print('done') return imdb.roidb
class TFGroupViTPreTrainedModel(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def _is_exception(obj): if (not inspect.isclass(obj)): return False return issubclass(obj, Exception)
class NormalizedClassifier(nn.Module): def __init__(self): super().__init__() self.weight = nn.Parameter(torch.Tensor(1501, 2048)) self.weight.data.uniform_((- 1), 1).renorm_(2, 0, 1e-05).mul_(100000.0) def forward(self, x): w = self.weight x = nn.functional.normalize(x, ...
_test() def test_matmul_np(): def matmul_np(A: dace.float64[(128, 64)], B: dace.float64[(64, 32)], C: dace.float64[(128, 32)]): C[:] = (A B) A = np.random.rand(128, 64).astype(np.float64) B = np.random.rand(64, 32).astype(np.float64) C = np.random.rand(128, 32).astype(np.float64) sdfg = mat...
class Optimizer(object): def __init__(self, cost, params): self.cost = cost self.params = params self.updates = self._updates() def _updates(self): raise NotImplementedError()
def read_posetrack_keypoints(output_folder): people = dict() for (idx, result_file) in enumerate(sorted(os.listdir(output_folder))): json_file = osp.join(output_folder, result_file) data = json.load(open(json_file)) for person in data['people']: person_id = person['person_id'...
def log_likelihood(mu, var, x, muq, varq, a, mask_flat, config): if (config.out_distr == 'bernoulli'): log_lik = log_bernoulli(x, mu, eps=1e-06) elif (config.out_distr == 'gaussian'): log_lik = log_gaussian(x, mu, var) log_lik = tf.reduce_sum(log_lik, 1) log_lik = tf.multiply(mask_flat, ...
def write_list(out_filename, dataset): formatted_dataset = [line._asdict() for line in dataset] with open(out_filename, 'w') as fout: fout.write('[\n') for (idx, line) in enumerate(formatted_dataset): fout.write(' ') json.dump(line, fout, ensure_ascii=False) ...
class ConcatChannel(SOFactor): n_next = 1 def __init__(self, Ns, axis=0): self.Ns = Ns self.axis = axis self.repr_init() self.n_prev = len(Ns) self.N = sum(Ns) def sample(self, *Zs): if (len(Zs) != self.n_prev): raise ValueError(f'expect {self.n_pr...
def write_label_file(labels_to_class_names, dataset_dir, filename=LABELS_FILENAME): labels_filename = os.path.join(dataset_dir, filename) with tf.gfile.Open(labels_filename, 'w') as f: for label in labels_to_class_names: class_name = labels_to_class_names[label] f.write(('%d:%s\n...
def main(): args = create_argparser().parse_args() logger.log(f'args: {args}') dist_util.setup_dist() logger.configure() logger.log('creating 2d model and diffusion...') (model, diffusion) = create_model_and_diffusion_2d(**args_to_dict(args, model_and_diffusion_defaults_2d().keys())) model.t...
class Partition0(nn.Module): LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEmbeddings[embeddings]/Embedding[word_embeddings]', 'BertForQuestionAnswering/BertModel[bert]/BertEmbeddings[embeddings]/Embedding[position_embeddings]', 'BertForQuestionAnswering/BertModel[bert]/BertEmbeddings[embeddings]/Em...
class UCBVI(abc.ABC): def __init__(self, mdp, n_episodes=1, init_state=None, reg_factor=1.0, confidence_scaling_factor=(- 1.0), delta=0.05, train_every=1, throttle=int(100.0)): self.mdp = mdp self.n_episodes = n_episodes self.init_state = init_state self.reg_factor = reg_factor ...
def get_kitchen_benchmark_goals(): object_goal_vals = {'bottom_burner': [(- 0.88), (- 0.01)], 'light_switch': [(- 0.69), (- 0.05)], 'slide_cabinet': [0.37], 'hinge_cabinet': [0.0, 0.5], 'microwave': [(- 0.5)], 'kettle': [(- 0.23), 0.75, 1.62]} object_goal_idxs = {'bottom_burner': [9, 10], 'light_switch': [17, 1...
def PreActResNet18(num_channels=3): return PreActResNet(PreActBlock, [2, 2, 2, 2], num_channels=num_channels)
def line_search(f, x0, dx, g0, alpha, condition, max_steps=10, c1=0.1): assert (0 < alpha < 1) f0 = f(x0) for _ in range(max_steps): x = (x0 + dx) if ((f(x) > (f0 + ((c1 * g0.T) dx))) and condition(x)): return x dx *= alpha print('Line search failed, returning x0') ...
class R1_mAP(Metric): def __init__(self, num_query, max_rank=50, feat_norm='yes'): super(R1_mAP, self).__init__() self.num_query = num_query self.max_rank = max_rank self.feat_norm = feat_norm def reset(self): self.feats = [] self.pids = [] self.camids = [...
class NovelViewSynthesizeModel(object): def __init__(self, output_dir): self.output_dir = mkdir(output_dir) self.si_out_dir = self.output_dir self.num_preds_si = 0 def imitate(self, src_infos: Dict[(str, Any)], ref_infos: Dict[(str, Any)]) -> List[str]: raise NotImplementedError ...
class BinaryMorphology2D(): param_names = ['shape', 'footprint', 'radius', 'decomposition'] params = [((512, 512),), ('square', 'diamond', 'octagon', 'disk', 'ellipse', 'star'), (1, 3, 5, 15, 25, 40), (None, 'sequence', 'separable', 'crosses')] def setup(self, shape, footprint, radius, decomposition): ...
def get_args(): parser = argparse.ArgumentParser() train_inten.add_inten_train_args(parser) nn_utils.add_hyperopt_args(parser) return parser.parse_args()
class Cipher(Element): def __init__(self, parent, key): Element.__init__(self, parent) self._key = key def __eq__(self, right): return ((type(self) is type(right)) and (self.parent() == right.parent()) and (self._key == right._key)) def _repr_(self): return ('Cipher on %s' % ...
def test_data_dependency_5(): module_block = BasicBlock([Instr('LOAD_BUILD_CLASS'), Instr('LOAD_CONST', arg=dummy_code_object), Instr('LOAD_CONST', arg='Foo'), Instr('MAKE_FUNCTION', arg=0), Instr('LOAD_CONST', arg='Foo'), Instr('CALL_FUNCTION', arg=2), Instr('STORE_NAME', arg='Foo'), Instr('LOAD_GLOBAL', arg='Foo'...
class InputFeatures_eval(object): def __init__(self, input_ids, input_mask, segment_ids, label_id, label_disf_id, label_sing_id): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids self.label_id = label_id self.label_disf_id = label_disf_id...
def decode_pose(root_score, root_id, root_image_coord, scores, offsets, output_stride, displacements_fwd, displacements_bwd): num_parts = scores.shape[2] num_edges = len(PARENT_CHILD_TUPLES) instance_keypoint_scores = np.zeros(num_parts) instance_keypoint_coords = np.zeros((num_parts, 2)) instance_k...
def xla_available() -> bool: try: return (find_spec('torch_xla') is not None) except ModuleNotFoundError: return False
class Extractor(ModelBase): def __init__(self, config: ExtractorConfig): super().__init__(config) def _get_full_embedded(self, batch: Batch): embedded = [] if hasattr(self, 'ohots'): ohots_embedded = [self.ohots[f](batch.ohots[f]) for f in self.ohots] embedded.ext...
class MBv3LatencyTable(LatencyTable): def query(self, l_type: str, input_shape, output_shape, mid=None, ks=None, stride=None, id_skip=None, se=None, h_swish=None): infos = [l_type, ('input:%s' % self.repr_shape(input_shape)), ('output:%s' % self.repr_shape(output_shape))] if (l_type in ('expanded_co...
class AutoUpliftTX(BaseAutoUplift): __MAP_META_TO_STAGES__: Dict[(str, List[MetaLearnerStage])] = {'TLearner': [MetaLearnerStage(name='outcome_control'), MetaLearnerStage(name='outcome_treatment')], 'XLearner': [MetaLearnerStage(name='outcome_control'), MetaLearnerStage(name='outcome_treatment'), MetaLearnerStage(n...
class AutoContrast(DauphinTransform): def __init__(self, name=None, prob=1.0, level=0): super().__init__(name, prob, level) def transform(self, pil_img, label, **kwargs): return (ImageOps.autocontrast(pil_img), label)
class CAtlas(): def __init__(self, cdbg_directory, catlas_directory, load_domfile=True, load_sizefile=False, min_abund=0.0): self.cdbg_dir = cdbg_directory self.name = catlas_directory self.parent = {} self.children = defaultdict(set) self.levels = {} self._cdbg_to_ca...
class MultiEnvWrapper(gym.Wrapper): def __init__(self, envs, sample_strategy=uniform_random_strategy): self._sample_strategy = sample_strategy self._num_tasks = len(envs) self._active_task_index = None self._observation_space = None super().__init__(envs[0]) self._tas...
class foldnorm_gen(rv_continuous): def _argcheck(self, c): return (c >= 0) def _shape_info(self): return [_ShapeInfo('c', False, (0, np.inf), (True, False))] def _rvs(self, c, size=None, random_state=None): return abs((random_state.standard_normal(size) + c)) def _pdf(self, x, c)...
_REGISTRY.register() class PartialiLIDS(ImageDataset): dataset_name = 'partialilids' def __init__(self, root='datasets'): self.root = root self.query_dir = osp.join(self.root, 'PartialiLIDS/query') self.gallery_dir = osp.join(self.root, 'PartialiLIDS/gallery') (query, gallery) = ...
class EvaluatorConfig(metaclass=AutodocABCMeta): _timedelta_keys = ['train_window', 'retrain_freq', 'cadence'] def __init__(self, train_window: float=None, retrain_freq: float=None, cadence: float=None): self.train_window = train_window self.retrain_freq = retrain_freq self.cadence = cad...
def get_joint_slot_correctness(preds, class_types, label_maps, key_class_label_id='class_label_id', key_class_prediction='class_prediction', key_start_pos='start_pos', key_start_prediction='start_prediction', key_end_pos='end_pos', key_end_prediction='end_prediction', key_refer_id='refer_id', key_refer_prediction='refe...
class RawData(TypedDict): label: ThreeLabels supporting_sentences: list[list[int]] claim: str evidence: list[str] meta: dict
class local_mem(Structure): _fields_ = [('raw_ptr', POINTER(ctypes.c_char)), ('mem_arr', POINTER(POINTER(ctypes.c_uint32))), ('count', ctypes.c_int32), ('size_per_mem', ctypes.c_int32), ('align_num', ctypes.c_int32), ('need_free', ctypes.c_int32)]
class GeneralEdgeAttConvv1(nn.Module): def __init__(self, dim_in, dim_out, bias=False, **kwargs): super(GeneralEdgeAttConvv1, self).__init__() self.model = GeneralEdgeAttConvv1Layer(dim_in, dim_out, bias=bias) def forward(self, batch): batch.node_feature = self.model(batch.node_feature, ...
def main(unused_argv): def _is_valid_num_shards(num_shards): return ((num_shards < FLAGS.num_threads) or (not (num_shards % FLAGS.num_threads))) assert _is_valid_num_shards(FLAGS.train_shards), 'Please make the FLAGS.num_threads commensurate with FLAGS.train_shards' assert _is_valid_num_shards(FLAGS...
def dconv_flops_counter_hook(dconv_module, input, output): input = input[0] batch_size = input.shape[0] output_dims = list(output.shape[2:]) (m_channels, in_channels, kernel_dim1, _) = dconv_module.weight.shape (out_channels, _, kernel_dim2, _) = dconv_module.projection.shape conv_per_position_f...
class TypecastNode(ExprNode): subexprs = ['operand'] base_type = declarator = type = None def type_dependencies(self, env): return () def infer_type(self, env): if (self.type is None): base_type = self.base_type.analyse(env) (_, self.type) = self.declarator.analys...
def set_working_device(device_name: str): device_manager = DeviceManager() device_manager.set_device(device_name)
def formatannotation(annotation, base_module=None): if isinstance(annotation, type): if (annotation.__module__ in ('builtins', '__builtin__', base_module)): return annotation.__name__ return ((annotation.__module__ + '.') + annotation.__name__) return repr(annotation)
def build_model(): g = tf.Graph() with g.as_default(), tf.device(tf.train.replica_device_setter(FLAGS.ps_tasks)): (inputs, labels) = imagenet_input(is_training=True) with slim.arg_scope(mobilenet_v1.mobilenet_v1_arg_scope(is_training=True)): (logits, _) = mobilenet_v1.mobilenet_v1(in...
def dstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False, workers=None, orthogonalize=None): return _execute(_pocketfft.dstn, x, type, s, axes, norm, overwrite_x, workers, orthogonalize)
def load_conv2d(state_dict, name_pth, name_tf): h5f = h5py.File((('dump/InceptionV4/' + name_tf) + '.h5'), 'r') state_dict[(name_pth + '.conv.weight')] = torch.from_numpy(h5f['weights'][()]).permute(3, 2, 0, 1) out_planes = state_dict[(name_pth + '.conv.weight')].size(0) state_dict[(name_pth + '.bn.weig...
def capture_time(): start = time.perf_counter() done = False def fn(): if done: return (end - start) else: return (time.perf_counter() - start) (yield fn) end = time.time()
_module() class SRREDSMultipleGTDataset(BaseSRDataset): def __init__(self, lq_folder, gt_folder, num_input_frames, pipeline, scale, val_partition='official', repeat=1, test_mode=False): self.repeat = repeat if (not isinstance(repeat, int)): raise TypeError(f'"repeat" must be an integer, ...
class IndicatorMin(OptimizationFunction): def __init__(self, objective: OptimizationFunction, beta: float=0, power: float=2): super().__init__(objective) self.obj = objective self.beta = beta self.power = power def eval(self, input_vals: List[np.ndarray]) -> np.ndarray: r...
class Inferencer(ABC): def load_model(self, path: (str | Path)) -> Any: raise NotImplementedError def pre_process(self, image: np.ndarray) -> (np.ndarray | Tensor): raise NotImplementedError def forward(self, image: (np.ndarray | Tensor)) -> (np.ndarray | Tensor): raise NotImplemente...
class AuxiliaryHeadCIFAR(nn.Module): def __init__(self, C, num_classes): super(AuxiliaryHeadCIFAR, self).__init__() self.features = nn.Sequential(nn.ReLU(inplace=True), nn.AvgPool2d(5, stride=3, padding=0, count_include_pad=False), nn.Conv2d(C, 128, 1, bias=False), nn.BatchNorm2d(128), nn.ReLU(inpla...
class BipedalWalkerExperiment(QDExperiment): def reinit(self): super().reinit() self.env_name = self.config['game']['env_name'] self.init_model() self.update_dimension() def init_model(self): self.model = Model(self.config['game']) def update_dimension(self): ...
def get_model(model_type: str, **kwargs: Union[(int, float)]) -> torch.nn.Module: if (model_type == 'deeptime'): model = deeptime(datetime_feats=kwargs['datetime_feats']) else: raise ValueError(f'Unknown model type {model_type}') return model
def add_model_args(parser): group = parser.add_argument_group('Model configuration') from fairseq.models import ARCH_MODEL_REGISTRY group.add_argument('--arch', '-a', default='fconv', metavar='ARCH', required=True, choices=ARCH_MODEL_REGISTRY.keys(), help='Model Architecture') return group