code
stringlengths
101
5.91M
def main(): args = parse() out_sents = [] with open(args.data_path, 'r') as fp: sent_list = [x.strip() for x in fp.readlines()] if (args.parallel_process_num > 1): try: import submitit except ImportError: logger.warn('submitit is not found and only one job...
.ignore def _get_minimal_slice_set(start: Sequence[int], end: Sequence[int], dims: int, start_edges: Optional[Sequence[bool]]=None, end_edges: Optional[Sequence[bool]]=None) -> Sequence[Tuple[int]]: def reduce_edge_list(l): tally = 1 for i in range(len(l)): reversed_idx = ((- 1) * (i + 1...
class LevelMapper(object): def __init__(self, k_min, k_max, canonical_scale=224, canonical_level=4, eps=1e-06): self.k_min = k_min self.k_max = k_max self.s0 = canonical_scale self.lvl0 = canonical_level self.eps = eps def __call__(self, boxlists): s = torch.sqrt(...
def rotate_and_omega_vec(vR, vT, vz, R, z, phi=0.0, t=0.0, rot=None, omega=None, omegadot=None, omegadotdot=None): (x, y, z) = coords.cyl_to_rect(R, phi, z) (vx, vy, vz) = coords.cyl_to_rect_vec(vR, vT, vz, phi=phi) xyzp = numpy.dot(rot, numpy.array([x, y, z])) (Rp, phip, zp) = coords.rect_to_cyl(xyzp[0...
class TestTorchModel(unittest.TestCase): def setUpClass(self): pass def tearDownClass(self): pass def test_1(self): if is_win(): return with open('int8_pattern.conf', 'w') as f: data = {'pattern_switch': {'Int8BF16MixedPrecisionChecker': True, 'MultiHe...
class TestFileChunker(unittest.TestCase): _tmpdir: Optional[str] = None _tmpfile: Optional[str] = None _line_content = 'Hello, World\n' _num_bytes = None _num_lines = 200 _num_splits = 20 def setUpClass(cls) -> None: cls._num_bytes = len(cls._line_content.encode('utf-8')) cls...
def test_map(): y_true = torch.tensor([[True, False, True, False, True], [False, False, False, True, True], [True, True, False, True, False], [False, True, True, False, True]]) y_pred = torch.tensor([[0.2, 0.8, 0.5, 0.4, 0.3], [0.8, 0.2, 0.3, 0.9, 0.4], [0.2, 0.4, 0.5, 0.9, 0.8], [0.8, 0.2, 0.9, 0.3, 0.7]]) ...
class EvaluationResult(): def __init__(self, configuration: ParameterConfiguration, task_id, task, train_loss, val_loss, time_in_sec, snr, model_path): self.configuration = configuration self.task_id = task_id self.task = task self.train_loss = train_loss self.val_loss = val_...
class SqlObserver(RunObserver): def create(cls, url, echo=False, priority=DEFAULT_SQL_PRIORITY): engine = sa.create_engine(url, echo=echo) return cls(engine, sessionmaker(bind=engine)(), priority) def __init__(self, engine, session, priority=DEFAULT_SQL_PRIORITY): self.engine = engine ...
class _NCEBatch(object): def __init__(self, context_size): self.context_ids = ([] if (context_size > 0) else None) self.doc_ids = [] self.target_noise_ids = [] def __len__(self): return len(self.doc_ids) def torch_(self): if (self.context_ids is not None): ...
class CondConvResidual(InvertedResidual): def __init__(self, in_chs, out_chs, dw_kernel_size=3, stride=1, dilation=1, pad_type='', act_layer=nn.ReLU, noskip=False, exp_ratio=1.0, exp_kernel_size=1, pw_kernel_size=1, se_ratio=0.0, se_kwargs=None, norm_layer=nn.BatchNorm2d, norm_kwargs=None, num_experts=0, drop_path_...
def avg_then_mlp_gnn(make_mlp_fn, epsilon): avg_then_mlp_block = AggThenMLPBlock(tf.unsorted_segment_mean, make_mlp_fn, epsilon) return NodeBlockGNN(avg_then_mlp_block)
class Attribute(Param): def __init__(self, xml_var, value_type, required=True, default=None, var=None): Param.__init__(self, xml_var, value_type, required, default, var) self.type = 'attribute' def set_from_string(self, obj, value): setattr(obj, self.var, self.value_type.from_string(valu...
class CLIPTokenizerFast(PreTrainedTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ['input_ids', 'attention_mask'] slow_tokenizer_class = CLIPTokenizer ...
def fourier(x, terms=10): axis = (len(x.get_shape()) - 1) x_list = [] for i in range(terms): x_list.append(torch.sin((((2 * math.pi) * i) * x))) x_list.append(torch.cos((((2 * math.pi) * i) * x))) return torch.cat(x_list, axis)
def load_bounding_boxes(object_detection_params, subject_path_list, slice_axis, constrast_lst): bounding_box_dict = {} if ((object_detection_params is None) or (object_detection_params[ObjectDetectionParamsKW.OBJECT_DETECTION_PATH] is None)): return bounding_box_dict bounding_box_path = Path(object_...
class DFTMRecovery(Recovery): def __init__(self, hosts, env, training=False): super().__init__() self.hosts = hosts self.env_name = ('simulator' if (env == '') else 'framework') self.training = training self.utilHistory = [] self.lr_bw = 10 def updateUtilHistory(s...
class LabeledVideoDataset(Dataset): _MAX_CONSECUTIVE_FAILURES = 10 def __init__(self, labeled_video_paths: list[tuple[(str, (dict | None))]], clip_sampler: ClipSampler, transform: (Callable[([dict], Any)] | None)=None, decode_audio: bool=True, decoder: str='pyav', decoder_args: DictConfig={}) -> None: s...
def cus_sample(feat, **kwargs): assert ((len(kwargs.keys()) == 1) and (list(kwargs.keys())[0] in ['size', 'scale_factor'])) return F.interpolate(feat, **kwargs, mode='bilinear', align_corners=False)
def add_metrics_to_dict(metrics, history, dot_str): for (name, value) in metrics.items(): history[(name + dot_str)].append(value)
class SVHN(): def __init__(self, args, normalize=False): self.args = args self.norm_layer = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) self.tr_train = [transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor()] self.tr_test = ...
def print_row(row, colwidth=10, latex=False): if latex: sep = ' & ' end_ = '\\\\' else: sep = ' ' end_ = '' def format_val(x): if np.issubdtype(type(x), np.floating): x = '{:.10f}'.format(x) return str(x).ljust(colwidth)[:colwidth] print(sep.j...
def create_simplicial_complex_from_cliques(cliques): G = nx.Graph() triangles_list = set() for c in cliques: d = len(c) if (d == 2): (i, j) = c G.add_edge(i, j) elif (d == 3): triangles_list.add(tuple(sorted(c))) for (i, j) in combinati...
def test_vote_head(): if (not torch.cuda.is_available()): pytest.skip('test requires GPU and torch+cuda') _setup_seed(0) vote_head_cfg = _get_vote_head_cfg('votenet/votenet_8x8_scannet-3d-18class.py') self = build_head(vote_head_cfg).cuda() fp_xyz = [torch.rand([2, 256, 3], dtype=torch.float...
def convert_leg_pose_to_motor_angles(robot_class, leg_poses): if (len(leg_poses) not in [8, 12]): raise ValueError('Dimension of the leg pose provided is not 8 or 12.') neutral_motor_angles = get_neutral_motor_angles(robot_class) motor_angles = leg_poses if ((len(neutral_motor_angles) == 12) and...
def remove_input_tensor_hook_recursively(module): if isinstance(module, Basic_ops): pass else: module.__hook_handle__.remove() del module.__hook_handle__ for (name, sub_module) in module._modules.items(): remove_input_tensor_hook_recursively(sub_module)
class FIDInceptionA(models.inception.InceptionA): def __init__(self, in_channels, pool_features): super().__init__(in_channels, pool_features) def forward(self, x): branch1x1 = self.branch1x1(x) branch5x5 = self.branch5x5_1(x) branch5x5 = self.branch5x5_2(branch5x5) branc...
def test_tell_fails_when_ask_dqd_not_called(scheduler_fixture): (scheduler, *_) = scheduler_fixture with pytest.raises(RuntimeError): scheduler.tell_dqd(None, None, None)
def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False): try: import tensorflow as tf import torch except ImportError: logger.error('Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Pleas...
def test_crunch_function_optimize_png_unoptimized_file(filename): startpath = filename testpath = (filename + '-crunch') if os.path.exists(testpath): os.remove(testpath) src.crunch.optimize_png(startpath) assert (os.path.exists(testpath) is True) if os.path.exists(testpath): os.r...
def tune_delta(loc, scale, y, ops=['add', 'mult'], delta_vals=[1e-08, 1e-07, 1e-06, 1e-05, 0.0001, 0.001, 0.01, 0.1, 0.0, 1.0, 10.0, 100.0, 1000.0], multipliers=[1.0, 2.5, 5.0], scoring='nll', verbose=0, logger=None): assert (ops == ['add', 'mult']) assert (loc.shape == scale.shape == y.shape) results = [] ...
class Kepler(): solmass = 1.9892e+33 gee = 6.67e-08 n0 = 6.02254e+23 sigt = 6.65205e-25 k = 1.38054e-16 a = 7.5648e-15 me = 9.10908e-28 h = 6.62559e-27 c = .0 pie = 3. solmassi = (1 / solmass) solrad = .0 solradi = (1 / solrad) penmex = 0. year = .0 pie43 ...
class Mosaic(): def __init__(self, images: Union[(SlideMap, List[np.ndarray], np.ndarray, List[Tuple[(str, int)]])], coords: Optional[Union[(Tuple[(int, int)], np.ndarray)]]=None, *, tfrecords: List[str]=None, normalizer: Optional[Union[(str, 'StainNormalizer')]]=None, normalizer_source: Optional[str]=None, **grid_...
class WeaklySupervisedCrackSeg(): def __init__(self, classifier_type='R50', classifier_weight_path='./', patch_size=32, stride_classifier=16, stride_thresholding=8): self.classifier_type = classifier_type self.classifier_weight_path = classifier_weight_path self.patch_size = patch_size ...
def gen_min_sigs(project_name: str, class_name: str) -> str: class_row = db.select(table_name='class', conditions={'project_name': project_name, 'class_name': class_name}, result_cols=['signature', 'fields']) if (not class_row): raise RuntimeError('Error happened in function gen_min_sigs.') (c_sig, ...
_module() class TopDownMhpDataset(TopDownCocoDataset): def __init__(self, ann_file, img_prefix, data_cfg, pipeline, test_mode=False): super(TopDownCocoDataset, self).__init__(ann_file, img_prefix, data_cfg, pipeline, test_mode=test_mode) self.use_gt_bbox = data_cfg['use_gt_bbox'] self.bbox_f...
def set_dtype_t(is_float32): global dtype_t dtype_t = (np.float32 if is_float32 else np.float64)
def foo(x: jnp.ndarray) -> jnp.ndarray: mlp = hk.nets.MLP([4, 5, 1]) loss = mlp(x).mean() return loss
class MyNeuronCoverage(): def __init__(self, threshold=0.5): self._threshold = threshold self._layer_neuron_id_to_global_neuron_id = {} self._global_neuron_id_to_layer_neuron_id = {} self._results = {} self._num_layer = 0 self._num_neuron = 0 self._num_input =...
class CelebAHQTrain(FacesBase): def __init__(self, size, keys=None): super().__init__() root = 'data/celebahq' with open('data/celebahqtrain.txt', 'r') as f: relpaths = f.read().splitlines() paths = [os.path.join(root, relpath) for relpath in relpaths] self.data =...
def parse(log): blocks = log[1:(- 1)].split('\n') log_means = dict() log_errs = dict() for block in blocks: chuncks = block.split('|') name = chuncks[0].replace(' ', '') scores = chuncks[2] (mean, err) = scores.replace('score', '').split(' +/- ') log_means[name] =...
class XgbAlgorithm(BaseAlgorithm): algorithm_name = 'Extreme Gradient Boosting' algorithm_short_name = 'Xgboost' def __init__(self, params): super(XgbAlgorithm, self).__init__(params) self.library_version = xgb.__version__ self.explain_level = params.get('explain_level', 0) s...
def check_finite(x, name): if (not np.all(np.isfinite(x))): if np.isscalar(x): raise ValueError(f'{name} must be finite (infinity and NaN values are not supported).') raise ValueError(f'All elements of {name} must be finite (infinity and NaN values are not supported).')
class OptimizationArguments(): prune: bool = field(default=False, metadata={'help': 'Whether or not to apply prune.'}) pruning_approach: Optional[str] = field(default='BasicMagnitude', metadata={'help': 'Pruning approach. Supported approach is basic_magnite.'}) target_sparsity_ratio: Optional[float] = field...
def print_args(args): print('\n') print(' ARGUMENTS ') for k in args.__dict__: print('- {} : {}'.format(k, args.__dict__[k])) print('\n')
class CLIPFeatureExtractor(CLIPImageProcessor): def __init__(self, *args, **kwargs) -> None: warnings.warn('The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please use CLIPImageProcessor instead.', FutureWarning) super().__init__(*args, **kwargs)
def str_filt(str_, voc_type): alpha_dict = {'digit': string.digits, 'lower': (string.digits + string.ascii_lowercase), 'upper': (string.digits + string.ascii_letters), 'all': ((string.digits + string.ascii_letters) + string.punctuation)} if (voc_type == 'lower'): str_ = str_.lower() for char in str_...
def total_norm_constraint(tensor_vars, max_norm, epsilon=1e-07, return_norm=False): norm = T.sqrt(sum((T.sum((tensor ** 2)) for tensor in tensor_vars))) dtype = np.dtype(theano.config.floatX).type target_norm = T.clip(norm, 0, dtype(max_norm)) multiplier = (target_norm / (dtype(epsilon) + norm)) ten...
def chrf(hypotheses, references, remove_whitespace=True): return sacrebleu.corpus_chrf(hypotheses=hypotheses, references=[references], remove_whitespace=remove_whitespace).score
class LatentTransformerEncoderLayer(TransformerEncoderLayer): def __init__(self, args, idx, layer_select=None): super().__init__(args) self.idx = idx self.layer_select = layer_select def residual_connection(self, x, residual): return (residual + (x * self.layer_select(self.idx)))
_model def efficientnet_el(pretrained=False, **kwargs): model = _gen_efficientnet_edge('efficientnet_el', channel_multiplier=1.2, depth_multiplier=1.4, pretrained=pretrained, **kwargs) return model
def build_optims_and_schedulers(model, critic, opt): if (model.__class__.__name__ == 'jointTemplateResponseGenerator'): optimR = nmt.Optim(opt.optim_method, opt.learning_rate_R, opt.max_grad_norm, opt.learning_rate_decay, opt.weight_decay, opt.start_decay_at) optimR.set_parameters(model.parameters()...
def get_art_abs(story_file): lines = read_story_file(story_file) lines = [' '.join(line.lower().strip().split()) for line in lines] lines = [fix_missing_period(line) for line in lines] article_lines = [] highlights = [] next_is_highlight = False for (idx, line) in enumerate(lines): i...
class MultiSkipLSTMCell(tf.nn.rnn_cell.RNNCell): def __init__(self, num_units, forget_bias=1.0, activation=tf.tanh, layer_norm=False, update_bias=1.0): if (not isinstance(num_units, list)): num_units = [num_units] self._num_units = num_units self._num_layers = len(self._num_units...
class FCN8sd(nn.Module): def __init__(self, backbone, backbone_out_channels=2048, aux=False, fixed_size=True, in_channels=3, in_size=(480, 480), num_classes=21): super(FCN8sd, self).__init__() assert (in_channels > 0) self.in_size = in_size self.num_classes = num_classes self...
def GetDetectObjectsService(srv='/costar_perception/segmenter'): return GetService(srv, EmptySrv)
class BaseSRDataset(BaseDataset): def __init__(self, pipeline, scale, test_mode=False): super().__init__(pipeline, test_mode) self.scale = scale def scan_folder(path): if isinstance(path, (str, Path)): path = str(path) else: raise TypeError(f"'path' must b...
def initialize_graph(): global max_generation plot_1.xaxis.label.set_color('c') plot_1.yaxis.label.set_color('r') plot_1.set_xlabel('Generation') plot_1.set_ylabel('Fitness') plot_1.set_title('Fitness Graph', x=0.2, fontsize=20) plot_1.set_xlim([(- (max_generation / 20)), max_generation]) ...
class TFRobertaPreLayerNormModel(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def test_parse_mongo_db_arg_hostname_dbname_collection_name(): assert (MongoDbOption.parse_mongo_db_arg('localhost:28017:foo.bar') == {'url': 'localhost:28017', 'db_name': 'foo', 'collection': 'bar'}) assert (MongoDbOption.parse_mongo_db_arg('www.mymongo.db:28017:bar.baz') == {'url': 'www.mymongo.db:28017', 'db...
class TestTaskEmbeddingWorker(TfGraphTestCase): def test_task_embedding_worker(self): env = GarageEnv(DummyBoxEnv(obs_dim=(1,))) env.active_task_one_hot = np.array([1.0, 0.0, 0.0, 0.0]) env._active_task_one_hot = (lambda : np.array([1.0, 0.0, 0.0, 0.0])) a = np.random.random(env.acti...
def _max_helper_all_tree_reductions(enc_tensor, dim=None, method='log_reduction', keepdim=False): assert (method == 'log_reduction') if (method == 'log_reduction'): return _max_helper_log_reduction(enc_tensor, dim, keepdim)
class Toast(): msg_duration = 4 fade_duration = 0.25 def __init__(self, message, title, icon, sticky=False, spinner=False, progress=False): if (icon and (title is None)): title = icon.capitalize() self._alpha = 0 self._height = None self._default_message_height = ...
class TFBertForPreTraining(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def split_4d(task_string): base_folder = join(raw_dataset_dir, task_string) output_folder = join(splitted_4d_output_dir, task_string) if isdir(output_folder): shutil.rmtree(output_folder) files = [] output_dirs = [] maybe_mkdir_p(output_folder) for subdir in ['imagesTr', 'imagesTs']:...
class UserResponse(ConversationTurn): speaker: str = 'USER' annotations: List[TurnAnnotation] = Field(..., description='List of annotations.') class Config(): schema_extra = {'example': {'speaker': 'USER', 'utterance': 'I am allergic to tomatoes but we have a lot of famous Italian restaurants here i...
def parse_args(): parser = ArgumentParser(description='Testing script: Linear evaluation') parser.add_argument('model_path', type=str, help='Path to the (discriminator) model checkpoint') parser.add_argument('architecture', type=str, help='Architecture') parser.add_argument('--n_classes', type=int, defa...
class ELUFlow(Flow): def __init__(self, alpha=1.0, inverse=False): super(ELUFlow, self).__init__(inverse) self.alpha = alpha def forward(self, input: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor)]: out = F.elu(input, self.alpha, False) input = input.view(input.size(0), (- 1...
class CorrBlockSingleScale(nn.Module): def __init__(self, fmap1, fmap2, num_levels=4, radius=4): super().__init__() self.radius = radius corr = CorrBlock.corr(fmap1, fmap2) (batch, h1, w1, dim, h2, w2) = corr.shape self.corr = corr.reshape(((batch * h1) * w1), dim, h2, w2) ...
class ResNet50TP(nn.Module): def __init__(self, num_classes, loss={'xent'}, **kwargs): super(ResNet50TP, self).__init__() self.loss = loss resnet50 = torchvision.models.resnet50(pretrained=True) self.base = nn.Sequential(*list(resnet50.children())[:(- 2)]) self.feat_dim = 204...
class SharedDepthwiseInducingImages(SharedInducingImages, DepthwiseInducingImages): def __init__(self, images: TensorData, channels_in: int, name: Optional[str]=None): SharedInducingImages.__init__(self, name=name, images=images, channels_in=channels_in)
def calc_index(node, c): ind = (((((node.yaw_index - c.min_yaw) * c.x_w) * c.y_w) + ((node.y_index - c.min_y) * c.x_w)) + (node.x_index - c.min_x)) if (ind <= 0): print('Error(calc_index):', ind) return ind
class Params(): def __init__(self): self.cuda_details = gnn_utils.CudaDetails(use_cuda=torch.cuda.is_available()) self.gnn_args = dict(output_dim=25, hidden_layer_size=101, edge_names=['single', 'double', 'triple'], embedding_dim=50, T=4) processed_data_dir = mchef_config.get_processed_data_...
def vgg13_bn(pretrained=False, **kwargs): model = VGG(make_layers(cfg['B'], batch_norm=True), **kwargs) model.cfg = cfg['B'] model.batch_norm = True if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg13_bn'])) return model
def main(): args = parse_args() update_config(cfg, args) if (args.prevModelDir and args.modelDir): copy_prev_models(args.prevModelDir, args.modelDir) (logger, final_output_dir, tb_log_dir) = create_logger(cfg, args.cfg, 'train') logger.info(pprint.pformat(args)) logger.info(cfg) cudn...
class NegLogLikehoodLoss(torch.nn.Module): def __init__(self): super(NegLogLikehoodLoss, self).__init__() def forward(self, positive_score, negative_score): softplus = (lambda x: torch.log((1 + torch.exp(x)))) output = (softplus((- positive_score)) + softplus(negative_score)) ret...
class DetectAnomaly(plc.Callback): def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, unused=0): if (not (loss := outputs['loss']).isfinite()): raise ValueError(f'Detected NaN/Infinite loss: "{loss}"')
def _set_common_bokeh_fig_props(fig): fig.toolbar.active_drag = None fig.toolbar.active_scroll = None fig.toolbar.active_tap = None fig.outline_line_color = '#333333' fig.outline_line_width = 1 fig.outline_line_alpha = 0.7 fig.title.text_font_size = '10px' fig.legend.label_text_font_size...
class GPS(): def __init__(self, port='/dev/ttyUSB0'): self.serial = None self.port = port self.stop_read_event = threading.Event() self.read_cyclic = threading.Thread(target=self.read_data, args=()) self.x = 0.0 self.y = 0.0 self.t = 0.0 def start(self): ...
def read_opt_def(filename, total_site): rf = open(filename, 'r') _arr = np.zeros(total_site, dtype=complex) for line in rf.readlines()[5:]: line1 = line.split() _arr[int(line1[0])] = (float(line1[1]) + (1j * float(line1[2]))) rf.close() return _arr
class MXNetDataLoader(BaseDataLoader): def _generate_dataloader(self, dataset, batch_size, last_batch, collate_fn, sampler, batch_sampler, num_workers, pin_memory, shuffle, distributed): if shuffle: logging.warning('Shuffle is not supported yet in MXNetDataLoader, ignoring shuffle keyword.') ...
def eval_macro_pw_f1(group2pred, group2gold): def clusters2dict(assgn): d = collections.defaultdict(list) for (idx, c) in enumerate(assgn): d[c].append(idx) return d scores = [] assert (len(group2pred) == len(group2gold)) for (pred, gold) in zip(group2pred, group2gold...
def main(): (list_of_info, keyprefix, rec2waypoints_fout, rec2callsign_list_fout) = sys.argv[1:] rec2waypoints = [] rec2callsign_list = [] with open(list_of_info) as fd: for line in fd: print(line.strip(), file=sys.stderr) info_file = line.strip() reco_key = (...
def is_ckpt_format(model_path): file_list = [os.path.splitext(i)[(- 1)] for i in os.listdir(model_path)] if ((file_list.count('.meta') == 1) and (file_list.count('.index') == 1)): return True return False
def train(gpmodule, optimizer=None, loss_fn=None, retain_graph=None, num_steps=1000): optimizer = (torch.optim.Adam(gpmodule.parameters(), lr=0.01) if (optimizer is None) else optimizer) loss_fn = (TraceMeanField_ELBO().differentiable_loss if (loss_fn is None) else loss_fn) def closure(): optimizer....
def get_val(book: List[PriceLevel], level: int) -> Tuple[(int, int)]: if (book == []): return (0, 0) else: try: price = book[level][0] volume = book[level][1] return (price, volume) except: return (0, 0)
def eval_mesh(mesh_pred, mesh_gt, bb_min, bb_max, n_points=100000): (pointcloud_pred, idx) = mesh_pred.sample(n_points, return_index=True) pointcloud_pred = pointcloud_pred.astype(np.float32) normals_pred = mesh_pred.face_normals[idx] (pointcloud_gt, idx) = mesh_gt.sample(n_points, return_index=True) ...
def dataclass_to_dict(obj): return {k: v for (k, v) in obj.__dict__.items() if (not k.startswith('_'))}
class User(): def __init__(self, ARCH, DATA, datadir, preddir, logdir, modeldir): self.ARCH = ARCH self.DATA = DATA self.datadir = datadir self.preddir = preddir self.logdir = logdir self.modeldir = modeldir parserModule = imp.load_source('parserModule', (((bo...
def set_homotopy_continuation_gamma(regamma=0, imgamma=0): from phcpy.phcpy2c3 import py2c_padcon_set_homotopy_continuation_gamma if ((regamma == 0) and (imgamma == 0)): regm = float(input('-> give the real part of gamma : ')) imgm = float(input('-> give the imaginary part of gamma : ')) ...
def anneal_dsm_score_estimation(scorenet, samples, labels, sigmas, anneal_power=2.0): used_sigmas = sigmas[labels].view(samples.shape[0], *([1] * len(samples.shape[1:]))) perturbed_samples = (samples + (torch.randn_like(samples) * used_sigmas)) target = (((- 1) / (used_sigmas ** 2)) * (perturbed_samples - s...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, prob=None, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(p...
def init_spark_on_k8s(master, container_image, conda_name, num_executors, executor_cores, executor_memory='2g', driver_memory='2g', driver_cores=4, extra_executor_memory_for_ray=None, extra_python_lib=None, penv_archive=None, spark_log_level='WARN', redirect_spark_log=True, jars=None, conf=None, python_location=None): ...
def get_model_normalizer(model_path: str) -> Optional['sf.norm.StainNormalizer']: config = sf.util.get_model_config(model_path) if is_torch_model_path(model_path): backend = 'torch' elif is_tensorflow_model_path(model_path): backend = 'tensorflow' else: log.warn(f'Unable to deter...
def load_module(filename): module_name = os.path.splitext(os.path.basename(filename))[0] return SourceFileLoader(module_name, filename).load_module()
def collate_to_max_length_for_train_dynamic_pron_loss(batch: List[List[torch.Tensor]], max_len: int=None, fill_values: List[float]=None) -> List[torch.Tensor]: lengths = np.array([[len(field_data) for field_data in sample] for sample in batch]) (batch_size, num_fields) = lengths.shape fill_values = (fill_va...
class HTMLProgressBar(BaseProgressBar): def __init__(self): super().__init__() self.progress_bar = None self.label = None self.box = None self._init_subscriber() def _init_subscriber(self): def _initialize_progress_bar(num_tasks): self.start(num_tasks)...
class VQAEval(): def __init__(self, q_2_annotation, q_2_answer, n=2): self.n = n self.accuracy = {} self.evalQA = {} self.evalQuesType = {} self.evalAnsType = {} self.q_2_annotat = q_2_annotation self.q_2_ans = q_2_answer self.contractions = {'aint': "...
def gen_search_space(block_list, block_id): the_block = block_list[block_id] student_blocks_list_list = [] if isinstance(the_block, super_blocks.SuperConvKXBNRELU): student_blocks_list = [] student_out_channels_list = get_select_student_channels_list(the_block.out_channels) for stude...
class Enc(nn.Module): def __init__(self, latentDim): super(Enc, self).__init__() self.embedding = nn.Embedding(vocabSize, embeddingDim, padding_idx=0) self.enc = nn.Sequential(nn.Conv2d(1, fBase, 4, 2, 1, bias=False), nn.BatchNorm2d(fBase), nn.ReLU(True), nn.Conv2d(fBase, (fBase * 2), 4, 2, ...