code
stringlengths
101
5.91M
_model def ssl_resnet50(pretrained=True, **kwargs): model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) model.default_cfg = default_cfgs['ssl_resnet50'] if pretrained: load_pretrained(model, num_classes=kwargs.get('num_classes', 0), in_chans=kwargs.get('in_chans', 3)) return model
def preprocess_point_cloud(pcd, voxel_size): print((':: Downsample with a voxel size %.3f.' % voxel_size)) pcd_down = pcd.voxel_down_sample(voxel_size) radius_normal = (voxel_size * 2) print((':: Estimate normal with search radius %.3f.' % radius_normal)) pcd_down.estimate_normals(o3d.geometry.KDTre...
class PreTrainedTokenizer(object): vocab_files_names = {} pretrained_vocab_files_map = {} max_model_input_sizes = {} SPECIAL_TOKENS_ATTRIBUTES = ['bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', 'additional_special_tokens'] def bos_token(self): if (...
class GPTJOnnxConfig(OnnxConfigWithPast): def __init__(self, config: PretrainedConfig, task: str='default', patching_specs: List[PatchingSpec]=None, use_past: bool=False): super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past) if (not getattr(self._config, 'pad_token_i...
def actor_net(args, data=None): model = ActorNet(args) model.load_state_dict(data) return model
def functional_pulse(func): (func) def to_pulse(duration, *args, name=None, **kwargs): if (isinstance(duration, int) and (duration > 0)): samples = func(duration, *args, **kwargs) samples = np.asarray(samples, dtype=np.complex128) return SamplePulse(samples=samples, n...
def gen_backward(): head = '\n/**\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#include "lightconv_cuda.cuh"\n\nstd::vector<at::Tensor> lightconv_cuda_backward(\n ...
def test_digits_cosine_naive_init(): model = FacilityLocationSelection(100, 'cosine', optimizer='naive', initial_subset=digits_cosine_ranking[:5]) model.fit(X_digits) assert_array_equal(model.ranking[:(- 5)], digits_cosine_ranking[5:]) assert_array_almost_equal(model.gains[:(- 5)], digits_cosine_gains[5...
.parametrize('device', list_devices()) def test_to_linear_transform(device): TOL = {'rtol': 1e-07, 'atol': 1e-07} input_data = np.array((10, 25, 0, 13, 5, 40), dtype=np.uint8).reshape((2, 3, 1)) output_ref = (input_data / 255.0) negative_image_ref = (1.0 - (input_data / 255.0)) saturate_ref = np.arr...
class Composite(Null): def __init__(self, children=[], *args, **kwargs): super(Composite, self).__init__() self.children = children def write_fm(self, json_fm={}): for child in self.children: json_fm.update(child.write_fm(json_fm)) return json_fm def create_node_c...
def get_word2vec(args, word_counter): glove_path = os.path.join(args.glove_dir, 'glove.{}.{}d.txt'.format(args.glove_corpus, args.glove_vec_size)) sizes = {'6B': int(400000.0), '42B': int(1900000.0), '840B': int(2200000.0), '2B': int(1200000.0)} total = sizes[args.glove_corpus] word2vec_dict = {} wi...
def att_loss(pred, mask, p4, p5): g = flat(mask) np4 = torch.sigmoid(p4.detach()) np5 = torch.sigmoid(p5.detach()) p4 = flat(np4) p5 = flat(np5) w1 = torch.abs((g - p4)) w2 = torch.abs((g - p5)) w = (((w1 + w2) * 0.5) + 1) attbce = F.binary_cross_entropy_with_logits(pred, g, weight=(...
def test_data_processing_pipeline(processed_data: Dict[(str, Dict[(str, Any)])]) -> None: assert (processed_data == expected_processed_data)
class FakeQuantize(FakeQuantizeBase): def __init__(self, per_channel=False, num_bits=8, channel_axis=(- 1), symmetric=True, narrow_range=True): self.num_bits = num_bits self.per_channel = per_channel self.symmetric = symmetric self.narrow_range = narrow_range self.channel_axi...
class NetConstructor(): def __init__(self, fun_name, fun_module, args, kwds): self.fun_name = fun_name self.fun_module = fun_module self.args = args self.kwds = kwds def get(self): net_module = importlib.import_module(self.fun_module) net_fun = getattr(net_module,...
def add_distributed_training_args(parser, default_world_size=None): group = parser.add_argument_group('Distributed training') if (default_world_size is None): default_world_size = max(1, torch.cuda.device_count()) group.add_argument('--distributed-world-size', type=int, metavar='N', default=default_...
(from_config=_train_loader_from_config) def build_detection_train_loader(dataset, *, mapper, sampler=None, total_batch_size, aspect_ratio_grouping=True, num_workers=0, collate_fn=None): if isinstance(dataset, list): dataset = DatasetFromList(dataset, copy=False) if (mapper is not None): dataset ...
def seq_accuracy(preds, labels): acc = [] for (idx, pred) in enumerate(preds): acc.append((pred == labels[idx]).mean()) return acc.mean()
class GraphDataModule(pl.LightningDataModule): def __init__(self, graph_family, graph_kwargs=None, samples_per_epoch=100000, batch_size=32, distributed_sampler=True, num_workers=1): super().__init__() if (graph_kwargs is None): graph_kwargs = {} self.graph_family = graph_family ...
def level_2_pass_manager(transpile_config): basis_gates = transpile_config.basis_gates coupling_map = transpile_config.coupling_map initial_layout = transpile_config.initial_layout seed_transpiler = transpile_config.seed_transpiler backend_properties = transpile_config.backend_properties _given_...
def stride(init: float, step: float, times: int) -> Iterable[float]: for _ in range(times): (yield init) init += step
class Runner(): def __init__(self, params): self.params = params data = Triples() (self.entity2id, self.relation2id) = (data.entity2id, data.relation2id) self.train_triples = data.triples self.id2entity = {idx: ent for (ent, idx) in self.entity2id.items()} self.id2rel...
class OCNLI(CLSProcessor): def __init__(self): super().__init__(labels_origin=['entailment', 'contradiction', 'neutral'], labels_mapped=['', '', '']) def get_examples(self, data_dir, split): path = os.path.join(data_dir, f'{split}.json') with open(path, encoding='utf8') as f: ...
def test_config_build_detector(): from xdoctest.utils import import_module_from_path from mmdet.models import build_detector config_dpath = _get_config_directory() print('Found config_dpath = {!r}'.format(config_dpath)) config_names = ['dcn/mask_rcnn_dconv_c3-c5_r50_fpn_1x.py', 'htc/htc_without_sema...
def import_file(path, name: str=None, add_to_sys=True, disable_warning=False): global CUSTOM_LOADED_MODULES path = Path(path) module_name = path.stem try: user_paths = os.environ['PYTHONPATH'].split(os.pathsep) except KeyError: user_paths = [] possible_paths = _get_possible_modul...
def normlize_image(img): t_min = np.min(img) t_max = np.max(img) img = ((img - t_min) / (t_max - t_min)) return img
class ToyModel2(BaseModel): def __init__(self): super().__init__() self.teacher = ToyModel1() self.student = ToyModel1() def forward(self, *args, **kwargs): return self.student(*args, **kwargs)
class nnUNetTrainerV2_ReLU_biasInSegOutput(nnUNetTrainerV2): def initialize_network(self): if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d ...
def main(): torch.set_printoptions(profile='full') parser = argparse.ArgumentParser(description='mgp') parser.add_argument('--config_path', type=str, help='path of dataset', required=True) parser.add_argument('--seed', type=int, default=2021, help='overwrite config seed') parser.add_argument('--loca...
def _dm_nfnet_cfg(depths, channels=(256, 512, 1536, 1536), act_layer='gelu', skipinit=True): attn_kwargs = dict(reduction_ratio=0.5, divisor=8) cfg = NfCfg(depths=depths, channels=channels, stem_type='deep_quad', stem_chs=128, group_size=128, bottle_ratio=0.5, extra_conv=True, gamma_in_act=True, same_padding=Tr...
def gradient_penalty_loss(discriminator, real_data, fake_data, mask=None): batch_size = real_data.size(0) alpha = torch.rand(batch_size, 1, 1, 1).to(real_data) interpolates = ((alpha * real_data) + ((1.0 - alpha) * fake_data)) interpolates = autograd.Variable(interpolates, requires_grad=True) disc_i...
def get_chatgpt_completion_response(prompt_text, max_tokens): messages = [{'role': 'system', 'content': 'You are a helpful assistant that continues the passage from the sentences provided.'}, {'role': 'user', 'content': prompt_text}] response = openai.ChatCompletion.create(model='gpt-3.5-turbo', messages=messag...
class EdgeResidual(nn.Module): def __init__(self, in_chs, out_chs, exp_kernel_size=3, exp_ratio=1.0, fake_in_chs=0, stride=1, dilation=1, pad_type='', act_layer=nn.ReLU, noskip=False, pw_kernel_size=1, se_ratio=0.0, se_kwargs=None, norm_layer=nn.BatchNorm2d, norm_kwargs=None, drop_path_rate=0.0): super(Edge...
class RegionLayer(nn.Module): def __init__(self, num_classes=0, anchors=[], num_anchors=1, use_cuda=None): super(RegionLayer, self).__init__() use_cuda = (torch.cuda.is_available() and (True if (use_cuda is None) else use_cuda)) self.device = torch.device(('cuda' if use_cuda else 'cpu')) ...
class Segmentation(object): def __init__(self): self.segments = None self.stats = SegmenterStats() def initialize_segments(self, alignment, frame_shift=0.01): self.segments = [] assert (len(alignment) > 0) prev_label = None prev_length = 0 for (i, text_lab...
class ShrinkRatio(): def __init__(self, w_iter, decay_rate): self.w_iter = w_iter self.decay_rate = decay_rate def __call__(self, n_iter): return ((1 + (self.w_iter * n_iter)) ** (- self.decay_rate))
def baytune_get_setting(self): import warnings with warnings.catch_warnings(): warnings.filterwarnings('ignore', module='sklearn') if (len(self._methods) == 1): (method,) = self._methods else: possible_methods = {m: getattr(self._tuners[m], 'scores', ()) for m in ...
def load_car_model(path='models/templates/car.pth'): template = TemplateUV(L=10, num_layers=3, hidden_size=256) template.load_state_dict(torch.load(path)) return template
class TMScoreHead(nn.Module): def __init__(self, c_z, no_bins, **kwargs): super(TMScoreHead, self).__init__() self.c_z = c_z self.no_bins = no_bins self.linear = Linear(self.c_z, self.no_bins, init='final') def forward(self, z): logits = self.linear(z) return logi...
class DotProduct(Function): def forward(ctx, query, pos_enc, out_F, kq_map): assert (query.is_contiguous() and pos_enc.is_contiguous() and out_F.is_contiguous()) ctx.m = kq_map.shape[1] (_, ctx.h, ctx.c) = query.shape ctx.kkk = pos_enc.shape[0] ctx.save_for_backward(query, po...
class SqueezeBertModel(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
class Tile(): def __init__(self, x, y, name, data, interconn_xy, site_insts): self.x = x self.y = y self.name = name self.data = data self.interconn_xy = interconn_xy self.site_insts = site_insts self.wire_to_node = {} self.node_autoidx = 0 sel...
class CIFAR10Mix(torchvision.datasets.CIFAR10): def __init__(self, root, out_path, train=False, val=False, transform=None, target_transform=None, download=False): super(CIFAR10Mix, self).__init__(root, train=train, transform=transform, target_transform=target_transform, download=download) self.outpa...
_model def resnetrs152(pretrained=False, **kwargs): attn_layer = partial(get_attn('se'), rd_ratio=0.25) model_args = dict(block=Bottleneck, layers=[3, 8, 36, 3], stem_width=32, stem_type='deep', replace_stem_pool=True, avg_down=True, block_args=dict(attn_layer=attn_layer), **kwargs) return _create_resnet('r...
def fine_validation(epoch, training_loss): fine_model.eval() fine_validation_loss = 0 scale_invariant_loss = 0 delta1_accuracy = 0 delta2_accuracy = 0 delta3_accuracy = 0 rmse_linear_loss = 0 rmse_log_loss = 0 abs_relative_difference_loss = 0 squared_relative_difference_loss = 0 ...
def rouge_single_pair(cand: str, ref: str, metric='rouge1'): s = full_rouge_scorer.score(cand, ref) return s[metric].fmeasure
class TestMatcher(unittest.TestCase): def test_scriptability(self): cfg = get_cfg() anchor_matcher = Matcher(cfg.MODEL.RPN.IOU_THRESHOLDS, cfg.MODEL.RPN.IOU_LABELS, allow_low_quality_matches=True) match_quality_matrix = torch.tensor([[0.15, 0.45, 0.2, 0.6], [0.3, 0.65, 0.05, 0.1], [0.05, 0.4...
def main(): args = get_args() output_dir = 'output/{}'.format(get_datetime_str()) create_dir(output_dir) LogHelper.setup(log_path='{}/training.log'.format(output_dir), level='INFO') _logger = logging.getLogger(__name__) _logger.info('Finished setting up the logger.') save_yaml_config(vars(ar...
class DelayStartHook(TrainingHook, tf.train.GlobalStepWaiterHook): def __init__(self, params, model_dir, run_config): TrainingHook.__init__(self, params, model_dir, run_config) self._task_id = self._run_config.task_id self._delay_k = self.params['delay_k'] self._wait_until_step = int...
class PolynomialLR(_LRScheduler): def __init__(self, optimizer, step_size, iter_max, power, last_epoch=(- 1)): self.step_size = step_size self.iter_max = iter_max self.power = power super(PolynomialLR, self).__init__(optimizer, last_epoch) def polynomial_decay(self, lr): ...
def register_meta_overrides(orig_target, meta_target): _MANUAL_META_OVERRIDES[orig_target] = meta_target
class TestFoldPadConv(unittest.TestCase): def setUpClass(self): build_fake_yaml() def tearDownClass(self): os.remove('fake_yaml.yaml') _random() def test_fold_pad_conv(self): x = tf.compat.v1.placeholder(tf.float32, [1, 56, 56, 16], name='input') paddings = tf.constant([[...
def get_auto_estimator(backend='torch'): loss = ('mse' if backend.startswith('keras') else torch.nn.MSELoss()) auto_lstm = AutoLSTM(input_feature_num=input_feature_dim, output_target_num=output_feature_dim, past_seq_len=5, optimizer='Adam', loss=loss, metric='mse', hidden_dim=hp.grid_search([32, 64]), layer_num...
class Wav2Vec2ForCTC(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class GANTensorboardWriter(LearnerTensorboardWriter): def __init__(self, learn: GANLearner, base_dir: Path, name: str, loss_iters: int=25, hist_iters: int=500, stats_iters: int=100, visual_iters: int=100): super().__init__(learn=learn, base_dir=base_dir, name=name, loss_iters=loss_iters, hist_iters=hist_ite...
_pytest_unraisable_warning def test_python_alreadyset_in_destructor(monkeypatch, capsys): hooked = False triggered = [False] if hasattr(sys, 'unraisablehook'): hooked = True default_hook = sys.__unraisablehook__ def hook(unraisable_hook_args): (exc_type, exc_value, exc_tb...
class R_MSFM6(nn.Module): def __init__(self, x): super(R_MSFM6, self).__init__() self.convX11 = torch.nn.Sequential(nn.ReflectionPad2d(1), torch.nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=0, bias=True), torch.nn.LeakyReLU(inplace=True), nn.ReflectionPad2d(1), torch.n...
class struct_c__SA_state_battery_out_t(ctypes.Structure): _pack_ = True _fields_ = [('stateOfCharge', ctypes.c_double), ('current', ctypes.c_double)]
(config_name='real', config_path='../configs/bc') def train(cfg: omegaconf.DictConfig): assert (cfg.num_gpus == 1) cfg_dict = omegaconf_to_dict(cfg) print_dict(cfg_dict) if (not cfg.test): os.makedirs(cfg.logdir, exist_ok=True) dump_cfg(cfg, cfg.logdir) set_np_formatting() set_se...
class Resnet50_NL(nn.Module): def __init__(self, non_layers=[0, 1, 1, 1], stripes=[16, 16, 16, 16], non_type='normal', temporal=None): super(Resnet50_NL, self).__init__() original = models.resnet50(pretrained=True).state_dict() if (non_type == 'normal'): self.backbone = res.ResNe...
def nms(dets, thresh, force_cpu=False): if (dets.shape[0] == 0): return [] return nms_gpu(dets, thresh)
class CrossEntropyLoss(torch.nn.Module): def __init__(self, epsilon=0.1): super().__init__() self.epsilon = epsilon self.softmax = torch.nn.LogSoftmax(dim=(- 1)) def forward(self, x, target): prob = self.softmax(x) mean = (- prob.mean(dim=(- 1))) nll_loss = (- pro...
def set_schema_simulation_period(schema: dict, count: int, seed: int) -> Tuple[(dict, int, int)]: assert (1 <= count <= 365), 'count must be between 1 and 365.' np.random.seed(seed) filename = schema['buildings'][building_name]['carbon_intensity'] filepath = os.path.join(root_directory, filename) ti...
class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(ResNet, self).__init__() self.in_planes = 64 self.conv1 = conv3x3(3, 64) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) self.layer2 ...
class SideCamBlock(nn.Sequential): def __init__(self, in_channels, out_channels, use_batchnorm=True): conv1 = md.Conv2dReLU(in_channels, out_channels, kernel_size=1, padding=0, use_batchnorm=use_batchnorm) conv2 = md.Conv2dReLU(out_channels, out_channels, kernel_size=1, padding=0, use_batchnorm=use_...
class StatsBatchNorm(_BaseNormalization): def __init__(self, momentum=0.99, epsilon=0.001, update_stats=False, **kwargs): super(StatsBatchNorm, self).__init__(**kwargs) self.momentum = momentum self.epsilon = epsilon self.update_stats = update_stats def build(self, input_shape): ...
class ANN_seq_class(models.Sequential): def __init__(self, Nin, Nh, Nout): super().__init__() self.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,))) self.add(layers.Dense(Nout, activation='softmax')) self.compile(loss='categorical_crossentropy', optimizer='adam', metrics=[...
def _dressup_style(text: str, bold: bool=False, italics: bool=False) -> str: if (not (bold or italics)): return text unicode_type = 'math sans' if bold: unicode_type += ' bold' if italics: unicode_type += ' italic' try: text = dressuplite.convert(text, unicode_type=un...
def write_utts(tgt_dir, pair_list, wav_dict, text_dict): text_writer = open((tgt_dir + '/text'), 'w', encoding='utf-8') scp_writer = open((tgt_dir + '/wav.scp'), 'w', encoding='utf-8') def write_utt(path1, path2, path): (wave1, sr1) = torchaudio.load(path1) (wave2, sr2) = torchaudio.load(pat...
class Segment(object): def __init__(self, split_lines_of_utt, start_index, end_index, debug_str=None): self.split_lines_of_utt = split_lines_of_utt self.start_index = start_index self.end_index = end_index self.start_unk_padding = 0.0 self.end_unk_padding = 0.0 if (de...
class BoxCoder(object): __metaclass__ = ABCMeta def code_size(self): pass def encode(self, boxes, anchors): with tf.name_scope('Encode'): return self._encode(boxes, anchors) def decode(self, rel_codes, anchors): with tf.name_scope('Decode'): return self._d...
class SMPL(nn.Module): NUM_JOINTS = 23 NUM_BODY_JOINTS = 23 NUM_BETAS = 10 def __init__(self, model_path, data_struct=None, create_betas=True, betas=None, create_global_orient=True, global_orient=None, create_body_pose=True, body_pose=None, create_transl=True, transl=None, dtype=torch.float32, batch_siz...
def plot_scores(*scores: pd.DataFrame, width: int=800, height: int=600, ci: float=0.95) -> pn.layout.Panel: viewer = _JulearnScoresViewer(scores=[*scores], width=width, height=height, ci=ci) pn.extension(template='fast') dashboard_title = pn.panel('## Scores Viewer') logo = ((Path(__file__).parent / 're...
def convert_network(network, dtype): for module in network.modules(): if (isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and (module.affine is True)): continue convert_module(module, dtype) return network
def small_scale(run_name='small_scale'): logdir = os.path.join(BASE_LOGDIR, run_name) writer = tf.summary.create_file_writer(logdir) cube = o3d.geometry.TriangleMesh.create_box(1, 2, 4, create_uv_map=True) cube.compute_vertex_normals() cylinder = o3d.geometry.TriangleMesh.create_cylinder(radius=1.0,...
class Mse_Loss(): def __init__(self): return def compute_loss(self, y_input, y_target): return F.mse_loss(y_input, y_target)
class TransformerEncoderLayer(nn.Module): def __init__(self, args): super().__init__() self.embed_dim = args.encoder_embed_dim self.self_attn = MultiheadAttention(self.embed_dim, args.encoder_attention_heads, dropout=args.attention_dropout, self_attention=True) self.self_attn_layer_n...
class SearchAllLibCall(SearchAllCall): ignore_calls = ['tf.print', 'tf.constant', 'tf.zeros', 'tf.onestf.shape'] def __init__(self, lib_prefix: str): super().__init__() self.lib_prefix = lib_prefix def check_if_ignore(self, api_call) -> bool: return ((api_call in self.ignore_calls) o...
def put_local_dir_tree_to_remote(local_dir: str, remote_dir: str, over_write: Optional[bool]=False): if remote_dir.startswith('hdfs'): return file_utils.put_local_dir_tree_to_remote(local_dir=local_dir, remote_dir=remote_dir, over_write=over_write) elif remote_dir.startswith('s3'): access_key_id...
class TestTorchAlgoUtils(TfGraphTestCase): .parametrize('discount', [1, 0.95]) .parametrize('num_trajs', [1, 5]) .parametrize('gae_lambda', [0, 0.5, 1]) .parametrize('rewards_traj, baselines_traj', [(ONES, ZEROS), (PI_DIGITS, ARRANGE), (ONES, FIBS)]) def test_compute_advantages(self, num_trajs, disc...
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)) if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')): (model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: (model_args, data_arg...
def blocks(files, size=65536): while True: b = files.read(size) if (not b): break (yield b)
class PSRoIAlign(nn.Module): def __init__(self, output_size: int, spatial_scale: float, sampling_ratio: int): super(PSRoIAlign, self).__init__() self.output_size = output_size self.spatial_scale = spatial_scale self.sampling_ratio = sampling_ratio def forward(self, input: Tensor,...
def combine_beam(int_order, true_ref, out_path): result = [] for (idx, num) in enumerate(int_order): result.append(true_ref[num]) with open((out_path + '_ref'), 'w') as f: for elem in result: print(elem, file=f) return
def is_anonym_type(index: int, amr: AMR, text_map: Dict, types: List) -> bool: lemma = amr.lemmas[index] return ((lemma in text_map) and (text_map[lemma]['ner'] in types))
class Vocab(): def __init__(self, voc_path, max_size=None, min_freq=1): self.pad_index = 0 self.unk_index = 1 self.eos_index = 2 self.sos_index = 3 self.mask_index = 4 print('Building Vocab') self.itos = list(['<pad>', '<unk>', '<eos>', '<sos>', '<mask>']) ...
class CompositeMutation(Mutation[Solution]): def __init__(self, mutation_operator_list: [Mutation]): super(CompositeMutation, self).__init__(probability=1.0) Check.is_not_none(mutation_operator_list) Check.collection_is_not_empty(mutation_operator_list) self.mutation_operators_list =...
class UNet(nn.Module): def __init__(self, nPlanes, reps): super(UNet, self).__init__() assert (reps == 1) assert (len(nPlanes) == 3) self.res1 = conv_block(nPlanes[0], nPlanes[1]) self.res2 = conv_block(nPlanes[1], nPlanes[2]) self.bridge = bridge_block(nPlanes[2], nP...
def parse_nullable_value(value): if ((not value) or (value == '_')): return None return value
def create_logger(filepath): log_formatter = LogFormatter() if (filepath is not None): file_handler = logging.FileHandler(filepath, 'a') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(log_formatter) console_handler = logging.StreamHandler() console_handler.setLeve...
def learn_halut_multi_core_dict(dict_to_learn: dict[(str, list)], data_path: str, store_path: str, kmeans_options: dict={}, codebook: int=(- 1)) -> None: for (k, v) in dict_to_learn.items(): print('learning', k, v) conv2d_options = {'loop_order': 'im2col', 'kernel_size': (3, 3), 'stride': (1, 1), 'p...
class Sst2Processor(DataProcessor): def get_example_from_tensor_dict(self, tensor_dict): return InputExample(tensor_dict['idx'].numpy(), tensor_dict['sentence'].numpy().decode('utf-8'), None, str(tensor_dict['label'].numpy())) def get_train_examples(self, data_dir): return self._create_examples(...
class Scenario(BaseScenario): def make_world(self): world = World() world.dim_c = 4 num_good_agents = 2 num_adversaries = 4 num_agents = (num_adversaries + num_good_agents) num_landmarks = 1 num_food = 2 num_forests = 2 world.agents = [Agent() ...
def generate_labels(dataset, model, batch_size): with torch.no_grad(): preds = [] if isinstance(model, torch.nn.Module): device = next(model.parameters()).device else: device = torch.device('cpu') loader = DataLoader(dataset, batch_size=batch_size) for...
class GaussianSampler(ZooKerasLayer): def __init__(self, input_shape=None, **kwargs): super(GaussianSampler, self).__init__(None, (list(input_shape) if input_shape else None), **kwargs)
class CheckpointEngine(metaclass=ABCMeta): def __init__(self, checkpoint_dir: str): self.checkpoint_dir = checkpoint_dir if dist.is_initialized(): self._rank = dist.get_rank() self._loader_group = dist.new_group(backend='gloo') else: self._rank = 0 ...
class TestTranslationGPU(unittest.TestCase): def setUp(self): logging.disable(logging.CRITICAL) def tearDown(self): logging.disable(logging.NOTSET) ((not torch.cuda.is_available()), 'test requires a GPU') def test_fp16(self): with contextlib.redirect_stdout(StringIO()): ...
def galton_rvs(theta, n_runs=100, n_rows=n_rows, n_nails=n_nails, random_state=None): rng = check_random_state(random_state) all_x = [] all_log_p_xz = [] all_t_xz = [] trajectories = [] for i in range(n_runs): u = rng.rand(n_rows) (log_p_xz, (begin, z, x)) = trace(theta, u) ...
class Evaluator(nn.Module): 'adapted from def __init__(self): super().__init__() self.lpips = LearnedPerceptualImagePatchSimilarity(net_type='alex') self.psnr = PeakSignalNoiseRatio(data_range=1) self.ssim = StructuralSimilarityIndexMeasure(data_range=1) _fwd(cast_inputs=tor...
def report_to_dana(dana_util, item_name, metric_name, device, soc, abi, value, trend): serie_id = dana_util.create_serie_id_lite(TABLE_NAME, ('%s_%s_%s_%s_%s' % (metric_name, device, soc, abi, item_name))) dana_util.report_benchmark(serie_id=serie_id, value=value, trend=trend)