code
stringlengths
101
5.91M
('spacy') class SpacyWordSplitter(WordSplitter): def __init__(self, language: str='en_core_web_sm', pos_tags: bool=False, parse: bool=False, ner: bool=False) -> None: self.spacy = get_spacy_model(language, pos_tags, parse, ner) def batch_split_words(self, sentences: List[str]) -> List[List[Token]]: ...
def DeepShuffleNetV3PlusD_OS8(args, num_classes, criterion, criterion_aux): print('Model : DeepLabv3+, Backbone : shufflenetv2') return DeepV3Plus(num_classes, trunk='shufflenetv2', criterion=criterion, criterion_aux=criterion_aux, variant='D', skip='m1', args=args)
def heat_diffusion_ind(graph, taus=TAUS, order=ORDER, proc=PROC): a = nx.adjacency_matrix(graph) (n_nodes, _) = a.shape thres = np.vectorize((lambda x: (x if (x > ((0.0001 * 1.0) / n_nodes)) else 0))) lap = laplacian(a) n_filters = len(taus) if (proc == 'exact'): (lamb, U) = np.linalg.ei...
class FiniteWordPath_north_east_iter_with_caching(WordDatatype_iter_with_caching, FiniteWordPath_north_east, FiniteWord_class): pass
def recurrent_plotting(vl_stats, OUTD_VL, tr_stats, OUTD_TR, CRITERION, OUTD_TLB, args, PLOT_STATS, epoch, plot_freq, force): cnd = (PLOT_STATS and ((epoch % plot_freq) == 0)) if (cnd or force): plot_curves_from_dict(vl_stats, join(OUTD_VL.folder, 'validset-stats.png'), title='Validset stats. {}'.format...
def unispeech_sat_base_plus(refresh=False, *args, **kwargs): kwargs['ckpt'] = ' return unispeech_sat_url(*args, refresh=refresh, **kwargs)
def getNodeImage(node_type): image_filename = TYPE_IMAGES[node_type] encoded_image = base64.b64encode(open(image_filename, 'rb').read()) return 'data:image/png;base64,{}'.format(encoded_image.decode())
class ModelArchive(object): def __init__(self, state_dict: Dict[(str, torch.Tensor)], metadata: dict, entity_vocab: EntityVocab): self.state_dict = state_dict self.metadata = metadata self.entity_vocab = entity_vocab def bert_model_name(self): return self.metadata['model_config']...
class AtomicRepresentation(Data): kind = 'data_atomic_representation' def from_linear(cls, representation, dataset, linear): data = atomic_data_dict(dataset.info['atoms_by_system'], linear) return cls.result(data=data, inputs=dataset, component=representation) def from_ragged(cls, representa...
def load_pfm(file): file = open(file, 'rb') color = None width = None height = None scale = None endian = None header = file.readline().rstrip() if (header.decode('ascii') == 'PF'): color = True elif (header.decode('ascii') == 'Pf'): color = False else: ra...
def run_generator(filename): saved_pretrained_model_file = 'datasets/comet_pretrained_models/atomic_pretrained_model.pickle' device = 'cpu' sampling_algorithm = 'topk-3' (opt, state_dict) = utilfuncs.load_model_file(saved_pretrained_model_file) (data_loader, text_encoder) = utilfuncs.load_data('atom...
def _inference(observed_target, target_cov, weight_fn, success_params=(1, 1), hypothesis=0, alpha=0.1): (k, m) = success_params target_sd = np.sqrt(target_cov[(0, 0)]) target_val = (np.linspace(((- 20) * target_sd), (20 * target_sd), 5001) + observed_target) if ((k, m) != (1, 1)): weight_val = n...
def show_image(image): if (image.shape[2] != 3): image = image.permute(1, 2, 0) image = Image.fromarray(image.numpy()) return image
def response_schema_conformance(response: GenericResponse, case: Case) -> (bool | None): from .schemas import BaseOpenAPISchema if (not isinstance(case.operation.schema, BaseOpenAPISchema)): return True return case.operation.validate_response(response)
def test_init(): tl = Timeline() fs = FiberStretcher('fs', tl, np.pi) fs_circ = fs._circuit.get_unitary_matrix() desired = np.array([[complex(1), complex(0)], [complex(0), complex((- 1))]]) assert np.array_equal(fs_circ, desired)
class DropPath(nn.Module): def __init__(self, drop_prob=None): super().__init__() self.drop_prob = drop_prob def forward(self, x): return drop_path(x, self.drop_prob, self.training)
_utils.test(arch=[ti.cpu, ti.cuda, ti.vulkan], exclude=[vk_on_mac], debug=True) def test_multi_print(): def func(x: ti.i32, y: ti.f32): print(x, 1234.5, y) func(666, 233.3) ti.sync()
def register_Ns3Ipv6MulticastRoutingTableEntry_methods(root_module, cls): cls.add_output_stream_operator() cls.add_constructor([]) cls.add_constructor([param('ns3::Ipv6MulticastRoutingTableEntry const &', 'route')]) cls.add_constructor([param('ns3::Ipv6MulticastRoutingTableEntry const *', 'route')]) ...
def make_dns_as(asn: int, zones: List[str], exchange: int): dns_as = base.createAutonomousSystem(asn) router = dns_as.createRouter('router0') net = dns_as.createNetwork('net0') router.joinNetwork('net0') router.joinNetwork('ix{}'.format(exchange)) for zone in zones: name = 's_{}dns'.form...
_metric def fid50k_cond(opts): opts.dataset_kwargs.update(max_size=None, xflip=False) fid = frechet_inception_distance.compute_fid_cond(opts, max_real=None, num_gen=50000) return dict(fid50k_cond=fid)
def preprocess_image(image, size=input_resolution): image = np.array(image) image_resized = tf.expand_dims(image, 0) if (size == 224): image_resized = tf.image.resize(image_resized, (256, 256), method='bicubic') image_resized = crop_layer(image_resized) elif (size == 384): image_...
def search_index_pytorch(index, x, k, D=None, I=None): assert x.is_contiguous() (n, d) = x.size() assert (d == index.d) if (D is None): D = torch.empty((n, k), dtype=torch.float32, device=x.device) else: assert (D.size() == (n, k)) if (I is None): I = torch.empty((n, k), ...
class TemplateTransform(VisitorTransform): temp_name_counter = 0 def __call__(self, node, substitutions, temps, pos): self.substitutions = substitutions self.pos = pos tempmap = {} temphandles = [] for temp in temps: TemplateTransform.temp_name_counter += 1 ...
def set_environment_variables_philly(single_node=False): os.environ['PHILLY_USE_INFINIBAND'] = 'True' os.environ['NCCL_IB_DISABLE'] = '0' IP_INTERFACE_NAME = os.environ['PHILLY_CONTAINER_ETH_INTERFACES'] print('>>> Rank: {}, IP: {}:{}'.format(get_rank(), os.environ['PHILLY_CONTAINER_ETH_INTERFACES'], ge...
def sep_params(model, loaded_roberta_keys): loaded_params = dict() not_loaded_params = dict() params_to_freeze = [] small_lr_params = dict() large_lr_params = dict() for (n, p) in model.named_parameters(): if (n in loaded_roberta_keys): loaded_params[n] = p params...
def generate_a_transition(batch: int): return {Episode.CUR_OBS: np.random.random((batch, 2)), Episode.ACTION: np.random.random((batch,)), Episode.REWARD: np.random.random((batch,))}
def register_Ns3CallbackImplBase_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) cls.add_method('IsEqual', 'bool', [param('ns3::Pt...
def get_running_cuda_version(run_lambda): return run_and_parse_first_match(run_lambda, 'nvcc --version', 'V(.*)$')
class IdentityLayer3D(torch.nn.Module): def __init__(self, m, n, k): super(IdentityLayer3D, self).__init__() self.weight = Parameter(torch.Tensor(m, n, k)) torch.nn.init.xavier_normal_(self.weight) def forward(self): return self.weight
def variable_summaries(var): with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean', mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean(tf.square((var - mean)))) tf.summary.scalar('stddev', stddev) tf.summary.scalar('...
class CQLImpl(SACImpl): _modules: CQLModules _alpha_threshold: float _conservative_weight: float _n_action_samples: int _soft_q_backup: bool def __init__(self, observation_shape: Shape, action_size: int, modules: CQLModules, q_func_forwarder: ContinuousEnsembleQFunctionForwarder, targ_q_func_for...
class adaILN(nn.Module): def __init__(self, num_features, eps=1e-05): super(adaILN, self).__init__() self.eps = eps self.rho = Parameter(torch.Tensor(1, num_features, 1, 1)) self.rho.data.fill_(0.9) def forward(self, input, gamma, beta): (in_mean, in_var) = (torch.mean(in...
def main(): global velocities_pair, pressures_pair, dyes_pair, curl_strength paused = False parser = argparse.ArgumentParser() parser.add_argument('--baseline', action='store_true') (args, _) = parser.parse_known_args() gui = ti.GUI('Stable Fluid', (res, res)) md_gen = MouseDataGen() _ve...
_properties class MultiStateTransformation(PatternTransformation, abc.ABC): def expressions(cls) -> List[gr.SubgraphView]: pass def can_be_applied(self, graph: SDFG, expr_index: int, sdfg: SDFG, permissive: bool=False) -> bool: pass
class DenseFeat(namedtuple('DenseFeat', ['name', 'dimension', 'dtype', 'transform_fn'])): __slots__ = () def __new__(cls, name, dimension=1, dtype='float32', transform_fn=None): return super(DenseFeat, cls).__new__(cls, name, dimension, dtype, transform_fn) def __hash__(self): return self.na...
class GenEfficientNet(nn.Module): def __init__(self, block_args, num_classes=1000, in_chans=3, num_features=1280, stem_size=32, fix_stem=False, channel_multiplier=1.0, channel_divisor=8, channel_min=None, pad_type='', act_layer=nn.ReLU, drop_rate=0.0, drop_connect_rate=0.0, se_kwargs=None, norm_layer=nn.BatchNorm2d...
class CorrelationFunction(Function): def forward(ctx, input1, input2, kernel_size=1, max_displacement=1, stride=1, padding=1, dilation=1, dilation_patch=1): ctx.save_for_backward(input1, input2) (kH, kW) = ctx.kernel_size = _pair(kernel_size) patch_size = ((max_displacement * 2) + 1) ...
_module() class PSENet(TextDetectorMixin, SingleStageTextDetector): def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None, show_score=False, init_cfg=None): SingleStageTextDetector.__init__(self, backbone, neck, bbox_head, train_cfg, test_cfg, pretrained, init_cfg) ...
def main(_): logging.set_verbosity((logging.DEBUG if FLAGS.debug else logging.INFO)) params = Config(FLAGS.config_path).params export_dir = os.path.join(FLAGS.export_dir, params.experiment.name, 'onnx_tensorrt') if (FLAGS.precision == 'int8'): image_params = params.dataloader_params.preprocessin...
class Dstc8DataProcessorTest(absltest.TestCase): def setUp(self): self._processor = data_utils.Dstc8DataProcessor(dstc8_data_dir=_TEST_DATA_DIR, dataset_config=config.DatasetConfig(file_ranges={'train': range(1), 'dev': None, 'test': None}, max_num_cat_slot=6, max_num_noncat_slot=6, max_num_value_per_cat_sl...
def dot(fun1: Function, fun2: Function, **kwargs) -> DotProduct: if (not isinstance(fun1, Function)): fun1 = Constant(fun1) if (not isinstance(fun2, Function)): fun2 = Constant(fun2) return DotProduct(fun1, fun2, **kwargs)
_function def fq(n, q=None): if (q is None): q = ZZ['q'].gen() return prod(((1 - (q ** ((- i) - 1))) for i in range(n)))
class SO3Shortcut(Module): def __init__(self, nfeature_in, nfeature_out, b_in, b_out): super(SO3Shortcut, self).__init__() assert (b_out <= b_in) if ((nfeature_in != nfeature_out) or (b_in != b_out)): self.conv = SO3Convolution(nfeature_in=nfeature_in, nfeature_out=nfeature_out, ...
class DAVIS2016(Dataset): def __init__(self, train=True, inputRes=None, db_root_dir='./DAVIS', transform=None, meanval=(104.00699, 116.66877, 122.67892), seq_name=None): self.train = train self.inputRes = inputRes self.db_root_dir = db_root_dir self.transform = transform self...
class ResNet(nn.Module): def __init__(self, bottleneck=True, aligned=False, use_3x3x3stem=False, stride_3x3=False, avg_down=False, stem_width=64, base_width=64, layers=(3, 4, 6, 3), radix=1, stage_with_conv=('Conv2d', 'Conv2d', 'Conv2d', 'Conv2d'), norm='BN', stage_with_ctx=('', '', '', ''), num_classes=1000): ...
def test_parens(): text = '(-LRB- -LRB-) (-RRB- -RRB-)' trees = tree_reader.read_trees(text) assert (len(trees) == 2) assert (trees[0].label == '-LRB-') assert (trees[0].children[0].label == '(') assert ('{}'.format(trees[0]) == '(-LRB- -LRB-)') assert (trees[1].label == '-RRB-') assert ...
def test_isa_head(): inputs = [torch.randn(1, 8, 23, 23)] isa_head = ISAHead(in_channels=8, channels=4, num_classes=19, isa_channels=4, down_factor=(8, 8)) if torch.cuda.is_available(): (isa_head, inputs) = to_cuda(isa_head, inputs) output = isa_head(inputs) assert (output.shape == (1, isa_h...
def _quantize_language_model(data_dir, arch, extra_flags=None, run_validation=False): train_parser = options.get_training_parser() train_args = options.parse_args_and_arch(train_parser, (['--task', 'language_modeling', data_dir, '--arch', arch, '--optimizer', 'adam', '--lr', '0.0001', '--criterion', 'adaptive_l...
class VoxCeleb1SV(Corpus): def __init__(self, dataset_root: str, download_dir: str, force_download: bool=True) -> None: self.dataset_root = Path(dataset_root).resolve() (train_path, valid_path, test_path, speakerid2label) = self.format_path(self.dataset_root, download_dir, force_download) se...
def from_music21_part(part: Part, resolution: int=DEFAULT_RESOLUTION) -> Union[(Track, List[Track])]: instruments = partitionByInstrument(part) if (not instruments): return parse_track(part, resolution) return [parse_track(instrument, resolution) for instrument in instruments]
class ContinuousQFunctionForwarder(metaclass=ABCMeta): def compute_expected_q(self, x: TorchObservation, action: torch.Tensor) -> torch.Tensor: pass def compute_error(self, observations: TorchObservation, actions: torch.Tensor, rewards: torch.Tensor, target: torch.Tensor, terminals: torch.Tensor, gamma:...
class DCGAN_D_nobn(nn.Module): def __init__(self, isize, nz, nc, ndf, ngpu, n_extra_layers=0): super(DCGAN_D_nobn, self).__init__() self.ngpu = ngpu assert ((isize % 16) == 0), 'isize has to be a multiple of 16' main = nn.Sequential() main.add_module('initial:conv:{0}-{1}'.fo...
def basic_clean(text): text = ftfy.fix_text(text) text = html.unescape(html.unescape(text)) return text.strip()
class KB(): def __init__(self, data_dir, out_dir): logging.basicConfig(level=logging.INFO) self.logger = logging.getLogger(' Knowledge base') self.data_dir = data_dir self.out_dir = out_dir self.criteria_counter = Counter() self.criteria_val_counter = Counter() ...
def _calc_win_score(board: Array) -> int: g = _is_gammon(board) return ((1 + g) + (g & _remains_at_inner(board)))
def load_train_ini(ini_file): cf = configparser.ConfigParser() cf.read(ini_file) param_sections = [] s = cf.sections() for d in range(len(s)): level_dict = dict(phase=cf.get(s[d], 'phase'), batch_size=cf.getint(s[d], 'batch_size'), inputI_width_size=cf.getfloat(s[d], 'inputI_width_size'), in...
def _to_tensor(tensor_or_scalar_like: Any) -> Tuple[(Optional[_TestingErrorMeta], Optional[Tensor])]: error_meta: Optional[_TestingErrorMeta] if isinstance(tensor_or_scalar_like, Tensor): tensor = tensor_or_scalar_like else: try: tensor = torch.as_tensor(tensor_or_scalar_like) ...
class ConnectorStub(object): def __init__(self, channel): self.AllianceStatusStream = channel.unary_stream('/grpc.Connector/AllianceStatusStream', request_serializer=fedn__pb2.ClientAvailableMessage.SerializeToString, response_deserializer=fedn__pb2.Status.FromString) self.SendStatus = channel.unary...
class TFAutoModelForVision2Seq(_BaseAutoModelClass): _model_mapping = TF_MODEL_FOR_VISION_2_SEQ_MAPPING
def html_table(classes, table, rgb_color, normalize=False, shortener=True): result = '' result += '<h2>Confusion Matrix ' if normalize: result += '(Normalized)' result += ': </h2>\n' result += '<table>\n' result += ('<tr style="text-align:center;">' + '\n') result += '<td>Actual</td>...
_params({'data_home': [str, PathLike, None], 'download_if_missing': ['boolean']}, prefer_skip_nested_validation=True) def fetch_species_distributions(*, data_home=None, download_if_missing=True): data_home = get_data_home(data_home) if (not exists(data_home)): makedirs(data_home) extra_params = dict...
class BaseModel(nn.Module): def forward(self, *inputs: Tensor) -> Tensor: raise NotImplementedError def loss_function(self, batch: Tensor, *inputs: Any, **kwargs) -> Tensor: raise NotImplementedError
class CrossEntropyNew(nn.Module): def __init__(self, num_classes, epsilon=0.1, use_gpu=True): super(CrossEntropyNew, self).__init__() self.num_classes = num_classes self.epsilon = epsilon self.use_gpu = use_gpu self.logsoftmax = nn.LogSoftmax(dim=1) def forward(self, inpu...
class PCQM4MDataset(DatasetBase): def __init__(self, dataset_path, dataset_name='PCQM4M', **kwargs): super().__init__(dataset_name=dataset_name, **kwargs) self.dataset_path = dataset_path def dataset(self): try: return self._dataset except AttributeError: ...
class MatrixFactorizationModel(keras.Model): def __init__(self, num_users, num_items, embed_mf_size, lambda_weights, learning_rate=0.01, name='MF', **kwargs): super().__init__(name=name, **kwargs) tf.random.set_seed(42) self.num_users = num_users self.num_items = num_items se...
def write_log(output, log, info): (xlabels, ylabels, yscales, names, plot_kwargs) = zip(*info.values()) _write_header(output, xlabels, ylabels, yscales, names, plot_kwargs) offset = 0 for (ig, (xlabel, ylabel, yscale, names, plot_kwargs)) in ordered_iteritems(info): for (ip, name) in enumerate(n...
def split_mnist_by_labels(args, train_loader, test_loader, choice=None): if (choice is None): choice = sorted(np.random.choice(np.arange(0, 10), size=5, replace=False)) total = sorted(np.arange(0, 10)) other = np.setdiff1d(total, choice) print('First train and test loaders') train_loader_a =...
def parse_config(config_file: str) -> Dict: with open(config_file, 'r') as fd: cfg = yaml.load(fd, yaml.FullLoader) return cfg
def get_preprocessing(name, is_training=False): preprocessing_fn_map = {'cifar10': cifar10_preprocessing, 'cifar100': cifar100_preprocessing, 'imgnet32': imgnet32_preprocessing} if (name not in preprocessing_fn_map): raise ValueError(('Preprocessing name [%s] was not recognized' % name)) def preproc...
def test_tokenize(): nlp = stanfordnlp.Pipeline(processors='tokenize', models_dir=TEST_MODELS_DIR, lang='en') doc = nlp(EN_DOC) assert (EN_DOC_GOLD_TOKENS == '\n\n'.join([sent.tokens_string() for sent in doc.sentences]))
def get_splits(args, task, FIELD, **kwargs): if ('multi30k' in task): (src, trg) = [('.' + x) for x in task.split('.')[1:]] split = torchtext.datasets.generic.Multi30k.splits(exts=(src, trg), fields=FIELD, root=args.data, **kwargs) elif ('iwslt' in task): (src, trg) = [('.' + x) for x in...
class SymbolicSubringRejectingVarsFunctor(GenericSymbolicSubringFunctor): _functor_name = 'SymbolicSubringRejectingVarsFunctor' _repr_type_ = 'rejecting' def merge(self, other): if (self == other): return self elif (type(self) is type(other)): return type(self)((self....
def eval(model, val_loader, a2v, args, test=False): model.eval() count = 0 (metrics, counts) = (collections.defaultdict(int), collections.defaultdict(int)) results = {} with torch.no_grad(): if (not args.mc): model.module._compute_answer_embedding(a2v) for (i, batch) in e...
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 extract_current_lr(optimizer): if isinstance(optimizer.lr, LearningRateSchedule): current_lr = optimizer.lr(optimizer.iterations).numpy() elif hasattr(optimizer.lr, 'numpy'): current_lr = optimizer.lr.numpy() else: current_lr = None return current_lr
def test_IndexedOptionArray_RecordArray_NumpyArray(): v2a = ak.contents.indexedoptionarray.IndexedOptionArray(ak.index.Index(np.array([2, 2, (- 1), 1, (- 1), 5, 4], np.int64)), ak.contents.recordarray.RecordArray([ak.contents.numpyarray.NumpyArray(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6]))], ['nest'])) resultv2 ...
class GILStatNode(NogilTryFinallyStatNode): state_temp = None def __init__(self, pos, state, body): self.state = state self.create_state_temp_if_needed(pos, state, body) TryFinallyStatNode.__init__(self, pos, body=body, finally_clause=GILExitNode(pos, state=state, state_temp=self.state_t...
class LogisticUCB(BaseLogisticPolicy): epsilon: float = 0.0 def __post_init__(self) -> None: check_scalar(self.epsilon, 'epsilon', float, min_val=0.0) self.policy_name = f'logistic_ucb_{self.epsilon}' super().__post_init__() def select_action(self, context: np.ndarray) -> np.ndarray:...
def create_calculator(calctype, *args, **kwargs): return {'asymptotics': AsymptoticCalculator, 'toybased': ToyCalculator}[calctype](*args, **kwargs)
class GraphNode(): def __init__(self, node_id: int): self.id = node_id self.links: Set[GraphNode] = set() self.visited = False def link(self, another: 'GraphNode'): self.links.add(another) another.links.add(self) def __repr__(self) -> str: return str(self.id)
('torch.distributed._broadcast_coalesced', mock) ('torch.distributed.broadcast', mock) ('torch.nn.parallel.DistributedDataParallel._ddp_init_helper', mock) def test_build_ddp(): model = Model() assert (not is_module_wrapper(model)) if torch.cuda.is_available(): mmddp = build_ddp(model, 'cuda', devic...
def get_encodename(name): username_quote = quote_plus(str(name)) username_base64 = base64.b64encode(username_quote.encode('utf-8')) return username_base64.decode('utf-8')
class PreNorm(nn.Module): def __init__(self, dim, fn): super().__init__() self.norm = LayerNorm(dim) self.fn = fn def forward(self, x, **kwargs): x = self.norm(x) return self.fn(x, **kwargs)
class ResizedCapturedImage(CapturedImage): def __init__(self, image_path, tgt_size, sampling=PIL.Image.BILINEAR): CapturedImage.__init__(self, image_path) self.tgt_size = tgt_size self.sampling = sampling def image(self): if (self._image is not None): return self._ima...
def is_safetensors_available(): if is_torch_available(): if (version.parse(_torch_version) >= version.parse('1.10')): return (importlib.util.find_spec('safetensors') is not None) else: return False else: return (importlib.util.find_spec('safetensors') is not None)
_utils.test() def test_offload_with_cross_block_locals(): ret = ti.field(ti.f32) ti.root.place(ret) def ker(): s = 0 for i in range(10): s += i ret[None] = s ker() assert (ret[None] == 45)
def test_consistency_d_dw(problem): from sfepy.discrete import Variables ok = True for aux in test_terms: (term_template, (prefix, par_name, d_vars, dw_vars)) = aux tst.report(term_template, prefix, par_name, d_vars, dw_vars) term1 = (term_template % ((prefix,) + d_vars)) var...
def read_points3D_text(path): points3D = {} with open(path, 'r') as fid: while True: line = fid.readline() if (not line): break line = line.strip() if ((len(line) > 0) and (line[0] != '#')): elems = line.split() ...
class FTB(nn.Module): def __init__(self, in_planes, out_planes=512, stride=1): super(FTB, self).__init__() self.conv0 = nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, padding=1, bias=False) self.conv1 = conv3x3(out_planes, out_planes, stride) self.bn1 = nn.BatchNorm2d...
def yaml_load(filename): with open(filename, 'r') as file: data = yaml.load(file) return data
def get_reg_ref(expr: Expression) -> Optional[Tuple[(Register, int)]]: if isinstance(expr, ExprCast): return get_reg_ref(expr.expr) elif isinstance(expr, ExprDeref): return get_reg_offset(expr.addr) return None
def gaussian_nll(x: Tensor, mean: Tensor, log_var: Tensor, min_noise: float=0.001) -> Tensor: return ((((((x - mean) ** 2) + min_noise) / ((2 * log_var.exp()) + 1e-08)) + (0.5 * log_var)) + (0.5 * np.log((2 * np.pi))))
def upscale_nn(input_tensor, f, use_norm=True, w_l2=w_l2, norm=norm): x = input_tensor x = UpSampling2D()(x) x = Conv2D(f, kernel_size=4, kernel_regularizer=regularizers.l2(w_l2), kernel_initializer=conv_init, padding='same')(x) x = (normalization(x, norm, f) if use_norm else x) x = LeakyReLU(0.2)(x...
def _gather_padding_ref(start_pad_width, end_pad_width, data, lengths): start_padding = np.zeros(data.shape[1:], dtype=data.dtype) end_padding = np.zeros(data.shape[1:], dtype=data.dtype) pad_width = (start_pad_width + end_pad_width) ptr = 0 for length in lengths: for _ in range(start_pad_wi...
def load_pytorch_checkpoint_in_flax_state_dict(flax_model, pytorch_checkpoint_path, allow_missing_keys=False): try: import torch except ImportError: logger.error('Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see and for installation instructions.') ...
class Params(object): def clone(source, strict=True): if isinstance(source, pyhocon.ConfigTree): return Params(**source.as_plain_ordered_dict()) elif isinstance(source, Params): return Params(**source.as_dict()) elif isinstance(source, dict): return Params...
class MediumLevelActionManager(object): def __init__(self, mdp, mlam_params): self.mdp = mdp self.params = mlam_params self.wait_allowed = mlam_params['wait_allowed'] self.counter_drop = mlam_params['counter_drop'] self.counter_pickup = mlam_params['counter_pickup'] s...
def compute_feature_stats_for_dataset(opts, detector_url, detector_kwargs, rel_lo=0, rel_hi=1, batch_size=8, data_loader_kwargs=None, max_items=None, **stats_kwargs): dataset = dnnlib.util.construct_class_by_name(**opts.dataset_kwargs) if (data_loader_kwargs is None): data_loader_kwargs = dict(pin_memor...
def test_replace_ref_nodes_with_names(): modelb = ModelB() modelb.name = 'modelbname' modela = ModelA() modela.int_field = 2 modela.ref_field = modelb modela.ref_field2 = 'user_set_name' model_list = [modelb, modela] schema._replace_ref_nodes_with_names(modela, model_list) assert (mo...
def local_path_from_s3_or_local_path(filename): relative_filename = os.path.join(LOCAL_LOG_DIR, filename) if os.path.isfile(filename): return filename elif os.path.isfile(relative_filename): return relative_filename else: return None