code
stringlengths
101
5.91M
class AzureMLCallback(TrainerCallback): def __init__(self, azureml_run=None): assert _has_azureml, 'AzureMLCallback requires azureml to be installed. Run `pip install azureml-sdk`.' self.azureml_run = azureml_run def on_init_end(self, args, state, control, **kwargs): if ((self.azureml_ru...
class FeatureDeviation(Layer): def __init__(self, scaling=True, mode='thresh', use_abs=True, use_square=True, min_std=1e-05, cutoff=10, **kwargs): self.scaling = scaling self.mode = mode self.min_std_val = min_std self.cutoff = cutoff self.use_abs = use_abs self.use_s...
class ECSSD(BaseImageDataset): def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, min_area=None): root = (env_settings().ecssd_dir if (root is None) else root) super().__init__('ECSSD', root, image_loader) self.image_list = self._load_dataset(min_area=min_area) ...
def compute_similarity_transform(S1, S2): transposed = False if ((S1.shape[0] != 3) and (S1.shape[0] != 2)): S1 = S1.T S2 = S2.T transposed = True assert (S2.shape[1] == S1.shape[1]) mu1 = S1.mean(axis=1, keepdims=True) mu2 = S2.mean(axis=1, keepdims=True) X1 = (S1 - mu1)...
def get_model(params): data = params['dataset'] if ('mnist' in data): model = {} model['rep'] = MultiLeNetR() if params['parallel']: model['rep'] = nn.DataParallel(model['rep']) model['rep'].cuda() if ('L' in params['tasks']): model['L'] = MultiLeN...
class MobileViTEncoder(nn.Module): def __init__(self, config: MobileViTConfig) -> None: super().__init__() self.config = config self.layer = nn.ModuleList() self.gradient_checkpointing = False dilate_layer_4 = dilate_layer_5 = False if (config.output_stride == 8): ...
def build_msev2_yaml(): mse_yaml = '\n model:\n name: fake_yaml\n framework: tensorflow\n inputs: x\n outputs: op2_to_store\n device: cpu\n evaluation:\n accuracy:\n metric:\n topk: 1\n tuning:\n strategy:\n name: mse_v2\n ...
_module() class GridRCNN(TwoStageDetector): def __init__(self, backbone: ConfigType, rpn_head: ConfigType, roi_head: ConfigType, train_cfg: ConfigType, test_cfg: ConfigType, neck: OptConfigType=None, data_preprocessor: OptConfigType=None, init_cfg: OptMultiConfig=None) -> None: super().__init__(backbone=bac...
def calculate_confs_on_correct(probabilities, class_idx, gt_targets): gt_matching_idcs = torch.nonzero((gt_targets == class_idx), as_tuple=False).squeeze() mapped_idx = map_index(probabilities.shape[1], class_idx) (_, preds) = torch.max(probabilities[gt_matching_idcs], dim=1) pred_gt_matching_idcs = gt_...
def get_marginal_density(layer_config, schema_tail, x_shape): (likelihood, z_shape) = get_likelihood(layer_config, schema_tail, x_shape) prior = get_density_recursive(schema_tail, z_shape) approx_posterior = DiagonalGaussianConditionalDensity(coupler=get_coupler(input_shape=x_shape, num_channels_per_output=...
def logging_setup(out_path=None): if logging.root: del logging.root.handlers[:] logging.basicConfig(level=logging.INFO, handlers=[logging.FileHandler(str(out_path)), logging.StreamHandler(stream=sys.stdout)], format='[%(asctime)s/%(levelname)s/%(module)s] %(message)s', datefmt='%Y-%m-%d/%H:%M')
def format_to_lines_tfds(args): tokenized_sub_dirs = os.listdir(args.raw_path) dataset_name = os.path.dirname(args.save_path).split('/')[(- 1)] if (not os.path.isdir(args.save_path)): os.makedirs(args.save_path) corpora = {} for tokenized_sub_dir in tokenized_sub_dirs: path = pjoin(a...
class SceneObjectClass(object): def __init__(self, class_name: str=None, instances: int=None, attributes: str=None): self.class_name = class_name self.instances = instances self.attributes = attributes self.proximity_children = [] def set_instances(self, instances: int): ...
class SuperMobileResnetBlock(nn.Module): def __init__(self, dim, padding_type, norm_layer, dropout_rate, use_bias): super(SuperMobileResnetBlock, self).__init__() self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, dropout_rate, use_bias) def build_conv_block(self, dim, paddin...
def load_and_cache_examples(args, task, tokenizer, evaluate=False): if ((args.local_rank not in [(- 1), 0]) and (not evaluate)): torch.distributed.barrier() processor = processors[task](language=args.language, train_language=args.train_language) output_mode = output_modes[task] cached_features_f...
def is_tensorflow_tensor(arg: Any) -> bool: if sf.util.tf_available: import tensorflow as tf return isinstance(arg, tf.Tensor) else: return False
class MetricHandlerBase(): def __init__(self, name, *args, **kwargs): self.name = name def collect(self, collection, time, mode='train'): pass
def save_results(logits_matrix, targets_list, class_to_idx, args): print('Saving inference results ...') path_to_save = os.path.join(args.ckpt, (args.logname + '_test_results.pkl')) with open(path_to_save, 'wb') as f: pickle.dump([logits_matrix, targets_list, class_to_idx], f)
def ham_mod_batch(x, t, bs, U, Yh, beta, a, b, c): n = (len(x) // 2) On = np.zeros((n, n)) In = np.eye(n) B = np.array((beta * np.eye(n))) F = np.vstack((np.hstack((On, In)), np.hstack(((- In), (- B))))) dJ = gradient_batch(bs, x, U, Yh, a, b, c) dxdt = F.dot(dJ) return dxdt
def data_processing(): (tsdata_train, tsdata_val, tsdata_test) = get_public_dataset(name='nyc_taxi') scaler = StandardScaler() for tsdata in [tsdata_train, tsdata_val, tsdata_test]: tsdata.deduplicate().impute().gen_dt_feature().scale(scaler, fit=(tsdata is tsdata_train)).roll(lookback=lookback, hor...
def val(args): model = get_model(args) model.eval() evaluations = NoteEvaluation.Evaluation(args) for group in range(4): args.restore_step = Restore_Step_list[group] print(('GROUP %d' % group)) args.group = group evaluations.group = args.group val_dataloader = val...
def wer(ctm_edit_lines): num_words = 0 num_incorrect_words = 0 for line in ctm_edit_lines: if (line[7] != 'sil'): num_words += 1 if (line[7] in ['ins', 'del', 'sub']): num_incorrect_words += 1 if ((num_words == 0) and (num_incorrect_words > 0)): re...
def load_state_ckpt(model_path, model): checkpoint = torch.load(model_path) model_dict = model.state_dict() for (key, v) in checkpoint['state_dict'].items(): if (key in model_dict): v1 = model_dict[key] if (len(v.shape) != len(v1.shape)): assert (v1.shape[:2] ...
class Classifier(nn.Module): def __init__(self, embed_dim, class_num, type='linear'): super(Classifier, self).__init__() self.type = type if (type == 'wn'): self.fc = nn.utils.weight_norm(nn.Linear(embed_dim, class_num), name='weight') self.fc.apply(init_weights) ...
class EarlyStopMonitor(): def __init__(self, patience, mode='min'): assert (mode in {'min', 'max'}), "`mode` must be one of 'min' or 'max'" self.log = [] self.mode = mode self.count = 0 self.patience = patience def step(self, metric): if (not self.log): ...
class TTSDatasetArguments(): audio_folder_path: Optional[str] = field(default=None, metadata={'help': 'The path to the directory of audios.'}) text_folder_path: Optional[str] = field(default=None, metadata={'help': 'The path to the directory of texts.'})
class Task(): def __init__(self, task_id, arguments, workers, status, script_url, optimized, approach, requirement, result='', q_model_path=''): self.task_id = task_id self.arguments = arguments self.workers = workers self.status = status self.script_url = script_url ...
def ibn_densenet121(**kwargs): return get_ibndensenet(num_layers=121, model_name='ibn_densenet121', **kwargs)
_executable('ffmpeg') def concat_video(video_list, out_file, vcodec=None, acodec=None, log_level='info', print_cmd=False): (_, tmp_filename) = tempfile.mkstemp(suffix='.txt', text=True) with open(tmp_filename, 'w') as f: for filename in video_list: f.write(f'''file {osp.abspath(filename)} ''...
class PostProcessCocoPt(PostProcessCoco): def __init__(self, use_inv_map, score_threshold): super().__init__() self.use_inv_map = use_inv_map self.score_threshold = score_threshold def __call__(self, results, ids, expected=None, result_dict=None): processed_results = [] b...
def stack(inputs, axis=1): return Variable.from_jvalue(callZooFunc('float', 'stack', inputs, axis))
def write_files(data, path): for d in DATASETS: for p in PARTITIONS: random.shuffle(data[d][p]) f = open(os.path.join(OUTPUT_PATH, '{}_{}.txt'.format(d, p)), 'w+') for sample in data[d][p]: story = ' '.join(sample[0]) task = sample[1] ...
def valence(v: Graph.Vertex) -> int: return sum((btToOrder[e.bondType] for e in v.incidentEdges))
_config def il_tiny(): cfg = {'training': {'dataloader_fn_kwargs': {'data_path': '/mnt/data/expert_trajs/tiny'}, 'num_epochs': 3000}, 'saving': {'ticks_per_epoch': 1, 'log_interval': 500, 'save_interval': 100}}
class SegformerLayer(nn.Module): def __init__(self, config, hidden_size, num_attention_heads, drop_path, sr_ratio, mlp_ratio): super().__init__() self.layer_norm_1 = nn.LayerNorm(hidden_size) self.attention = SegformerAttention(config, hidden_size=hidden_size, num_attention_heads=num_attenti...
class DatasetLoader_pano(data.Dataset): def __init__(self, cfg, split='train', resize_index=False): self.split = split self.resize_index = resize_index if (split == 'train'): self.root = (cfg['root'] + '/training') self.resize_index = True elif (split == 'val'...
def update(i): global surf surf.remove() surf = ax.plot_surface(*(sim.grid / nm), Pt[i], cmap='viridis') return [surf]
def parsedoc(path, format=None): if isinstance(path, str): if ((format == 'pdf') or path.endswith('.pdf')): return parsepdf(path) if ((format == 'docx') or path.endswith('.docx')): return parsedocx(path) if ((format == 'html') or path.endswith(('.htm', '.html', '.xhtm...
class PythonStatementGenerator(object): def __init__(self): self.indexVariables = {} self.indentation = 0 def assignmentStatement(self, var, expr, replacement=None): try: if (var == VAR_COND): return self.pythonExpression(expr, replacement)[0] elif...
def read_vec_int(file_or_fd): fd = open_or_fd(file_or_fd) binary = fd.read(2).decode() if (binary == '\x00B'): assert (fd.read(1).decode() == '\x04') vec_size = np.frombuffer(fd.read(4), dtype='int32', count=1)[0] vec = np.frombuffer(fd.read((vec_size * 5)), dtype=[('size', 'int8'), ...
def moment_for_poly(mass, vertices, offset=(0, 0)): verts = (Vec2d * len(vertices)) verts = verts(Vec2d(0, 0)) for (i, vertex) in enumerate(vertices): verts[i].x = vertex[0] verts[i].y = vertex[1] return cp.cpMomentForPoly(mass, len(verts), verts, offset)
_distributed class TestAutoSeq2Seq(TestCase): def setUp(self) -> None: from bigdl.orca import init_orca_context init_orca_context(cores=8, init_ray_on_spark=True) def tearDown(self) -> None: from bigdl.orca import stop_orca_context stop_orca_context() _torch def test_fit_...
def printProgress(iteration, total, prefix='', suffix='', decimals=1, barLength=100): formatStr = (('{0:.' + str(decimals)) + 'f}') percents = formatStr.format((100 * (iteration / float(total)))) filledLength = int(round(((barLength * iteration) / float(total)))) bar = (('' * filledLength) + ('-' * (bar...
class TestProjects(unittest.TestCase): def test_import(self): from detectron2.projects import point_rend _ = point_rend.add_pointrend_config import detectron2.projects.deeplab as deeplab _ = deeplab.add_deeplab_config
def flatten(inputs): return [([flatten(i) for i in inputs] if isinstance(inputs, (list, tuple)) else inputs)]
class DataTrainingArguments(): lang: str = field(default=None, metadata={'help': 'Language id for summarization.'}) dataset_name: Optional[str] = field(default=None, metadata={'help': 'The name of the dataset to use (via the datasets library).'}) dataset_config_name: Optional[str] = field(default=None, meta...
class InstallHeaders(install_headers): def run(self): if (not self.distribution.headers): return for header in self.distribution.headers: subdir = os.path.dirname(os.path.relpath(header, 'include/pybind11')) install_dir = os.path.join(self.install_dir, subdir) ...
def quad_double_estimated_distance(vrblvl=0): if (vrblvl > 0): print('in quad_double_estimated_distance ...') phc = get_phcfun() apar = pointer(c_int32(2)) bvrb = pointer(c_int32(0)) cdist = pointer(c_double(0.0)) vrb = c_int32(vrblvl) if (vrblvl > 0): print('-> quad_double_e...
def test_check_parameters_min_values_bool(): x = torch.tensor([True, True, False], dtype=torch.bool) dtypes = [torch.bool] _check_parameter(x, 'x', min_value=0) _check_parameter(x, 'x', min_value=(- 1.0)) assert_raises(ValueError, _check_parameter, x, 'x', min_value=1) assert_raises(ValueError, ...
class ModelCheckpoint_Stat(Callback): def __init__(self, filepath, filepath_static, monitor='val_loss', verbose=0, save_best_only=False, save_weights_only=False, mode='max', period=1, patience=None, validation_data=()): super(ModelCheckpoint_Stat, self).__init__() self.interval = period (sel...
def write_obj_with_colors_texture(obj_name, vertices, colors, triangles, texture, uv_coords): if (obj_name.split('.')[(- 1)] != 'obj'): obj_name = (obj_name + '.obj') mtl_name = obj_name.replace('.obj', '.mtl') texture_name = obj_name.replace('.obj', '_texture.png') triangles = triangles.copy() ...
def indice_maxpool_backward(features, out_features, out_bp, indice_pairs, indice_pair_num): if ((features.dtype == torch.float32) or (features.dtype == torch.half)): return ext_module.indice_maxpool_backward(features, out_features, out_bp, indice_pairs, indice_pair_num) else: raise NotImplemente...
class ThreeInterpolate(Function): def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: if (not (open3d.core.cuda.device_count() > 0)): raise NotImplementedError assert features.is_contiguous() assert idx.is_contiguous() assert...
def print_diagnostics(): print('System') print(platform.platform()) os.system('cat /etc/lsb-release') print(sys.version) print('Python') print(sys.version) print(sys.version_info) print('Pytorch') try: import torch print(torch.__version__) print(f'torch.cuda.i...
def get_params_for_weight_decay_optimization(module, config): weight_decay_params = {'params': []} no_weight_decay_params = {'params': [], 'weight_decay': 0.0} blacklist_modules = (torch.nn.LayerNorm, torch.nn.Embedding) for module_ in module.modules(): if (isinstance(module_, blacklist_modules)...
class TrustedFirstParty(): NAME = 'TFP' def generate_additive_triple(size0, size1, op, device=None, *args, **kwargs): a = generate_random_ring_element(size0, device=device) b = generate_random_ring_element(size1, device=device) c = getattr(torch, op)(a, b, *args, **kwargs) a = Ar...
def test_statcast_chunking() -> None: result = statcast('2019-05-01', '2019-05-15').reset_index(drop=True) assert (result is not None) assert (not result.empty) day_results = [] start_date = date(2019, 5, 1) for day in range(15): day_results.append(statcast(str((start_date + timedelta(da...
class SourceHandler(ScorerHandler): def get(self): instance_id = int(self.get_argument('instance_id')) segment_size = None if ('segment_size' in self.request.arguments): string = self.get_argument('segment_size') if (len(string) > 0): segment_size = in...
class TakeKey(gym.ObservationWrapper): def __init__(self, env, take_key): super(TakeKey, self).__init__(env) self._take_key = take_key assert (take_key in self.observation_space.spaces) self.observation_space = self.env.observation_space[take_key] def observation(self, observatio...
def integrate_rgb_frames_for_fragment(color_files, depth_files, fragment_id, n_fragments, pose_graph_name, intrinsic, config): pose_graph = o3d.io.read_pose_graph(pose_graph_name) volume = o3d.pipelines.integration.ScalableTSDFVolume(voxel_length=(config['tsdf_cubic_size'] / 512.0), sdf_trunc=0.04, color_type=o...
class AdaptiveResNet(nn.Module): def __init__(self, ch_cfg, block, layers, num_classes=1000, input_size=224): super(AdaptiveResNet, self).__init__() channels = np.load(os.path.join(ch_cfg, 'sample.npy'), allow_pickle=True).item() self.inplanes = 64 self.conv1 = nn.Conv2d(3, channels[...
_module() class BFP(nn.Module): def __init__(self, in_channels, num_levels, refine_level=2, refine_type=None, conv_cfg=None, norm_cfg=None): super(BFP, self).__init__() assert (refine_type in [None, 'conv', 'non_local']) self.in_channels = in_channels self.num_levels = num_levels ...
class AEPNN(Algorithm): def __init__(self, ae, sympnet, lam=1, recurrent=1): super(AEPNN, self).__init__() self.ae = ae self.sympnet = sympnet self.lam = lam self.recurrent = recurrent self.dim = ae.encoder_size[0] def criterion(self, X, y): (X_latent, y_l...
class ModelNet40(Dataset): def __init__(self, num_points, partition='train'): (self.data, self.label) = load_data(partition) self.num_points = num_points self.partition = partition def __getitem__(self, item): pointcloud = self.data[item][:self.num_points] label = self.la...
def array_from_imgdir(directory: Path, crop_size: int=256, grayscale: bool=False, num_samples: int=None, num_workers: int=1) -> np.ndarray: paths = [] for path in directory.iterdir(): if (path.suffix.lower() == '.png'): paths.append(path) if ((num_samples is not None) and (len(paths)...
_start_docstrings('\n CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.\n for Named-Entity-Recognition (NER) tasks.\n ', CAMEMBERT_START_DOCSTRING) class CamembertForTokenClassification(RobertaForTokenClassification): config_class = CamembertCo...
def save_cfg_file(file_path, source=__C): source = source.copy() masked_keys = ['DATASET_PATH', 'ROOT_DIR'] for key in masked_keys: if (key in source): del source[key] delattr(source, key) with open(file_path, 'w') as f: logging.info(('Save YAML config file to %s'...
class CarsEncodeTransforms(TransformsConfig): def __init__(self, opts): super(CarsEncodeTransforms, self).__init__(opts) def get_transforms(self): transforms_dict = {'transform_gt_train': transforms.Compose([transforms.Resize((192, 256)), transforms.RandomHorizontalFlip(0.5), transforms.ToTensor...
class Ipecac(): def __init__(self, set_, dig_, eles_): self.set = set_ self.dig = dig_ self.eles = eles_ def ReverseAtomwiseEmbedding(self, emb_, atoms_, guess_, GdDistMatrix): natoms = emb_.shape[0] if (atoms_ == None): atoms = np.full(natoms, 6) else...
def check_save_model_path(): save_model_path = os.path.abspath(opt.save_model) model_dirname = os.path.dirname(save_model_path) if (not os.path.exists(model_dirname)): os.makedirs(model_dirname)
class BigBirdForCausalLM(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def head_conv3x3(in_c, out_c, stride=1, norm=nn.InstanceNorm2d): return nn.Sequential(nn.Conv2d(in_channels=in_c, out_channels=out_c, kernel_size=3, stride=stride, padding=1, bias=False), norm(out_c), nn.LeakyReLU(0.1, inplace=True))
class TestActorCritic(unittest.TestCase): def test_discounted_cumsum(self): discount = 0.99 bootstrap = 5.0 dones = np.array([0, 0, 0]) rewards = np.array([1.0, 1.0, 1.0]) discounts = (discount * (1 - dones)) rewards = np.append(rewards, bootstrap) result = rv...
def extract_frames_from_video_path(video_path, target_fps=3, num_frames=3, multi_thread_decode=False, sampling_strategy='rand', safeguard_duration=False): with open(video_path, 'rb') as f: input_bytes = f.read() in_mem_bytes_io = io.BytesIO(input_bytes) frames = extract_frames_from_video_binary(in_m...
def join_model_name(amr): while True: span = None if (len(amr.tokens) < 2): break for i in range((len(amr.tokens) - 1)): (x, y) = amr.tokens[i:(i + 2)] if (x.isalpha() and x.isupper() and re.search('^-\\d+$', y)): span = list(range(i, (i + ...
class G(): output_dir = None output_file = None first_row = True log_headers = [] log_current_row = {}
def register_extension(cls, fcreate=None): if issubclass(cls, _NDArrayBase): assert (fcreate is not None) assert hasattr(cls, '_array_type_code') _reg_ndarray(cls, fcreate) else: assert hasattr(cls, '_tvm_tcode') if (fcreate and (cls._tvm_tcode < TypeCode.EXT_BEGIN)): ...
class Generator(nn.Module): def __init__(self, ngpu, nc=3, ndf=160, ngf=160, nz=100): super(Generator, self).__init__() self.ngpu = ngpu self.main = nn.Sequential(nn.ConvTranspose2d(nz, (ngf * 8), 4, 1, 0, bias=False), nn.BatchNorm2d((ngf * 8)), nn.ReLU(True), nn.ConvTranspose2d((ngf * 8), (...
def lang_pair_dataset(lengths: Sequence[int]) -> LanguagePairDataset: tokens = [([i] * l) for (i, l) in enumerate(lengths)] return LanguagePairDataset(ListDataset(tokens), lengths, mock_dict())
def build_rpn(cfg): if cfg.MODEL.RETINANET_ON: return build_retinanet(cfg) return RPNModule(cfg)
def create_selfloop_edges(num_nodes): edges = [] for i in range(0, num_nodes): edges.append((int(i), int(i))) return edges
class VehiclePrediction(PythonMsg): t: float = field(default=None) x: array.array = field(default=None) y: array.array = field(default=None) v: array.array = field(default=None) v_x: array.array = field(default=None) v_y: array.array = field(default=None) a_x: array.array = field(default=Non...
def init_spark_on_yarn_cluster(hadoop_conf, conda_name, num_executors, executor_cores, executor_memory='2g', driver_cores=4, driver_memory='2g', extra_executor_memory_for_ray=None, extra_python_lib=None, penv_archive=None, additional_archive=None, hadoop_user_name=None, spark_yarn_archive=None, spark_log_level='WARN', ...
def load_model_config_from_hf(model_id: str): assert has_hf_hub(True) cached_file = _download_from_hf(model_id, 'config.json') default_cfg = load_cfg_from_json(cached_file) default_cfg['hf_hub'] = model_id model_name = default_cfg.get('architecture') return (default_cfg, model_name)
class NaiveSyncBatchNorm(BatchNorm2d): def forward(self, input): if ((comm.get_world_size() == 1) or (not self.training)): return super().forward(input) assert (input.shape[0] > 0), 'SyncBatchNorm does not support empty input' C = input.shape[1] mean = torch.mean(input, d...
class ResBlocks(nn.Module): def __init__(self, num_blocks, input_nc, output_nc=None, hidden_nc=None, norm_layer=nn.BatchNorm2d, nonlinearity=nn.LeakyReLU(), learnable_shortcut=False, use_spect=False, use_coord=False): super(ResBlocks, self).__init__() hidden_nc = (input_nc if (hidden_nc is None) els...
def test_invalid_response_connection(): n = Network([_TestAgent2('A'), _TestAgent2('B'), _TestAgent2('C')], BatchResolver()) n.add_connection('A', 'B') n.send('A', 'B', Request(0.0)) with pytest.raises(NetworkError): n.resolve({aid: n.context_for(aid, EnvView(0, 0.0)) for aid in n.agents})
def load_flattened_documents(data_dir: str, docids: Set[str]) -> Dict[(str, List[str])]: unflattened_docs = load_documents(data_dir, docids) flattened_docs = dict() for (doc, unflattened) in unflattened_docs.items(): flattened_docs[doc] = list(chain.from_iterable(unflattened)) return flattened_d...
class TestYOLOXHead(TestCase): def test_init_weights(self): head = YOLOXHead(num_classes=4, in_channels=1, stacked_convs=1, use_depthwise=False) head.init_weights() bias_init = bias_init_with_prob(0.01) for (conv_cls, conv_obj) in zip(head.multi_level_conv_cls, head.multi_level_conv_...
def test_digits_sqrt_greedi_ln_sparse(): model = FeatureBasedSelection(100, 'sqrt', optimizer='greedi', optimizer_kwds={'optimizer1': 'lazy', 'optimizer2': 'naive'}, random_state=0) model.fit(X_digits_sparse) assert_array_equal(model.ranking, digits_sqrt_greedi_ranking) assert_array_almost_equal(model.g...
class Generator3(nn.Module): def __init__(self): super(Generator3, self).__init__() image_size = 28 latent_dim = 100 output_channels = 1 self.init_size = (image_size // 4) self.l1 = nn.Sequential(nn.Linear(latent_dim, (128 * (self.init_size ** 2)))) self.label...
def define_G(input_nc, output_nc, ngf, which_model_netG, norm='batch', use_dropout=False, gpu_ids=[], use_parallel=True, learn_residual=False): netG = None use_gpu = (len(gpu_ids) > 0) norm_layer = get_norm_layer(norm_type=norm) if use_gpu: assert torch.cuda.is_available() if (which_model_ne...
def apply_augmentations(augmentations: List[Union[(Transform, Augmentation)]], inputs): if isinstance(inputs, np.ndarray): image_only = True inputs = AugInput(inputs) else: image_only = False tfms = inputs.apply_augmentations(augmentations) return ((inputs.image if image_only els...
class ToyModel2(BaseModel): def __init__(self): super().__init__() self.teacher = ToyModel1() self.student = ToyModel1() self.semi_test_cfg = dict(predict_on='teacher') def forward(self, *args, **kwargs): return self.student(*args, **kwargs)
def single_gpu_test(model, data_loader): model.eval() results = [] dataset = data_loader.dataset prog_bar = mmcv.ProgressBar(len(dataset)) for data in data_loader: with torch.no_grad(): result = model(return_loss=False, **data) results.extend(result) batch_size = ...
class CmsPfSingleElectron(tfds.core.GeneratorBasedBuilder): VERSION = tfds.core.Version('1.6.0') RELEASE_NOTES = {'1.0.0': 'Initial release.', '1.1.0': 'Initial release.', '1.2.0': '12_1_0_pre3 generation, add corrected energy, cluster flags, 20k events', '1.4.0': 'Add gen jet index information', '1.5.0': 'With...
def preprocess(tokenizer, config, example, max_seq_length): prompt = example['context'] target = example['target'] prompt_ids = tokenizer.encode(prompt, max_length=max_seq_length, truncation=True) target_ids = tokenizer.encode(target, max_length=max_seq_length, truncation=True, add_special_tokens=False)...
class _module(): def __init__(self, receiver, buffer_size): self._source_wires = _create_interface_source() self._interconnect_wires = _create_interface_interconnect() self._source = _create_source(receiver, self._source_wires, self._interconnect_wires) self._interconnect = _create_i...
def run_model_with_conf(flags, args, model_name, model_conf): target_abi = 'host' dev = device.HostDevice('host', target_abi) install_dir = ('/tmp/micro_run/' + model_name) if (ModelKeys.check_tensors in model_conf): model_conf[ModelKeys.output_tensors] = model_conf[ModelKeys.check_tensors] ...
_task('multilingual_translation') class MultilingualTranslationTask(FairseqTask): def add_args(parser): parser.add_argument('data', metavar='DIR', help='path to data directory') parser.add_argument('--lang-pairs', default=None, metavar='PAIRS', help='comma-separated list of language pairs (in traini...