code
stringlengths
101
5.91M
class Parameter(nn.Module): _parameter: nn.Parameter def __init__(self, data: torch.Tensor): super().__init__() self._parameter = nn.Parameter(data) def forward(self) -> torch.Tensor: return self._parameter def __call__(self) -> torch.Tensor: return super().__call__() ...
class MacroBlock(): def __init__(self, prefix): self.prefix = prefix self.blocks = [] self.combinations = [] self.connections = [] def declare(self, blocks): self.blocks = blocks def connect(self, combinations): self.combinations = combinations def __iter_...
def masked_accuracy(preds, labels, mask): correct_prediction = tf.equal(tf.argmax(preds, 1), tf.argmax(labels, 1)) accuracy_all = tf.cast(correct_prediction, tf.float32) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.reduce_mean(mask) accuracy_all *= mask return tf.reduce_mean(accuracy_all)
class GraphProfiler(): def __init__(self, graph, device_id, ext_name, solver=None, n_run=100, max_measure_execution_time=1, time_scale='m', backward_accum=False): self.graph = graph self.solver = solver self.n_run = n_run self.device_id = str(device_id) self.ext_name = ext_na...
class ArrayDiffStats(): def __init__(self, a, b): self.astat = ArrayStats(a) self.bstat = ArrayStats(b) self.diffstat = ArrayStats((a - b)) def __str__(self): lines = ['', '[diff]', str(self.diffstat), '[left]', str(self.astat), '[right]', str(self.bstat)] return '\n'.joi...
def is_abstract_token(token): return (re.search('^([A-Z]+_)+\\d+$', token) or re.search('^\\d0*$', token))
def test_tf_3d_correct_shape(): p_enc_3d = TFPositionalEncoding3D(170) z = tf.zeros((1, 4, 1, 1024, 170)) assert (p_enc_3d(z).shape == (1, 4, 1, 1024, 170))
class MaxPooling3D(_Pooling3D): _pooling3d_support def __init__(self, pool_size=(2, 2, 2), strides=None, padding='valid', data_format=None, **kwargs): super(MaxPooling3D, self).__init__(pool_size, strides, padding, data_format, **kwargs) def _pooling_function(self, inputs, pool_size, strides, paddin...
def weights_init(init_type='gaussian'): def init_fun(m): classname = m.__class__.__name__ if (((classname.find('Conv') == 0) or (classname.find('Linear') == 0)) and hasattr(m, 'weight')): if (init_type == 'gaussian'): init.normal_(m.weight.data, 0.0, 0.02) eli...
class TsEnum(EnumBuilder, TsBase): def __init__(self, package, enum, args): super(TsEnum, self).__init__(package, enum, args) self.storage_type = TsTypeRef(self.storage_type)
def spc2npow(spectrogram): npow = np.apply_along_axis(_spvec2pow, 1, spectrogram) meanpow = np.mean(npow) npow = (10.0 * np.log10((npow / meanpow))) return npow
def process_sample(aud_path, lable, utt_id, sp, tgt_dict): input = {} output = {} (si, ei) = torchaudio.info(aud_path) input['length_ms'] = int((((si.length / si.channels) / si.rate) / MILLISECONDS_TO_SECONDS)) input['path'] = aud_path token = ' '.join(sp.EncodeAsPieces(lable)) ids = tgt_dic...
def test_rint_big_int(): val = assert_equal(val, int(float(val))) assert_equal(val, np.rint(val))
def register_Ns3ObjectBase_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) cls.add_method('GetAttributeFailSaf...
(DipoleSource) class DipoleSourceImpl(SimSourceImpl): def __init__(self, source: DipoleSource) -> None: self._src = source self._J = None def before_sim(self, sim: FdfdSimProp) -> None: if (self._J is None): self._J = fdfd_solvers.dipole.build_dipole_source(omega=((2 * np.pi)...
def test_Tuple_append(): def f38(builder): content_one = builder.content(0) content_one.append(1.1) content_two = builder.content(1) content_list = content_two.begin_list() content_list.append(1) content_list.append(2) content_list.append(3) content_tw...
.skip('skipping') def test_cylinder(): T = get_function_space('cylinder') u = TrialFunction(T) du = div(grad(u)) assert (du.tolatex() == '\\frac{\\partial^2 u}{\\partial x^2 }+\\frac{1}{x}\\frac{\\partial u}{\\partial x }+\\frac{1}{x^{2}}\\frac{\\partial^2 u}{\\partial y^2 }+\\frac{\\partial^2 u}{\\pa...
def _setup_wrapper(with_cuda): here = os.path.abspath(os.path.dirname(__file__)) lib_dir = os.path.join(here, '..', '..', 'lib') include_dirs = [os.path.join(lib_dir, 'include'), os.path.join(lib_dir, 'include', 'TH')] wrapper_source = '#include <TH/TH.h>\n' if with_cuda: import torch.cuda ...
def _get_dataset_url(name): url = _read_extend_url_file(FASTNLP_EXTEND_DATASET_URL, name) if url: return url filename = DATASET_DIR.get(name, None) if filename: url = (_get_base_url('dataset') + filename) return url else: raise KeyError(f'There is no {name}.')
class TFElectraForSequenceClassification(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
class Partition7(nn.Module): LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[decoder]/ModuleList[block]/T5Block[10]', 'T5ForConditionalGeneration/T5Stack[decoder]/ModuleList[block]/T5Block[11]', 'T5ForConditionalGeneration/T5Stack[decoder]/ModuleList[block]/T5Block[12]', 'T5ForConditionalGeneration/T5Stack[deco...
.parametrize('ctx', ctx_list) .parametrize('seed', [313]) .parametrize('window_size, stride, fft_size', [(16, 8, 16), (16, 4, 16), (16, 8, 32)]) .parametrize('window_type', ['hanning', 'hamming', 'rectangular']) .parametrize('center', [True, False]) .parametrize('pad_mode', ['reflect', 'constant']) .parametrize('as_stf...
def verify_ninja_availability(): if (not is_ninja_available()): raise RuntimeError('Ninja is required to load C++ extensions')
class Supervision_Train(pl.LightningModule): def __init__(self, config): super().__init__() self.config = config self.net = config.net self.automatic_optimization = False self.loss = config.loss self.metrics_train = Evaluator(num_class=config.num_classes) self...
def _read_arraydesc(f): arraydesc = {'arrstart': _read_long(f)} if (arraydesc['arrstart'] == 8): _skip_bytes(f, 4) arraydesc['nbytes'] = _read_long(f) arraydesc['nelements'] = _read_long(f) arraydesc['ndims'] = _read_long(f) _skip_bytes(f, 8) arraydesc['nmax'] = _...
class TracingAdapter(nn.Module): flattened_inputs: Tuple[torch.Tensor] = None inputs_schema: Schema = None outputs_schema: Schema = None def __init__(self, model: nn.Module, inputs, inference_func: Optional[Callable]=None, allow_non_tensor: bool=False): super().__init__() if isinstance(m...
def main(argv): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('contigs_db') parser.add_argument('picklefile') parser.add_argument('-k', '--ksize', type=int, default=31) parser.add_argument('--scaled', type=int, default=10000) args = parser.parse_args(argv) mh = so...
class MLP(nn.Module): def __init__(self, input_size, output_size, layer_sizes, activation, last_layer_activation, dropout_prob): super().__init__() (layers, layer_sizes) = ([], ([input_size] + list(layer_sizes))) for i in range(1, len(layer_sizes)): layers.append(nn.Linear(layer_...
class CrfRnn(nn.Module): def __init__(self, num_labels, num_iterations=5, crf_init_params=None): super(CrfRnn, self).__init__() if (crf_init_params is None): crf_init_params = DenseCRFParams() self.params = crf_init_params self.num_iterations = num_iterations self...
def dictClean_Pickle(b): trans_dict = {} raw_dict = b[0] for (key, val) in raw_dict.items(): trans_dict[key] = modules.dictConvert(val) with open('/data-local/taejin/feat_dir/Fisher/fisher_trans_dict.pickle', 'wb') as handle: pickle.dump(trans_dict, handle, protocol=pickle.HIGHEST_PROTOC...
class IncrementalDecoder(codecs.BufferedIncrementalDecoder): def _buffer_decode(self, data, errors, final): if (errors != 'strict'): raise IDNAError('Unsupported error handling "{0}"'.format(errors)) if (not data): return (u'', 0) if isinstance(data, unicode): ...
def make_non_contiguous(tensor): if (tensor.numel() <= 1): return tensor.clone() osize = list(tensor.size()) for _ in range(2): dim = random.randint(0, (len(osize) - 1)) add = random.randint(4, 15) osize[dim] = (osize[dim] + add) input = tensor.new(torch.Size((osize + [ra...
class ReciprocalMappingExample(props.HasModel): (sigma, sigmaMap, sigmaDeriv) = props.Invertible('Electrical conductivity (S/m)') (rho, rhoMap, rhoDeriv) = props.Invertible('Electrical resistivity (Ohm m)') props.Reciprocal(sigma, rho) def __init__(self, sigma=None, sigmaMap=None, rho=None, rhoMap=None,...
def grid_points(left, top, round_left=None, round_top=None): def round(point, diff, direction, minimum, maximum): assert ((direction is None) or (direction == 'up') or (direction == 'down')) if ((diff > 0) and (direction == 'down')): return max((point - 1), minimum) elif ((diff <...
_repository.replaces_method('Array', 'requires_grad_') _repository.replaces_method('Scalar', 'requires_grad_') def requires_grad_(pv: newast.ProgramVisitor, sdfg: SDFG, state: SDFGState, self: str): if (self not in sdfg.arrays): raise common.DaceSyntaxError(pv, None, 'Array {} is not defined'.format(self)) ...
class Resnet50_128(nn.Module): def __init__(self): super(Resnet50_128, self).__init__() self.meta = {'mean': [131.0912, 103.8827, 91.4953], 'std': [1, 1, 1], 'imageSize': [224, 224, 3]} self.conv1_7x7_s2 = nn.Conv2d(3, 64, kernel_size=[7, 7], stride=(2, 2), padding=(3, 3), bias=False) ...
def network(frame1, frame2, frame3, is_training, reuse=False, scope='netflow'): with tf.variable_scope(scope, reuse=reuse): c3_1_w = tf.get_variable('c3_1_w', shape=[3, 3, 1, 32], initializer=tf.contrib.layers.xavier_initializer(uniform=True)) c3_1_b = tf.get_variable('c3_1_b', shape=[32], initializ...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--task_name', default=None, type=str, required=True, help='The name of the task to train.') parser.add_argument('--cache_dir', default='', type=str, help='Where do you want to store the pre-trained models downloaded from s3') parser.add...
def test_initialize_rdn_1(): _dn = BoostedRDNClassifier() assert (_dn.target == 'None') assert (_dn.n_estimators == 10)
class BTSNmat(SpectralMatrix): def assemble(self, method): (test, trial) = (self.testfunction, self.trialfunction) assert isinstance(test[0], T) assert isinstance(trial[0], SN) h = get_norm_sq(test[0], trial[0], method) (M, N) = (test[0].N, (trial[0].N - 2)) alpha = t...
def _strip_string(string: str) -> str: string = string.replace('\n', '') string = string.replace('\\!', '') string = string.replace('\\\\', '\\') string = string.replace('tfrac', 'frac') string = string.replace('dfrac', 'frac') string = string.replace('\\left', '') string = string.replace('\...
def get_2lvl_model(**kwargs): mel = AugmentMelSTFT(n_mels=128, sr=32000, win_length=800, hopsize=100, n_fft=1024, freqm=48, timem=192, htk=False, fmin=0.0, fmax=None, norm=1, fmin_aug_range=10, fmax_aug_range=2000) net = get_model_passt(arch='stfthop100', input_tdim=3200) model = PasstBasicWrapper(mel=mel, ...
(frozen=True) class PartialTrajectory(): observations: ObservationSequence actions: NDArray rewards: Float32NDArray returns_to_go: Float32NDArray terminals: Float32NDArray timesteps: Int32NDArray masks: Float32NDArray length: int def observation_signature(self) -> Signature: ...
class Feat2Net(nn.Module): def __init__(self, in_dim=1): super(Feat2Net, self).__init__() self.net = archs.v2v2d.V2VModel(in_dim, hyp.feat2_dim).cuda() print(self.net) def forward(self, feat, summ_writer=None, comp_mask=None): total_loss = torch.tensor(0.0).cuda() (B, C, ...
def _parse_comma_separated_option(arguments: list[str], option: str) -> list[str]: index = arguments.index(option) if (',' not in arguments[(index + 1)]): return arguments variables = arguments[(index + 1)].split(',') return ((arguments[:(index + 1)] + variables) + arguments[(index + 2):])
def start_training(): logger.info('Setup config, data and model...') opt = BaseOptions().parse() set_seed(opt.seed) if opt.debug: cudnn.benchmark = False cudnn.deterministic = True dataset_config = dict(dset_name=opt.dset_name, data_path=opt.train_path, v_feat_dirs=opt.v_feat_dirs, q...
def reshape_nd(arr, ndim, dim): if (arr.ndim != 1): raise ValueError('arr must be a 1D array') new_shape = ([1] * ndim) new_shape[dim] = (- 1) return np.reshape(arr, new_shape)
def test_vectorizer_min_df(): test_data = ['abc', 'dea', 'eat'] vect = CountVectorizer(analyzer='char', min_df=1) vect.fit(test_data) assert ('a' in vect.vocabulary_.keys()) assert (len(vect.vocabulary_.keys()) == 6) assert (len(vect.stop_words_) == 0) vect.min_df = 2 vect.fit(test_data)...
.parametrize('device', ['cpu', 'cuda']) def test_compatibility(device, m=4, M=5, L=16, B=2): c2acr = diffsptk.CepstrumToAutocorrelation(M, L) U.check_compatibility(device, c2acr, [], f'nrand -l {(B * (m + 1))}', f'c2acr -m {m} -M {M} -l {L}', [], dx=(m + 1), dy=(M + 1)) U.check_differentiable(device, c2acr,...
class qConformalNoisyExpectedHypervolumeImprovement(qConformalExpectedHypervolumeImprovement, qNoisyExpectedHypervolumeImprovement): def __init__(self, alpha, temp, grid_res, max_grid_refinements, ratio_estimator, optimistic=False, grid_sampler=None, randomized=False, *args, **kwargs): qNoisyExpectedHypervo...
class FunctionEvent(FormattedTimesMixin): def __init__(self, id, name, thread, cpu_start, cpu_end): self.id = id self.name = name self.cpu_interval = Interval(cpu_start, cpu_end) self.thread = thread self.kernels = [] self.count = 1 def append_kernel(self, name, d...
def test_empty_arrays_cartesian(): one = ak.Array([]) two = one = ak.Array([]) with pytest.raises(ValueError) as err: to_list(ak.operations.cartesian([one, two])) assert isinstance(err.value, ValueError) to_list(ak.operations.concatenate([one, two], axis=0))
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...
def keyword_filter(caption) -> bool: keywords = [kw for kws in KEYWORDS.values() for kw in kws] return any(((x in caption) for x in keywords))
def train_epoch(data_loader, model, optimizer, lr_scheduler, evaluator, logger, **kwargs): model.model.train() for (batch_idx, batch) in enumerate(tqdm(data_loader)): gt_answers = batch['answers'] (outputs, pred_answers, pred_answer_page, answer_conf) = model.forward(batch, return_pred_answer=Tr...
def agg_runs(dir, metric_best='auto'): results = {'train': None, 'val': None, 'test': None} results_best = {'train': None, 'val': None, 'test': None} for seed in os.listdir(dir): if is_seed(seed): dir_seed = os.path.join(dir, seed) split = 'val' if (split in os.li...
def register_Ns3SimpleRefCount__Ns3Dot11sIeBeaconTimingUnit_Ns3Empty_Ns3DefaultDeleter__lt__ns3Dot11sIeBeaconTimingUnit__gt___methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::SimpleRefCount< ns3::dot11s::IeBeaconTimingUnit, ns3::empty, ns3::DefaultDeleter< ns3::dot11s::IeBeaco...
.parametrize('separate_eval', [True, False]) def test_concat_ade(separate_eval): test_dataset = ADE20KDataset(pipeline=[], img_dir=osp.join(osp.dirname(__file__), '../data/pseudo_dataset/imgs')) assert (len(test_dataset) == 5) concat_dataset = ConcatDataset([test_dataset, test_dataset], separate_eval=separa...
_model_architecture('ab_transformer_model', 'ab_transformer') def ab_transformer_model(args): args.encoder_layers = getattr(args, 'encoder_layers', 12) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 4096) args.encoder...
def _get_shared_name_to_stage_ops(ops): stage_ops = [op for op in ops if (op.type in STAGE_OP_TYPES)] shared_name_to_stage_ops = {} for stage_op in stage_ops: shared_name = stage_op.get_attr('shared_name') if (shared_name not in shared_name_to_stage_ops): shared_name_to_stage_ops...
def downsample_conv(in_chs, out_chs, kernel_size, stride=1, dilation=1, first_dilation=None, norm_layer=None): norm_layer = (norm_layer or nn.BatchNorm2d) kernel_size = (1 if ((stride == 1) and (dilation == 1)) else kernel_size) first_dilation = ((first_dilation or dilation) if (kernel_size > 1) else 1) ...
def set_vars_to_moving_average(moving_averager): moving_avg_variables = tf.get_collection(tf.GraphKeys.MOVING_AVERAGE_VARIABLES) return tf.group(*[tf.assign(x, moving_averager.average(x)) for x in moving_avg_variables])
def test_consistency(): x = np.logspace((- 30), 300, 200) dataset = np.vstack(((x + 0j), spence(x))).T FuncData(spence, dataset, 0, 1, rtol=1e-14).check()
def p1_fit_plots(): for graph in ['test_acc', 'train_acc', 'train_loss', 'test_loss']: plt.figure() p1(graph)
def resnet18(pretrained=False, encoder=False, **kwargs): if encoder: model = ResNet_Encoder(BasicBlock, [2, 2, 2, 2], **kwargs) else: model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model
def load_checkpoint(fpath): if os.path.isfile(fpath): checkpoint = torch.load(fpath, map_location=torch.device('cpu')) print("=> Loaded checkpoint '{}'".format(fpath)) return checkpoint else: raise ValueError("=> No checkpoint found at '{}'".format(fpath))
def update_function_order_in_functsions_yaml(): d = utils.load_yaml_ordered(open(join(here, 'functions.yaml'), 'r')) order_info_by_id = {} order_info = OrderedDict() duplicated = {} missing = {} for (cat_name, cat_info) in d.items(): for (func_name, func_info) in d[cat_name].items(): ...
def build_spk_hashtable(base_folder_dm, sample_rate): wsj0_utterances = glob.glob(os.path.join(base_folder_dm, '**/*.wav'), recursive=True) spk_hashtable = {} for utt in wsj0_utterances: spk_id = Path(utt).stem[:3] assert (torchaudio.info(utt).sample_rate == sample_rate) if (spk_id n...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--video', default='webcam', type=str) parser.add_argument('--output', default='output', type=str) parser.add_argument('--inres', default='512,512', type=str) parser.add_argument('--outres', default='1080,1920', type=str) parser....
def is_parallel(model): return isinstance(model, (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel))
def get_path_info(environ, charset='utf-8', errors='replace'): path = wsgi_get_bytes(environ.get('PATH_INFO', '')) return to_unicode(path, charset, errors, allow_none_charset=True)
def _run_ninja_build(build_directory: str, verbose: bool, error_prefix: str) -> None: command = ['ninja', '-v'] num_workers = _get_num_workers(verbose) if (num_workers is not None): command.extend(['-j', str(num_workers)]) env = os.environ.copy() if (IS_WINDOWS and ('VSCMD_ARG_TGT_ARCH' not ...
def vsd(R_est, t_est, R_gt, t_gt, model, depth_test, K, delta, tau, cost_type='tlinear'): im_size = (depth_test.shape[1], depth_test.shape[0]) depth_est = renderer.render(model, im_size, K, R_est, t_est, clip_near=100, clip_far=10000, mode='depth') depth_gt = renderer.render(model, im_size, K, R_gt, t_gt, c...
class PoseFeature(nn.Module): def __init__(self, cfg, input_dim, hidden_dim=128, num_layers=4): super(PoseFeature, self).__init__() self.CoordEncoder = CoordEncoder(cfg, hidden_dim, num_layers) self.conv1 = nn.Sequential(nn.Conv2d(input_dim, hidden_dim, kernel_size=(3, 3), padding=(1, 1)), n...
class PythonCodeExecutor(object): Py_single_input = 256 Py_file_input = 257 Py_eval_input = 258 def malloc(self, size): chunk = gdb.parse_and_eval(('(void *) malloc((size_t) %d)' % size)) pointer = pointervalue(chunk) if (pointer == 0): raise gdb.GdbError('No memory c...
def _search_src_or_doc(what, string, extra1='', extra2='', extra3='', extra4='', extra5='', **kwargs): interact = kwargs.get('interact', True) path_re = kwargs.get('path_re', '') module = kwargs.get('module', 'sage') whole_word = kwargs.get('whole_word', False) ignore_case = kwargs.get('ignore_case'...
class StreamElementsSpeech(VoiceBase): def _setup(self) -> None: def _speech(self, text: str, voice: str, _: int=0) -> bool: tts_url = f' response = requests.get(tts_url) if (response.status_code == 200): with open('speech.mp3', 'wb') as f: f.write(response.co...
def code_to_sequence(code, code_dict, collapse_code): if collapse_code: prev_c = None sequence = [] for c in code: if ((c in code_dict) and (c != prev_c)): sequence.append(code_dict[c]) prev_c = c else: sequence = [code_dict[c] for c in...
class GoldenRatio(Constant): def __init__(self, name='golden_ratio'): conversions = dict(mathematica='(1+Sqrt[5])/2', gp='(1+sqrt(5))/2', maple='(1+sqrt(5))/2', maxima='(1+sqrt(5))/2', pari='(1+sqrt(5))/2', octave='(1+sqrt(5))/2', kash='(1+Sqrt(5))/2', giac='(1+sqrt(5))/2') Constant.__init__(self, n...
def annotate_heatmap(im, data=None, valfmt='{x:.2f}', textcolors=('black', 'white'), threshold=None, **textkw): if (not isinstance(data, (list, np.ndarray))): data = im.get_array() if (threshold is not None): threshold = im.norm(threshold) else: threshold = (im.norm(data.max()) / 2.0...
class Seq2SeqQuestionAnsweringModelOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None start_logits: torch.FloatTensor = None end_logits: torch.FloatTensor = None past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = N...
class SamPreTrainedModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class NewbobAbs(LearningRateControl): def load_initial_kwargs_from_config(cls, config): kwargs = super(NewbobAbs, cls).load_initial_kwargs_from_config(config) kwargs.update({'error_threshold': config.float('newbob_error_threshold', (- 0.01))}) return kwargs def __init__(self, error_thres...
class MultiPeriodDiscriminator(torch.nn.Module): def __init__(self, h): super(MultiPeriodDiscriminator, self).__init__() self.mpd_reshapes = h.mpd_reshapes print('mpd_reshapes: {}'.format(self.mpd_reshapes)) discriminators = [DiscriminatorP(h, rs, use_spectral_norm=h.use_spectral_nor...
def low_weight_bases(N, p, m, NN, weightbound): generators = [] for k in range(2, (weightbound + 2), 2): b = ModularForms(N, k, base_ring=Zmod((p ** m))).q_expansion_basis(prec=NN) generators.append(list(b)) return generators
class CMRC2018Loss(LossBase): def __init__(self, target_start=None, target_end=None, context_len=None, pred_start=None, pred_end=None, reduction='mean'): super().__init__() assert (reduction in ('mean', 'sum')) self._init_param_map(target_start=target_start, target_end=target_end, context_le...
class ListOffsetArray(ListOffsetMeta[Content], Content): def __init__(self, offsets, content, *, parameters=None): if ((not isinstance(offsets, Index)) and (offsets.dtype in (np.dtype(np.int32), np.dtype(np.uint32), np.dtype(np.int64)))): raise TypeError("{} 'offsets' must be an Index with dtype...
def train(model, optimizer, loader, device): model.train() total_loss = 0 for data in loader: optimizer.zero_grad() x = data.x.to(device) out = model(x) loss = F.l1_loss(out, x, reduction='mean') loss.backward() total_loss += loss.item() optimizer.step...
def p2(): csv = '4partitions.csv' out_file_name = 'output.png' out_file_name = os.path.join('.', out_file_name) df = pd.read_csv(csv).query("dataset == 'cifar100'").query('epoch == 200') ax = sns.barplot(x='epoch', y='test_acc', hue='alg', data=df) model = pd.unique(df.model) assert (len(mod...
class ComplexConv2d(nn.Module): def __init__(self, in_channel, out_channel, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, **kwargs): super().__init__() self.conv_re = nn.Conv2d(in_channel, out_channel, kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups...
(for_each_device=True) def cupy_launch(strFunction, strKernel): return cupy.RawKernel(strKernel, strFunction)
('/dialog_status/<cid>', methods=['GET']) def showtree(cid): try: ctx = dmgr.get_ctx(cid) if (not ctx): return json.dumps({'Info': 'session not initialized.'}) tree_data = ctx.tree_manager.task_tree.tree_show() except Exception as e: msg = printException() ret...
def mobius_matvec(m, x, *, c=1.0): c = torch.as_tensor(c).type_as(x) return _mobius_matvec(m, x, c)
.parametrize('ctx, func_name', ctxs) .parametrize('seed', [313]) .parametrize('shape', shapes) def test_relu_forward_backward(seed, ctx, func_name, shape): from nbla_test_utils import cap_ignore_region, function_tester rng = np.random.RandomState(seed) inputs = [cap_ignore_region((rng.randn(*shape).astype(n...
def convert_dense(vars, source_name, target_name): weight = vars[(source_name + '/weight')].value().eval() bias = vars[(source_name + '/bias')].value().eval() dic = {'weight': weight.transpose((1, 0)), 'bias': bias} dic_torch = {} for (k, v) in dic.items(): dic_torch[((target_name + '.') + k...
def power_of_two_quantization(activation_n_bits: int, quantization_params: dict) -> Callable: activation_threshold = quantization_params.get(THRESHOLD) activation_is_signed = quantization_params.get(SIGNED) if (activation_threshold is None): Logger.error('Activation threshold is None') if (activ...
def post_tokenization_processing(document_state: DocumentState, subword_tokenizer, max_segment_len=4096): split_into_segments(document_state, max_segment_len, document_state.sentence_end, document_state.token_end) sent_len_list = [len(sent) for sent in document_state.segments] document_state.sent_len_list =...
class SLSQP(WrappedOptimizerBase): def __init__(self, options: dict=None, callback=default_callback): super().__init__() if (options is None): options = {} self.tol = options.get('tol', 1e-06) if ('tol' in options): options.pop('tol') self.options = op...
_zero_only def dump_yaml(cfg, yaml_dict, time_tag): distiller = dict() for attr in dir(cfg): if ((not callable(getattr(cfg, attr))) and (not attr.startswith('_'))): distiller[attr] = getattr(cfg, attr) dump_dict = yaml_dict for key in distiller: if (key in ['activation_fn', '...
def convert_example_to_features(example, max_seq_length, tokenizer): tokens_a = example.tokens_a tokens_b = example.tokens_b raw_label = example.raw_label if (SEP_TOKEN not in tokens_b): logger.info('\n** ** * tokens_b: ', tokens_b) _truncate_seq_pair(tokens_a, tokens_b, (max_seq_length - 3)...