code
stringlengths
101
5.91M
def link_attr_list_to_map(l): if isinstance(l, dict): return l attr_name = ['delay', 'capacity'] han = {'delay': float, 'capacity': int} nl = [str(han[n](convert_unit(v))) for (n, v) in zip(attr_name, l)] m = dict(zip(attr_name, nl)) m['weight'] = '10' return m
def dump_torchscript_IR(model, dir): dir = os.path.expanduser(dir) PathManager.mkdirs(dir) def _get_script_mod(mod): if isinstance(mod, torch.jit.TracedModule): return mod._actual_script_module return mod with PathManager.open(os.path.join(dir, 'model_ts_code.txt'), 'w') as f...
def Inference(model, data): sess = ort.InferenceSession(model.SerializeToString(), providers=['CPUExecutionProvider']) out = sess.run(None, data) return out
def string_of_symbols(maxlen=100, vrblvl=0): if (vrblvl > 0): print('in string_of_symbols, maxlen :', maxlen) phc = get_phcfun() slen = pointer(c_int32(0)) ssym = create_string_buffer(b'', (maxlen * 4)) ccc = pointer(c_double(0.0)) vrb = c_int32(vrblvl) if (vrblvl > 0): print...
class DimPlanner(DistributedGraphMixin): def __init__(self, num_nodes=None, num_devices_per_node=None, tracer_backend: str='meta_fx', prop_mode: str='interpreter', use_fake_mode: bool=False, device_context=None): super().__init__(num_nodes=num_nodes, num_devices_per_node=num_devices_per_node, tracer_backend...
class install(_install): def finalize_options(self): _install.finalize_options(self) self.install_libbase = self.install_platlib self.install_lib = self.install_platlib
def reduce_process(opts, output_queue, spool_length, out_file=None, file_size=0, file_compress=True): global options options = opts createLogger(options.quiet, options.debug, options.log_file) if out_file: nextFile = NextFile(out_file) output = OutputSplitter(nextFile, file_size, file_co...
def softmax_layer(name, bottom, label='label', loss_weight=1): txt = open('templates/softmax_layer.txt', 'r').read() txt = txt.replace('_NAME_', name) txt = txt.replace('_BOTTOM_', bottom) txt = txt.replace('_LABEL_', label) txt = txt.replace('_LOSS_WEIGHT_', str(loss_weight)) return txt
def powerset(arr): if arr: (first, *rest) = arr rest_subsets = powerset(rest) return [([first] + subset) for subset in rest_subsets] else: return [[]]
class ExecutionTraceGetter(object): def __init__(self, trace_obj): self.trace_obj = trace_obj def get(self) -> List[Tuple[(E.Expression, TensorValue)]]: return self.trace_obj
class Scorer(): def __init__(self, args=None): self.args = args self.device = self.args.device self.eval_asp = self.args.aspect self.data = read_pickle(self.args.file_path) (self.demos, self.asp_dfs) = read_demos(self.args.demo_path) print('Since GPT3-based models are...
def sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float=0.25, gamma: float=2): prob = inputs.sigmoid() ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction='none') p_t = ((prob * targets) + ((1 - prob) * (1 - targets))) loss = (ce_loss * ((1 - p_t) ** gamma)) if (alpha >= ...
def parse_args(): parser = ArgumentParser(description='Train Single Shot MultiBox Detector on COCO') parser.add_argument('--data', '-d', type=str, default='/coco', help='path to test and training data files') parser.add_argument('--pretrained-backbone', type=str, default=None, help='path to pretrained backb...
class VQModel(pl.LightningModule): def __init__(self, ddconfig, lossconfig, n_embed, embed_dim, ckpt_path=None, ignore_keys=[], image_key='image', colorize_nlabels=None, monitor=None, remap=None, sane_index_shape=False): super().__init__() self.image_key = image_key self.encoder = Encoder(**...
def main(dst): print(f'-> Copying splits to "{dst}"...') shutil.copytree((REPO_ROOT / 'api/data/splits'), dst, dirs_exist_ok=True) (dst / FILE.name).unlink()
class FairseqBMUF(FairseqOptimizer): def __init__(self, cfg: FairseqBMUFConfig, optimizer): super().__init__(cfg) self._optimizer = optimizer self._num_updates = 0 self.sync_iter = cfg.global_sync_iter self.block_momentum = cfg.block_momentum self.block_lr = cfg.block...
def sMDAPE(y_true: 'ndarray', y_pred: 'ndarray', multioutput: str='raw_values') -> Union[(float64, 'ndarray')]: (y_true, y_pred, original_shape) = _standardize_input(y_true, y_pred, multioutput) output_errors = np.median(((100 * np.abs((y_true - y_pred))) / ((np.abs(y_true) + np.abs(y_pred)) + EPSILON)), axis=0...
class CollectVars(TraverseAction): hn: CHeaderNode def __init__(self, hn: CHeaderNode): super().__init__() self.hn = hn self.traverse_edges = ['content', 'next'] def _pre_action(self, edge) -> bool: t = edge.target if issubclass(type(t), Node): if t.math_r...
class ResNet(nn.Module): def __init__(self, depth, num_filters, block_name='BasicBlock', num_classes=10): super(ResNet, self).__init__() if (block_name.lower() == 'basicblock'): assert (((depth - 2) % 6) == 0), 'When use basicblock, depth should be 6n+2, e.g. 20, 32, 44, 56, 110, 1202' ...
class catbAbI(data.Dataset): def __init__(self, partition, whitelist, ra_mode, large=True, folder=DATA_PATH): self.partition = partition self.whitelist = whitelist self.ra_mode = ra_mode if large: self.fp = os.path.join(folder, catbAbI10k_TEMPLATE.format(partition)) ...
def translate_texts(dataset: DatasetDict, texts: Dict[(str, Dict[(str, List[str])])], translate_args: Dict[(str, Any)], dataset_args: Dict[(str, Any)]) -> None: translations = {} for config in dataset_args['dataset_configs']: translations[config] = dataset[config].to_dict() translate_args['sourc...
def draw_disparity(disparity_map): min_val = np.min(disparity_map) max_val = np.max(disparity_map) norm_disparity_map = (255 * ((disparity_map - min_val) / (max_val - min_val))).astype(np.uint8) return cv2.applyColorMap(cv2.convertScaleAbs(norm_disparity_map, 1), cv2.COLORMAP_JET)
class CNNParams(): def __init__(self, verbose): self.pool_window = [1, 2, 2, 1] self.pool_stride = [1, 2, 2, 1] self.last_features = 1024 self.conv_filters = [64, 64, 128, 128, 256, 256, 256, 512, 512, 512, 512, 512, 512] self.depth_filters = [32] self.layer_shapes = ...
class Convolution2D(KerasLayer): def __init__(self, nb_filter, nb_row, nb_col, init='glorot_uniform', activation=None, border_mode='valid', subsample=(1, 1), dim_ordering='th', W_regularizer=None, b_regularizer=None, bias=True, input_shape=None, **kwargs): super(Convolution2D, self).__init__(None, nb_filter...
def element_featurize(sampletype, default_features, filepaths, directory): folder = (('%s-features-' % sampletype) + str(uuid.uuid1())) old_dir = directory train_dir = (basedir + '/train_dir') directory = ((basedir + '/train_dir/') + folder) os.mkdir(((basedir + '/train_dir/') + folder)) for i i...
def _FracInt(x, y, z, a, b, c, tau, n): denom = numpy.sqrt((((a + tau) * (b + tau)) * (c + tau))) return (((((1.0 - ((x ** 2) / (a + tau))) - ((y ** 2) / (b + tau))) - ((z ** 2) / (c + tau))) ** n) / denom)
_registry(dataset_type='ImageFolder', framework='mxnet', dataset_format='') class MXNetImageFolder(ImageFolder): def __getitem__(self, index): sample = self.image_list[index] label = sample[1] image = mx.image.imread(sample[0]) if (self.transform is not None): (image, lab...
def WideResNet40x10(num_class=10, block=None, attention_module=None): return WideResNetWrapper(depth=40, widen_factor=10, dropRate=0.3, num_class=num_class, attention_module=attention_module)
def main(): now = int(time.time()) args = parse_args() if (not args.weights_folder): raise 'you must pass a --weights_folder' weights_folder_name = filter(None, args.weights_folder.split('/'))[(- 1)] output_path = 'results/coco_results_{}'.format(weights_folder_name) print("Output to: '{...
class CenterBlock(nn.Sequential): def __init__(self, in_channels, out_channels, use_batchnorm=True): conv1 = md.Conv2dReLU(in_channels, out_channels, kernel_size=3, padding=1, use_batchnorm=use_batchnorm) conv2 = md.Conv2dReLU(out_channels, out_channels, kernel_size=3, padding=1, use_batchnorm=use_b...
(loss_fn='L1') class Interior(sc.SampleDomain): def sampling(self, *args, **kwargs): points = geo.sample_interior(10000) constraints = {'integral_dx': 0} return (points, constraints)
class BatchScorerInterface(ScorerInterface): def batch_init_state(self, x: torch.Tensor) -> Any: return self.init_state(x) def batch_score(self, ys: torch.Tensor, states: List[Any], xs: torch.Tensor) -> Tuple[(torch.Tensor, List[Any])]: warnings.warn('{} batch score is implemented through for lo...
class Attr(): def __init__(self, string=None, **args): if (not string): self.attr = args else: self.attr = ParseArg(string) def __str__(self): string = ('"' + self.attr['name']) for (k, v) in self.attr.iteritems(): if (k == 'name'): ...
class GRA(nn.Module): def __init__(self, channel, subchannel): super(GRA, self).__init__() self.group = (channel // subchannel) self.conv = nn.Sequential(nn.Conv2d((channel + self.group), channel, 3, padding=1), nn.ReLU(True)) self.score = nn.Conv2d(channel, 1, 3, padding=1) def ...
_model def skresnet50d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): sk_kwargs = dict(split_input=True) default_cfg = default_cfgs['skresnet50d'] model = ResNet(SelectiveKernelBottleneck, [3, 4, 6, 3], stem_width=32, stem_type='deep', avg_down=True, num_classes=num_classes, in_chans=in_chans, b...
def poly_utilities(n, theta): u = np.array(([0.0] * n)) for i in range(len(theta)): u += ((np.array(range(n)) ** i) * theta[i]) return u
def train_predict_model(env_pool, predict_env, flag=False): print('> Model Train < ') global model_step global eval_step if (flag == True): model_train_num = 3 else: model_train_num = 1 for i in range(model_train_num): t1 = time.time() (state, next_state, actio...
class SourceNotFoundError(DatasetError): def __init__(self, source, config): self.source = source self.config = config super().__init__('Unable to find source {} in config {}'.format(source, config)) def __reduce__(self): return (SourceNotFoundError, (self.source, self.config))
def fmt_n(x, n=4): if USE_CUDA: return torch.tensor(x.reshape((int((len(x) / n)), (n * x.shape[1]))), dtype=torch.float32).cuda() else: return torch.tensor(x.reshape((int((len(x) / n)), (n * x.shape[1]))), dtype=torch.float32)
def digit_norm(s): out = '' buf = '' for c in s: if (not c.isdigit()): if buf: try: digit_str = cn2an.an2cn(buf) except: print(f'cannot convert digit {buf}') digit_str = ''.join([digit_dict.get(x,...
def tsv_to_examples(): label_map = {} token_map = {} shape_map = {} char_map = {} update_vocab = True update_chars = True if FLAGS.start_end: token_map[SENT_START] = len(token_map) token_int_str_map[token_map[SENT_START]] = SENT_START shape_map[SENT_START] = len(shape...
def err_cc_img(list_gt, list_pred): errs = [] for b in range(list_gt.shape[0]): mask_gt = list_gt[(b, ...)] mask_pred = list_pred[(b, ...)] errs.append(error_l1_cc(mask_gt, mask_pred)) return np.array(errs)
class ItrexOpt(object): def __init__(self, config_file, no_cuda): if ((int(os.environ.get('LOCAL_RANK', (- 1))) != (- 1)) and no_cuda): from intel_extension_for_transformers.transformers.utils.utility import distributed_init distributed_init() parser = HfArgumentParser((Model...
class ActorCriticValueRewardPolicy(ModuleContainer): CONTAINERS = ['reward', 'encoder', 'actor', 'critic', 'value']
def conv3x3x3(in_planes, out_planes, stride=1, bias=False): return nn.Conv3d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=bias)
def _make_dummy_env_func(config, dataset, id): return DummyRLEnv(config=config, dataset=dataset, env_ind=id)
def findMatchingBraces(text, ldelim=0): if ldelim: reOpen = re.compile(('[{]{%d,}' % ldelim)) reNext = re.compile('[{]{2,}|}{2,}') else: reOpen = re.compile('{{2,}|\\[{2,}') reNext = re.compile('{{2,}|}{2,}|\\[{2,}|]{2,}') cur = 0 while True: m1 = reOpen.search(te...
def build_scores_break(matrix, selected, epsilon=0.0001): has_breaks = ((selected[1:] - selected[:(- 1)]) > 1) has_breaks = np.concatenate((np.zeros(1), has_breaks), axis=0) n_sites = len(selected) n_colors = matrix.shape[1] epsilon = 0.0001 all_scores = [] maxi_size = 0 for (site, has_b...
class MetadataCaptureHook(TrainingHook): def __init__(self, params, model_dir, run_config): super(MetadataCaptureHook, self).__init__(params, model_dir, run_config) self._active = False self._done = False self._global_step = None self._output_dir = os.path.abspath(self.model_...
class UniDiffuserTextDecoder(metaclass=DummyObject): _backends = ['torch', 'transformers'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch', 'transformers']) def from_config(cls, *args, **kwargs): requires_backends(cls, ['torch', 'transformers']) def from_pretrained(...
def test_geotext_extract_with_count_span_info_true(geotext): output = geotext.extract(input_text=text) assert (output['cities']['Berlin']['count'] == 2) assert (output['cities']['Berlin']['span_info'] == [(0, 6), (43, 49)]) assert (output['cities']['Berlin']['found_as'] == ['Berlin', 'Berlin'])
def seq_start(tag='', anchor='', anchor_id=0, style='_'): emit = [] handle = [] if tag: emit += [('VerbatimTag("%s")' % encode(tag))] if anchor: emit += [('Anchor("%s")' % encode(anchor))] handle += [('OnAnchor(_, "%s")' % encode(anchor))] if tag: out_tag = encode(tag...
def get_tokenizer(config): tokenizer = '' max_len_token = 0 if (config.tokenizer_name == 'Char'): tokenizer = Char() max_len_token = config.max_num_char return (tokenizer, max_len_token)
class PegasusTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES offset = 103 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 = ['attention_mask'] ...
_grad() def pose_evaluate(model, matcher, pose_evaluator, data_loader, image_set, bbox_mode, rotation_mode, device, output_dir, epoch=None): model.eval() matcher.eval() pose_evaluator.reset() if (epoch is not None): output_eval_dir = (((((((output_dir + '/eval_') + image_set) + '_') + bbox_mode)...
def build_dataset(data_path, config, is_train, vocab=None, load_vocab=None): args = config.data if is_train: (src_txt, tgt_txt) = load_dataset(data_path) src_train = TextDataset(src_txt, args.src_max_train) tgt_train = TextDataset(tgt_txt, args.tgt_max_train) if (load_vocab is no...
def compute_heads_importance(args, model, eval_dataloader, compute_entropy=True, compute_importance=True, head_mask=None, actually_pruned=False): (n_layers, n_heads) = (model.config.num_hidden_layers, model.config.num_attention_heads) head_importance = torch.zeros(n_layers, n_heads).to(args.device) attn_ent...
class PerceptualLossVgg16ExDark(nn.Module): def __init__(self, vgg=None, load_model=None, gpu_ids=[0], weights=None, indices=None, normalize=True): super(PerceptualLossVgg16ExDark, self).__init__() if (vgg is None): self.vgg = Vgg16ExDark(load_model) else: self.vgg = ...
def identity_inference(images, keep_probability, phase_train=True, bottleneck_layer_size=128, weight_decay=0.0, reuse=None): batch_norm_params = {'decay': 0.995, 'epsilon': 0.001, 'updates_collections': None, 'variables_collections': [tf.GraphKeys.TRAINABLE_VARIABLES]} with slim.arg_scope([slim.conv2d, slim.ful...
class BoxOnClWireTop(MultiBox, BoxOnClWire): def __init__(self, label='', top_connect=None, wire_label=''): super().__init__(label) self.wire_label = wire_label self.mid_content = '' self.bot_format = ' %s ' self.top_connect = (top_connect if top_connect else '') self...
class STrack(BaseTrack): shared_kalman = KalmanFilter() def __init__(self, tlwh, score): self._tlwh = np.asarray(tlwh, dtype=np.float) self.kalman_filter = None (self.mean, self.covariance) = (None, None) self.is_activated = False self.score = score self.tracklet_...
def read_image1(): image_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets', 'encode_jpeg', 'grace_hopper_517x606.jpg') image = Image.open(image_path) image = image.resize((224, 224)) x = F.to_tensor(image) return x.view(1, 3, 224, 224)
def get_info(I): (w, h) = I.size gridY = torch.linspace((- 1), 1, steps=h).view(1, (- 1), 1, 1).expand(1, h, w, 1) gridX = torch.linspace((- 1), 1, steps=w).view(1, 1, (- 1), 1).expand(1, h, w, 1) grid = torch.cat((gridX, gridY), dim=3).cuda() tensor = transforms.ToTensor()(I).unsqueeze(0).cuda() ...
def sepreresnet1202_cifar10(num_classes=10, **kwargs): return get_sepreresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False, model_name='sepreresnet1202_cifar10', **kwargs)
_model def seresnet18(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['seresnet18'] model = SENet(SEResNetBlock, [2, 2, 2, 2], groups=1, reduction=16, inplanes=64, input_3x3=False, downsample_kernel_size=1, downsample_padding=0, num_classes=num_classes, in_chans=in_chans, *...
class MockStub(object): def optimize(self, request): res = brain_pb2.OptimizeResponse() res.job_optimize_plans.add() plan = res.job_optimize_plans[0] group_resources = plan.resource.task_group_resources group_resources[NodeType.WORKER].count = 5 group_resources[NodeTy...
def set_disable_prefix(disable_prefix): global _disable_prefix _disable_prefix = disable_prefix
def test_dfa_models(model_architectures): for (arch, input_size) in model_architectures: check_model(models.dfa.__dict__[arch], input_size)
class Accuracy(base.Metric): def __init__(self, threshold=0.5, activation=None, ignore_channels=None, **kwargs): super().__init__(**kwargs) self.threshold = threshold self.activation = Activation(activation) self.ignore_channels = ignore_channels def forward(self, y_pr, y_gt): ...
class Net(torch.nn.Module): def __init__(self, cfg): super(Net, self).__init__() self.num_nodes = cfg['model']['num_nodes'] self.num_output_dim = cfg['model']['output_dim'] self.num_units = cfg['model']['rnn_units'] self.num_input_dim = cfg['model']['input_dim'] self....
def get_model_config(model_name, model_version=None): config_fname = (f'config_{model_name}_{model_version}.json' if (model_version is not None) else f'config_{model_name}.json') config_file = os.path.join(ROOT, 'models', model_name, config_fname) if (not os.path.exists(config_file)): return None ...
def set_seed(seed, cuda=True): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False
class IterationBasedBatchSampler(BatchSampler): def __init__(self, batch_sampler, num_iterations, start_iter=0): self.batch_sampler = batch_sampler self.sampler = self.batch_sampler.sampler self.num_iterations = num_iterations self.start_iter = start_iter def __iter__(self): ...
def lidar2camera(point_cloud, rotationMat=rotationMat, translationMat=translationMat, file_name='merge', data_index=1): img = np.zeros((720, 1280, 3), np.uint8) trans_pc = (np.dot(rotationMat, point_cloud) + np.tile(translationMat, (point_cloud.shape[1], 1)).T) image_uv = np.array([(((trans_pc[0] * fx) / tr...
class subData(object): def __init__(self, cfg, data_name, start): self.data_name = data_name self.start = start info = cfg.OCEAN.DATASET[data_name] self.frame_range = info.RANGE self.num_use = info.USE self.root = info.PATH with open(info.ANNOTATION) as fin: ...
class Motors(): def __init__(self, p: bullet_client.BulletClient, physics_period: float, np_random: np.random.RandomState, uav_id: (np.ndarray | int), motor_ids: (np.ndarray | list[int]), tau: np.ndarray, max_rpm: np.ndarray, thrust_coef: np.ndarray, torque_coef: np.ndarray, thrust_unit: np.ndarray, noise_ratio: np...
class CCSBUDataset(BaseDataset): def __init__(self, vis_processor, text_processor, location): super().__init__(vis_processor=vis_processor, text_processor=text_processor) self.inner_dataset = wds.DataPipeline(wds.ResampledShards(location), wds.tarfile_to_samples(handler=wds.warn_and_continue), wds.s...
def load_tests(city): test_input = pandas.read_parquet(((((BASEDIR / 'test') / city) / 'input') / 'counters_test.parquet')) test_input['vol'] = np.array(test_input['volumes_1h'].to_numpy().tolist()).sum(axis=1) return test_input
def get_latest_epoch(loadpath, prior=''): states = glob.glob1(loadpath, (prior + 'state_*')) latest_epoch = (- 1) for state in states: epoch = int(state.replace((prior + 'state_'), '').replace('.pt', '')) latest_epoch = max(epoch, latest_epoch) return latest_epoch
def data_parallel(module, inputs, device_ids=None, output_device=None, dim=0, module_kwargs=None): if (not isinstance(inputs, tuple)): inputs = (inputs,) if (device_ids is None): device_ids = list(range(torch.cuda.device_count())) if (output_device is None): output_device = device_id...
class ScaleParameter(message.Message): __metaclass__ = reflection.GeneratedProtocolMessageType DESCRIPTOR = _SCALEPARAMETER
_model def resnest50d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['resnest50d'] model = ResNet(ResNestBottleneck, [3, 4, 6, 3], num_classes=num_classes, in_chans=in_chans, stem_type='deep', stem_width=32, avg_down=True, base_width=64, cardinality=1, block_args=dict(radi...
def _export_inference_graph(input_type, detection_model, use_moving_averages, trained_checkpoint_prefix, output_directory, optimize_graph=False, output_collection_name='inference_op'): tf.gfile.MakeDirs(output_directory) frozen_graph_path = os.path.join(output_directory, 'frozen_inference_graph.pb') saved_m...
class AnnotationClip(Segmentation): def __init__(self, split, name, starting_frame, single_object, regex='*.png', lmdb_env=None): super(AnnotationClip, self).__init__(split, osp.join(get_anno_path(split), name), single_object, regex, lmdb_env=lmdb_env) self.starting_frame = starting_frame
def loss_fn(y_pred, y_true): return F.binary_cross_entropy_with_logits(y_pred, y_true.view((- 1), 1))
def jaccard_similarity(list1, list2): s1 = set(list1) s2 = set(list2) return (len(s1.intersection(s2)) / len(s1.union(s2)))
def number_of_symbols(pols): from phcpy.phcpy2c3 import py2c_scan_for_symbols inpols = ''.join(pols) return py2c_scan_for_symbols(len(inpols), inpols)
def best_probing_seed(task, ref_depth, list_ref_seeds): data_dict = pkl.load(open(scores_path, 'rb')) list_to_max = [np.mean(data_dict[task][seed][(ref_depth + 1)][0][0]) for seed in list_ref_seeds] (idx, _) = max(enumerate(list_to_max), key=(lambda x: x[1])) return list_ref_seeds[idx]
class Lambda(nn.Module): def __init__(self): super(Lambda, self).__init__() def forward(self, x): return x
def display_model(fname, renderView): model_1vtk = LegacyVTKReader(FileNames=[fname]) generateIds1 = GenerateIds(Input=model_1vtk) idsLUT = GetColorTransferFunction('Ids') generateIds1Display = Show(generateIds1, renderView) generateIds1Display.AmbientColor = [0.0, 0.0, 0.0] generateIds1Display....
def get_memory_settings(path, args): memory_prefix_list = [] jemalloc_prefix = 'LD_PRELOAD={}/intel_extension_for_transformers/llm/runtime/deprecated/third_party/jemalloc/lib/libjemalloc.so:$LD_PRELOAD '.format(path) if (args.memory_allocator == 'jemalloc'): memory_prefix_list.append(jemalloc_prefix...
class EarlyStopping(): def __init__(self, patience=7, verbose=False, delta=0): self.patience = patience self.verbose = verbose self.counter = 0 self.best_score = None self.early_stop = False self.val_loss_min = np.Inf self.delta = delta def __call__(self, ...
def generate_mask(x, x_len): if (False and (int(x_len.min()) == x.size(1))): mask = None else: mask = [] for l in x_len: mask.append(torch.zeros([x.size(1)]).byte().cuda()) mask[(- 1)][:l] = 1 mask = torch.stack(mask, 0) return mask
class Render(): def __init__(self, width=1600, height=1200, name='GL Renderer', program_files=['simple.fs', 'simple.vs'], color_size=1, ms_rate=1, egl=False): self.width = width self.height = height self.name = name self.use_inverse_depth = False self.egl = egl glEnab...
class MaskRCNNLossComputation(object): def __init__(self, proposal_matcher, discretization_size): self.proposal_matcher = proposal_matcher self.discretization_size = discretization_size def match_targets_to_proposals(self, proposal, target): match_quality_matrix = boxlist_iou(target, pro...
def _tokenize_str(str_): str_ = re.sub("[^A-Za-z0-9(),.!?\\'`]", ' ', str_) str_ = re.sub('\\s{2,}', ' ', str_) str_ = re.sub('\\(', ' ( ', str_) str_ = re.sub('\\)', ' ) ', str_) str_ = re.sub(',', ' , ', str_) str_ = re.sub('\\.', ' . ', str_) str_ = re.sub('!', ' ! ', str_) str_ = re....
_loss def l1_loss(pred, target): assert ((pred.size() == target.size()) and (target.numel() > 0)) loss = torch.abs((pred - target)) return loss
class InceptionV3Test(tf.test.TestCase): def testBuildClassificationNetwork(self): batch_size = 5 (height, width) = (299, 299) num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) (logits, end_points) = inception.inception_v3(inputs, num_classes) ...
def dla60x(**kwargs): return get_dla(levels=[1, 2, 3, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneckX, model_name='dla60x', **kwargs)
def _compute_log_a(q: float, sigma: float, alpha: float) -> float: if float(alpha).is_integer(): return _compute_log_a_for_int_alpha(q, sigma, int(alpha)) else: return _compute_log_a_for_frac_alpha(q, sigma, alpha)