code
stringlengths
101
5.91M
def replace_tail(tail): xxs_tail = re.compile(".*(Person.) .* (Person.)\\'s .*", re.I) xy_tail = re.compile('.*(Person.) .* (Person.).*', re.I) px_tail = re.compile('.*(Person.).*', re.I) a_underline = re.compile('.* a ___.*') the_underline = re.compile('.* the ___.*') some_underline = re.compil...
def conv3x3(in_planes, out_planes, groups=1, stride=1): return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False, groups=groups)
class BigDLMetric(object): def __init__(self, val_method, outputs, labels): self.val_method = val_method self.outputs = outputs self.labels = labels
def list_detectors(): print("\nAVAILABLE DETECTORS (for fc.detector(s,'DETECTOR')):\n") print_dirs(os.path.join(data_path, 'Detectors'))
def enable_multi_fs_save(save_func: Callable) -> Callable: (save_func) def fs_save(obj, path, *args, **kwargs): from bigdl.dllib.utils.file_utils import is_local_path if is_local_path(path): return save_func(obj, path, *args, **kwargs) else: import uuid ...
def readme(): with open('README.rst', encoding='utf-8') as f: content = f.read() return content
def training_params(is_gcloud=False, output_dir=None): if (not output_dir): output_dir = util.construct_experiment_output_dir(__file__) num_gpus = 1 stop_after = 7 dynamic_batch_size = {2: 128, 3: 128, 4: 64, 5: 32, 6: 16, 7: 6, 8: 3} imgs_per_phase = 384000 dynamic_steps_per_phase = {ph...
class FlaxRobertaPreLayerNormForCausalLM(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
def set_accelerator(accel_obj): global accelerator _validate_accelerator(accel_obj) if (accel_logger is not None): accel_logger.info(f'Setting accelerator to {accel_obj._name} (model specified)') accelerator = accel_obj
class QUVA(data.Dataset): def __init__(self, dataset_path, subset, sample_duration, n_samples_for_each_video=10, spatial_transform=None, target_transform=None, get_loader=get_default_video_loader): (self.data, self.max_n_frames) = make_dataset(dataset_path, subset, sample_duration, n_samples_for_each_video)...
_model def hardcorenas_c(pretrained=False, **kwargs): arch_def = [['ds_r1_k3_s1_e1_c16_nre'], ['ir_r1_k5_s2_e3_c24_nre', 'ir_r1_k5_s1_e3_c24_nre_se0.25'], ['ir_r1_k5_s2_e3_c40_nre', 'ir_r1_k5_s1_e3_c40_nre', 'ir_r1_k5_s1_e3_c40_nre', 'ir_r1_k5_s1_e3_c40_nre'], ['ir_r1_k5_s2_e4_c80', 'ir_r1_k5_s1_e6_c80_se0.25', 'ir...
def vgg_johnson(vgg, img, rec): ff = vgg.fw_relu(img, 4)[(- 1)] fn = vgg.fw_relu(rec, 4)[(- 1)] vgg_imgs = [] vgg_imgs.append((ff - fn).pow(2).mean(dim=1, keepdim=True)) loss = vgg_imgs[(- 1)].mean() return (loss, vgg_imgs)
class NMTFlow(Flow): def __init__(self, levels, num_steps, features, src_features, factors, hidden_features=None, inverse=False, transform='affine', coupling_type='conv', kernel_size=3, rnn_mode='LSTM', heads=1, pos_enc='add', max_length=100, dropout=0.0): super(NMTFlow, self).__init__(inverse) asse...
def LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True, export=False): if ((not export) and torch.cuda.is_available()): try: from apex.normalization import FusedLayerNorm return FusedLayerNorm(normalized_shape, eps, elementwise_affine) except ImportError: ...
class RecurrentTransformerEncoder(Module): def __init__(self, layers, norm_layer=None, event_dispatcher=''): super(RecurrentTransformerEncoder, self).__init__() self.layers = ModuleList(layers) self.norm = norm_layer self.event_dispatcher = EventDispatcher.get(event_dispatcher) d...
class GradientDescent(): def __init__(self, problem: MinimizationProblem, variable: TensorList, step_length: float, momentum: float=0.0, debug=False, plotting=False, fig_num=(10, 11)): self.problem = problem self.x = variable self.step_legnth = step_length self.momentum = momentum ...
def extract_audio(dataset_json_file, mdl, tar_path, total_split=16): if (os.path.exists(tar_path) == False): os.makedirs(tar_path) with open(dataset_json_file, 'r') as fp: data = json.load(fp) num_sample = len(data) num_each_split = math.ceil((num_sample / total_split)) c...
class DBSNLoss_Pretrain(nn.Module): def __init__(self): super(DBSNLoss_Pretrain, self).__init__() def forward(self, target, mu, sigma_mu, sigma_n, sigma_y): loss = 0 eps = 1e-06 target = target.detach() mu = mu.detach() t1 = (((target - mu) ** 2) / sigma_y) ...
def cook_test(test, xxx_todo_changeme, eff=None, n=4): (reflen, refmaxcounts) = xxx_todo_changeme (testlen, counts) = precook(test, n, True) result = {} if (eff == 'closest'): result['reflen'] = min(((abs((l - testlen)), l) for l in reflen))[1] else: result['reflen'] = reflen res...
def main(args): import glob import random import numpy as np import json mpnn_alphabet = 'ACDEFGHIKLMNPQRSTVWYX' mpnn_alphabet_dict = {'A': 0, 'C': 1, 'D': 2, 'E': 3, 'F': 4, 'G': 5, 'H': 6, 'I': 7, 'K': 8, 'L': 9, 'M': 10, 'N': 11, 'P': 12, 'Q': 13, 'R': 14, 'S': 15, 'T': 16, 'V': 17, 'W': 18, ...
def callback(lcl, glb): total = (sum(lcl['episode_rewards'][(- 101):(- 1)]) / 100) totalt = lcl['t'] is_solved = ((totalt > 2000) and (total >= (- 50))) return is_solved
def make_mujoco_env(env_id, seed, reward_scale=1.0): rank = MPI.COMM_WORLD.Get_rank() myseed = ((seed + (1000 * rank)) if (seed is not None) else None) set_global_seeds(myseed) env = gym.make(env_id) logger_path = (None if (logger.get_dir() is None) else os.path.join(logger.get_dir(), str(rank))) ...
def apply_momentum(updates, params=None, momentum=0.9): if (params is None): params = updates.keys() updates = OrderedDict(updates) for param in params: value = param.get_value(borrow=True) velocity = theano.shared(np.zeros(value.shape, dtype=value.dtype), broadcastable=param.broadca...
def shufflenet_v2_x1_0(pretrained=False, progress=True, quantize=False, **kwargs): return _shufflenetv2('shufflenetv2_x1.0', pretrained, progress, quantize, [4, 8, 4], [24, 116, 232, 464, 1024], **kwargs)
def filter_greater_than(boxlist, thresh, scope=None): with tf.name_scope(scope, 'FilterGreaterThan'): if (not isinstance(boxlist, box_list.BoxList)): raise ValueError('boxlist must be a BoxList') if (not boxlist.has_field('scores')): raise ValueError("input boxlist must have ...
class TestPostCSEOptimizer(unittest.TestCase): def setUpClass(self): build_fake_yaml() import tensorflow as tf self.enable_s8 = bool(((tf.version.VERSION.find('1.15.0-up') != (- 1)) or (tf.version.VERSION >= '2.1.0'))) def tearDownClass(self): os.remove('fake_yaml.yaml') _ran...
def clear_double_syspool(vrblvl=0): if (vrblvl > 0): print('in clear_double_syspool ...') phc = get_phcfun() adim = pointer(c_int32(0)) bbb = pointer(c_int32(0)) ccc = pointer(c_double(0.0)) vrb = c_int32(vrblvl) if (vrblvl > 0): print('-> clear_double_syspool calls phc', end...
class BartForQuestionAnswering(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
def test_bbox2result_kitti2d(): (data_root, ann_file, classes, pts_prefix, pipeline, modality, split) = _generate_kitti_dataset_config() kitti_dataset = KittiDataset(data_root, ann_file, split, pts_prefix, pipeline, classes, modality) bboxes = np.array([[[46.1218, (- 4.6496), (- 0.9275), 0.5316, 0.5], [33.3...
_inducing_shape.register(InducingVariables) def _getter(x): assert (not isinstance(InducingVariables, MultioutputInducingVariables)) return list(x.Z.shape)
class Block(nn.Module): def __init__(self, in_planes, out_planes, pool_method, stride): super(Block, self).__init__() self.branches = nn.ModuleList([nn.Sequential(_make_conv(in_planes, out_planes, kernel_size=1, padding=0), _make_conv(out_planes, out_planes, stride=stride)), nn.Sequential(_make_conv...
class MinPooling(_AbstractPoolingBase): def __init__(self, kernel_size, keep_size=True, name=None, deterministic=False, random_state=None): super(MinPooling, self).__init__(kernel_size=kernel_size, keep_size=keep_size, name=name, deterministic=deterministic, random_state=random_state) def _pool_image(se...
class ACubeNet(nn.Module): def __init__(self, args, conv=common.default_conv): super(ACubeNet, self).__init__() n_resgroups = args.n_resgroups n_resblocks = args.n_resblocks n_feats = args.n_feats kernel_size = 3 reduction = args.reduction scale = args.scale[0...
class Discriminator(nn.Module): def __init__(self, inhw, c1_channels=64, c2_channels=128, c3_channels=256, c4_channels=512, i_channels_in_2=True): super().__init__() self.c1_channels = c1_channels if i_channels_in_2: self.c2_channels = (self.c1_channels * 2) self.c3_c...
def get_all_content_words(sentences, N, tokenize): all_words = [] if tokenize: for s in sentences: all_words.extend([stemmer.stem(r) for r in tokenizer.tokenize(s)]) elif isinstance(sentences, list): all_words = sentences[0].split() else: all_words = sentences.split()...
class CuIRFFTOp(Op): __props__ = () def output_type(self, inp): return GpuArrayType(inp.dtype, broadcastable=([False] * (inp.type.ndim - 1)), context_name=inp.type.context_name) def make_node(self, inp, s=None): if (not scikits_cuda_available): raise RuntimeError('skcuda is neede...
class MultiViewPreprocessing(TransformerMixin): def __init__(self, preprocessing_list): self.preprocessing_list = preprocessing_list def fit(self, views, y=None): if (len(self.preprocessing_list) == 1): self.preprocessing_list = (self.preprocessing_list * len(views)) elif (le...
class TLU(nn.LayerBase): def __init__(self, in_ch, dtype=None, **kwargs): self.in_ch = in_ch if (dtype is None): dtype = nn.floatx self.dtype = dtype super().__init__(**kwargs) def build_weights(self): self.tau = tf.get_variable('tau', (self.in_ch,), dtype=sel...
(x='double[::1]', acc_container='AcceleratorContainer', digest=str, returns='AcceleratorContainer') def fetch_acc(x): digest = AcceleratorContainer.hash_interpolation_domain(x) acc_container = acc_store.get(digest) if (acc_container is None): acc_container = AcceleratorContainer(x) else: ...
.slow def test_harmonic_oscillator_vmc_random_particle(caplog): model_omega = 5 spring_constant = 1.5 nchains = (100 * jax.local_device_count()) nburn = 100 nepochs = 100 nsteps_per_param_update = 5 std_move = 0.25 learning_rate = 0.001 (log_psi_model, params, random_particle_positio...
def histogram(iterable, k=10, interval=None, *args, **kwargs): if ('range' in kwargs): interval = kwargs['range'] a = (iterable if isinstance(iterable, list) else list(iterable)) r = (interval or (min(a), max(a))) k = max(int(k), 1) w = (float(((r[1] - r[0]) + 1e-06)) / k) h = [[] for i ...
def compute_exact(a_gold, a_pred): return int((normalize_answer(a_gold) == normalize_answer(a_pred)))
def set_default_adaptor_args(args): args.adaptor_n_layers = getattr(args, 'adaptor_n_layers', 3) args.adaptor_kernel_size = getattr(args, 'adaptor_kernel_size', 3) args.adaptor_stride = getattr(args, 'adaptor_stride', 2) args.adaptor_layerdrop = getattr(args, 'adaptor_layerdrop', 0.0) args.adaptor_l...
def test_reference_wrapper(): assert (m.refwrap_builtin(42) == 420) assert (m.refwrap_usertype(UserType(42)) == 42) assert (m.refwrap_usertype_const(UserType(42)) == 42) with pytest.raises(TypeError) as excinfo: m.refwrap_builtin(None) assert ('incompatible function arguments' in str(excinfo...
def RRSE_np(pred, true, mask_value=None): if (mask_value != None): mask = np.where((true > mask_value), True, False) true = true[mask] pred = pred[mask] mean = true.mean() return np.divide(np.sqrt(np.sum(((pred - true) ** 2))), np.sqrt(np.sum(((true - mean) ** 2))))
class Custom_Dataset(Dataset): def __init__(self, tokenizer, dataset_name, valid_subset_path, type_path, input_length, output_length, args): self.args = args self.tokenizer = tokenizer self.input_length = input_length self.output_length = output_length self.dataset_name = dat...
class StopOnTokens(StoppingCriteria): def __init__(self, min_length: int, start_length: int, stop_token_id: List[int]): self.min_length = min_length self.start_length = start_length self.stop_token_id = stop_token_id def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTens...
def get_tsdataset(): df = get_ts_df() return TSDataset.from_pandas(df, dt_col='datetime', target_col=['value 1', 'value 2'], extra_feature_col=['extra feature 1', 'extra feature 2'], id_col='id')
def main(image_root: Path, output_root: Path, transform: str, plot_subdir: Path, moment: str, log: bool, vmin: float, vmax: float, img_dirs: List[str], overwrite: bool, num_workers: int, experiment: str, fraction: float, zoom: bool, diff: bool, fixed_height: int): output_dir = (output_root / 'frequency_analysis') ...
class PreOptimization(): def __init__(self, model, new_api, device): self.model = model if (version1_gte_version2(tf.version.VERSION, '2.1.0') or version1_eq_version2(tf.version.VERSION, '1.15.0-up3')): self.optimization = {'pruning': True, 'shape': True, 'constfold': False, 'arithmetic'...
_grad() def test(model, x, evaluator, y, train_idx, val_idx, test_idx, out=None): model.eval() out = (model(x) if (out is None) else out) pred = out.argmax(dim=(- 1), keepdim=True) train_acc = evaluator.eval({'y_true': y[train_idx], 'y_pred': pred[train_idx]})['acc'] val_acc = evaluator.eval({'y_tru...
def test_no_unlinked_images(): linked_images = metadata['filename'] all_images = os.listdir('images') assert (set(all_images).difference(set(linked_images)) == set(['FAFA-A1BF-49A8-A1D3-66FAFA41B7345D.jpg']))
def test_dice_lose(): from mmseg.models import build_loss loss_cfg = dict(type='DiceLoss', reduction='none', class_weight=[1.0, 2.0, 3.0], loss_weight=1.0, ignore_index=1, loss_name='loss_dice') dice_loss = build_loss(loss_cfg) logits = torch.rand(8, 3, 4, 4) labels = (torch.rand(8, 4, 4) * 3).long(...
class kitenet(nn.Module): def __init__(self): super(kitenet, self).__init__() self.encoder1 = nn.Conv2d(1, 32, 3, stride=1, padding=1) self.encoder2 = nn.Conv2d(32, 64, 3, stride=1, padding=1) self.encoder3 = nn.Conv2d(64, 128, 3, stride=1, padding=1) self.decoder3 = nn.Conv2...
def save_pkl(filename, save_object): writer = open(filename, 'wb') pickle.dump(save_object, writer) writer.close()
class GraphEmbedder(nn.Module): def __init__(self, hidden_layer_size, edge_names, embedding_dim, num_layers): super().__init__() self.ggnn = ggnn_sparse.GGNNSparse(ggnn_base.GGNNParams(hidden_layer_size, edge_names, num_layers)) mlp_project_up = mlp.get_mlp(mlp.MlpParams(hidden_layer_size, e...
def mask_cross_entropy(pred, target, label, reduction='mean', avg_factor=None, class_weight=None, ignore_index=None, **kwargs): assert (ignore_index is None), 'BCE loss does not support ignore_index' assert ((reduction == 'mean') and (avg_factor is None)) num_rois = pred.size()[0] inds = torch.arange(0,...
def valid_dataloader_creator(config): import torch from torch.utils.data import DataLoader RandomDataset = gen_RandomDataset() return DataLoader(RandomDataset(size=400), batch_size=config['batch_size'], shuffle=True)
def build_backbone_layers(backbone_net, layers, pretrained, backbone_output_stride=8, convert_bn=None): if (backbone_net == 'pyconvhgresnet'): if (layers == 50): backbone = pyconvhgresnet.pyconvhgresnet50() elif (layers == 101): backbone = pyconvhgresnet.pyconvhgresnet101() ...
class LazyFrames(object): def __init__(self, frames): self._frames = frames self._out = None def _force(self): if (self._out is None): self._out = np.concatenate(self._frames, axis=(- 1)) self._frames = None return self._out def __array__(self, dtype=N...
class DeformRoIPoolFunction(Function): def symbolic(g, input, rois, offset, output_size, spatial_scale, sampling_ratio, gamma): return g.op('MMCVDeformRoIPool', input, rois, offset, pooled_height=output_size[0], pooled_width=output_size[1], spatial_scale=spatial_scale, sampling_ratio=sampling_ratio, gamma=g...
class RandomRotate(object): def __init__(self, degree): self.degree = degree def __call__(self, img, mask): rotate_degree = (((random.random() * 2) * self.degree) - self.degree) return (tf.affine(img, translate=(0, 0), scale=1.0, angle=rotate_degree, resample=Image.BILINEAR, fillcolor=(0...
def Add_Window_Horizon(data, window=3, horizon=1, single=False): length = len(data) end_index = (((length - horizon) - window) + 1) X = [] Y = [] index = 0 if single: while (index < end_index): X.append(data[index:(index + window)]) Y.append(data[(((index + window...
def pyconvresnet34(pretrained=False, **kwargs): model = PyConvResNet(PyConvBasicBlock2, [3, 4, 6, 3], **kwargs) if pretrained: raise NotImplementedError('Not available the pretrained model yet!') return model
class CollisionObjectManager(object): def __init__(self, root='/world', listener=None, max_dt=1.0): self.objs = {} self.urdfs = {} self.frames = {} if (listener is None): self.listener = tf.TransformListener() else: self.listener = listener sel...
def get_vehicle_dyn_scenario() -> SimContext: scenario_name = 'USA_Lanker-1_1_T-1' (scenario, planning_problem_set) = load_commonroad_scenario(scenario_name) x0_p1 = VehicleStateDyn(x=0, y=0, psi=deg2rad(0), vx=kmh2ms(50), delta=0) x0_p2 = VehicleStateDyn(x=25, y=(- 10), psi=deg2rad(90), vx=kmh2ms(0), d...
class ActionPublisher(): def __init__(self): if rospy.get_param('train_mode'): raise Exception('This node should be used solely in eval mode!') rospy.init_node('action_publisher', anonymous=True) self._step_size = rospy.get_param('step_size') self._update_rate = rospy.get...
def to_cuda(samples, targets, device): samples = samples.to(device, non_blocking=True) targets = [{k: v.to(device, non_blocking=True) for (k, v) in t.items()} for t in targets] return (samples, targets)
def IoU(r1, r2): (x11, y11, w1, h1) = r1 (x21, y21, w2, h2) = r2 x12 = ((x11 + w1) - 1) y12 = ((y11 + h1) - 1) x22 = ((x21 + w2) - 1) y22 = ((y21 + h2) - 1) x_overlap = max(0, (min(x12, x22) - max(x11, x21))) y_overlap = max(0, (min(y12, y22) - max(y11, y21))) I = ((1.0 * x_overlap) ...
def random_resize(data_loader, exp, epoch, rank, is_distributed): tensor = torch.LongTensor(1).cuda() if is_distributed: synchronize() if (rank == 0): if (epoch > (exp.max_epoch - 10)): size = exp.input_size else: size = random.randint(*exp.random_size) ...
def get_data_parallel_world_size(): return torch.distributed.get_world_size(group=get_data_parallel_group())
class CheckpointModule(nn.Module): def __init__(self, module, num_segments=1): super(CheckpointModule, self).__init__() assert ((num_segments == 1) or isinstance(module, nn.Sequential)) self.module = module self.num_segments = num_segments def forward(self, x): if (self.n...
def test_empty_list_assignment(): run_cell('a = [5]') run_cell('b = a + [6]') run_cell('logging.info(b)') run_cell('a = [6]') run_cell('logging.info(b)') assert_detected('`b` depends on stale `a`') run_cell('b = a + [7]') run_cell('a = []') run_cell('logging.info(b)') assert_dete...
class resnet_block(nn.Module): def __init__(self, channel, kernel, stride, padding): super(resnet_block, self).__init__() self.channel = channel self.kernel = kernel self.strdie = stride self.padding = padding self.conv1 = nn.Conv2d(channel, channel, kernel, stride, 0...
def tf_top_k_top_p_filtering(*args, **kwargs): requires_backends(tf_top_k_top_p_filtering, ['tf'])
_gs_scheduler('base_gs') class BaseGsSchedule(object): def __init__(self, args): self.tau_max = args.gumbel_softmax_max self.tau_r = args.gumbel_softmax_tau_r self.tau_min = args.gumbel_softmax_min self.update_freq = args.gumbel_softmax_update_freq self.step_update(0) def...
def _unitary(norm): if (norm not in (None, 'ortho', 'no_norm')): raise ValueError(("Invalid value %s for norm, must be None, 'ortho' or 'no norm'" % norm)) return norm
def parse_args(): parser = argparse.ArgumentParser(description='Synthesize images with pre-trained models.') parser.add_argument('model_name', type=str, help='Name to the pre-trained model.') parser.add_argument('--save_dir', type=str, default=None, help='Directory to save the results. If not specified, the...
_task('masked_lm', dataclass=MaskedLMConfig) class MaskedLMTask(FairseqTask): cfg: MaskedLMConfig def __init__(self, cfg: MaskedLMConfig, dictionary=None): super().__init__(cfg) self.dictionary = (dictionary or self.load_dict(cfg)) self.mask_idx = self.dictionary.add_symbol('<mask>') ...
def efficientnet_b1(pretrained=False, **kwargs): model = _gen_efficientnet('efficientnet_b1', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs) return model
class Space(): def __init__(self, shape=(), dtype=np.int32, domain=(0, 1), categorical=False, name=None): self.name = name (self.shape, self.dtype) = (shape, dtype) (self.categorical, (self.lo, self.hi)) = (categorical, domain) def is_discrete(self) -> bool: return np.issubdtype(...
def create_stem(in_chs, out_chs, stem_type='', preact=True, conv_layer=None, norm_layer=None): stem = OrderedDict() assert (stem_type in ('', 'fixed', 'same', 'deep', 'deep_fixed', 'deep_same')) if ('deep' in stem_type): mid_chs = (out_chs // 2) stem['conv1'] = conv_layer(in_chs, mid_chs, ke...
def upSampleConv_Res(nin, nout, upscale=2, bias=False, BN=False, ws=False, activ=nn.LeakyReLU(0.2)): return nn.Sequential(nn.Upsample(scale_factor=upscale), ResidualConv(nin, nout, bias=bias, BN=BN, ws=ws, activ=activ))
def make_parser(): parser = argparse.ArgumentParser('YOLOX Eval') parser.add_argument('-expn', '--experiment-name', type=str, default=None) parser.add_argument('-n', '--name', type=str, default=None, help='model name') parser.add_argument('--dist-backend', default='nccl', type=str, help='distributed bac...
_config def il_source_rmt(): cfg = {} cfg['training'] = {'sources': ['rgb_filled', 'map', 'target'], 'sources_as_dict': True}
def simple_algorithm_plot(experiment_name, data_path=_DEFAULT_DATA_PATH): df = load_data(experiment_name, data_path) plt_df = df.groupby(['t', 'agent']).agg({'instant_regret': np.mean}).reset_index() p = (((((gg.ggplot(plt_df) + gg.aes('t', 'instant_regret', colour='agent')) + gg.geom_line(size=1.25, alpha=...
def AutogradSkipConnectRNN(num_layers=1, batch_first=False, bidirectional=False, lstm=False): rec_factory = SkipConnectRecurrent if bidirectional: layer = (rec_factory(), rec_factory(reverse=True)) else: layer = (rec_factory(),) func = StackedRNN(layer, num_layers, lstm=lstm) def for...
class DictionaryMatcher(TaggingRule): def __init__(self, name, terms, uncased=False, match_lemmas=False, i_label='I', abs_label='ABS'): self.name = name self.uncased = uncased self.match_lemmas = match_lemmas self.i_label = i_label self.abs_label = abs_label self._loa...
def resource_to_bytes(resource_str): if (not resource_str): return resource_str matched = re.compile('([0-9]+)([a-z]+)?').match(resource_str.lower()) fraction_matched = re.compile('([0-9]+\\.[0-9]+)([a-z]+)?').match(resource_str.lower()) if fraction_matched: invalidInputError(False, 'Fra...
def _preprocess_commonsense_qa(path): data = [] candidates = ['A', 'B', 'C', 'D', 'E'] with open(path) as f: for (sample_index, line) in enumerate(f): sample = json.loads(line) question = sample['question']['stem'].strip() choices = [c['text'] for c in sample['que...
class MultitaskLossBase(nn.Module): def __init__(self): super().__init__() self._sigmoid_xent_loss = SigmoidCrossEntropy() self._multilabel_sigmoid_xent_loss = MultilabelSigmoidCrossEntropy() self._batched_xent_loss = nn.CrossEntropyLoss() def _mse_loss(self, pred, label): ...
def process_yaml_config(global_config, local_configs, default_config): pruners_info = [] default_all = global_config for key in default_config.keys(): default_all[key] = reset_none_to_default(default_all, key, default_config[key]) if (len(local_configs) == 0): update_params(default_all) ...
def _latency_errors(data, num_steps, threshold, tau, first_spike_time, normalize): if ((threshold <= 0) or (threshold >= 1)): raise Exception('Threshold must be between 0 and 1.') if (tau <= 0): raise Exception('``tau`` must be greater than 0.') if (first_spike_time and num_steps and (first_...
def var_gauss(t, y, w, freq, dphi): gaussian = (lambda x: np.exp(((- 0.5) * (x ** 2)))) var = 0.0 for (i, (T, Y, W)) in enumerate(zip(t, y, w)): mbar = 0.0 wtot = 0.0 for (j, (T2, Y2, W2)) in enumerate(zip(t, y, w)): dph = dphase(abs((T2 - T)), freq) wgt = (W2...
class Block(nn.Module): def __init__(self, in_channels, norm_args=None, act_args=None, aggr_args={'feature_type': 'dp_fj', 'reduction': 'max'}, group_args={'NAME': 'ballquery'}, conv_args=None, expansion=1, use_res=True, num_posconvs=2, **kwargs): super().__init__() self.use_res = use_res mi...
def pair_id_to_image_ids(pair_id): image_id2 = (pair_id % ) image_id1 = ((pair_id - image_id2) / ) return (image_id1, image_id2)
def test_new_format_string(): run_cell('a = 5\nb = 7') run_cell('expr_str = f"{a} + {b} = {a+b}"') run_cell('a = 9') run_cell('logging.info(expr_str)') assert_detected('`expr_str` depends on stale `a`')
def eval_func_onnx(model, dataloader, metric, postprocess=None): metric.reset() sess = ort.InferenceSession(model.SerializeToString(), providers=ort.get_available_providers()) input_names = [i.name for i in sess.get_inputs()] for (input_data, label) in dataloader: output = sess.run(None, dict(zi...
class MicroPoolingOptOPSResolverRule(MicroOPSResolverRule): def valid_tag(self, mace_op, mace_net): tag = '' kernels = NetUtil.get_arg(mace_op, MaceKeyword.mace_kernel_str) mace_check((kernels is not None), 'Get kernels failed.') size = (kernels.ints[0] * kernels.ints[1]) if ...
class NllbTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP model_input_names = ['input_ids', 'attention_mask'] prefix_tokens: List[int] = [] suffix_tokens: ...