code
stringlengths
101
5.91M
def find_best_thresh(preds, scores, na_probs, qid_to_has_ans): num_no_ans = sum((1 for k in qid_to_has_ans if (not qid_to_has_ans[k]))) cur_score = num_no_ans best_score = cur_score best_thresh = 0.0 qid_list = sorted(na_probs, key=(lambda k: na_probs[k])) for (i, qid) in enumerate(qid_list): ...
class Configs(): def __init__(self, batch, instance, cores, weight_sharing, memory_allocator, memory_planning, cmds, mode): self.batch = batch self.instance = instance self.cores = cores self.weight_sharing = weight_sharing self.memory_allocator = memory_allocator sel...
def distort_image(image, height, width): distorted_image = tf.random_crop(image, [height, width, 3]) distorted_image = tf.image.random_flip_left_right(distorted_image) distorted_image = tf.image.random_brightness(distorted_image, max_delta=63) distorted_image = tf.image.random_contrast(distorted_image, ...
def idx2seqtype(idx): if (idx == 1): return 'mpii' elif (idx == 2): return 'bonn' elif (idx == 3): return 'mpiinew' else: assert False
def round_filters(config: EfficientNetConfig, num_channels: int): divisor = config.depth_divisor num_channels *= config.width_coefficient new_dim = max(divisor, ((int((num_channels + (divisor / 2))) // divisor) * divisor)) if (new_dim < (0.9 * num_channels)): new_dim += divisor return int(ne...
def init(exp_parent_dir, run_group=None): return global _g_session assert (_g_session is None), 'aim_wrapper.init() should be called only once.' _g_session = Session(repo=os.path.realpath(os.path.abspath(exp_parent_dir)), experiment=(run_group or 'default'), flush_frequency=64)
class HelenSegmentation(BaseDataset): NUM_CLASS = 11 def __init__(self, root='dataset/helen/', split='train', mode=None, transform=None, target_transform=None): super(HelenSegmentation, self).__init__(root, split, mode, transform, target_transform, base_size=256, crop_size=256) _mask_dir = os.pa...
class PatchGANDiscriminator(DiscriminatorEnsemble): def __init__(self, cfg): self._parse_config(cfg) configs = ([(3, 64, self._max_dim, self._num_layers, self._num_layers)] * self._num_discs) super(PatchGANDiscriminator, self).__init__(make_disc_backbones(configs)) self._log = loggin...
class BaseLoader(): def __init__(self): pass def prepare(self): raise NotImplementedError def get_num_images(self): raise NotImplementedError def get_patch_batch(self, batch_size, scale, input_patch_size): raise NotImplementedError def get_random_image_patch_pair(self...
class RougeL(Rouge): def __init__(self, **kwargs): super(RougeL, self).__init__(rouges=['rougeL'])
def test_audio_datamodule_prepare_unprocessed_downloaded(fs, mocker): mocked_download = mocker.patch(f'{TESTED_MODULE}.data_utils.download_full_dataset') mocked_preprocess = mocker.patch(f'{TESTED_MODULE}.AudioDataModule.preprocess_dataset') data = AudioDataModule() fs.create_dir(data.data_dir_unprocess...
def get_pip_packages(run_lambda): def run_with_pip(pip): if (get_platform() == 'win32'): system_root = os.environ.get('SYSTEMROOT', 'C:\\Windows') findstr_cmd = os.path.join(system_root, 'System32', 'findstr') grep_cmd = '{} /R "numpy torch mypy"'.format(findstr_cmd) ...
_model def mobilenetv2_120d(pretrained=False, **kwargs): model = _gen_mobilenet_v2('mobilenetv2_120d', 1.2, depth_multiplier=1.4, fix_stem_head=True, pretrained=pretrained, **kwargs) return model
def main(_): eps = (((1.0 * FLAGS.max_epsilon) / 256.0) / FLAGS.max_iter) mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True) tf.reset_default_graph() caps_net = CapsNet(mnist) caps_net.creat_architecture() config = tf.ConfigProto() config.gpu_options.allow_growth = True trai...
def main(root: _path_type): root_: Path = path2Path(root) assert (root_.is_dir() and root_.exists()), root exp_list = find_experiment_list(root_) print(f'Found {len(exp_list)} experiments.') failed_exp_list = [x for x in exp_list if (not is_experiment_sucessed(x))] print(f'Found {len(failed_exp_...
def _compute_scales(A): norm = matrix_1_norm(A) max_norm = torch.max(norm) s = torch.zeros_like(norm) if (A.dtype == torch.float64): if A.requires_grad: ell = {3: 0., 5: 0., 7: 0., 9: 1., 13: 4.} else: ell = {3: 0., 5: 0., 7: 0., 9: 2., 13: 5.} if (max_nor...
class MSRResNet(nn.Module): def __init__(self, in_nc=3, out_nc=3, nf=64, nb=16, upscale=4): super(MSRResNet, self).__init__() self.upscale = upscale self.conv_first = nn.Conv2d(in_nc, nf, 3, 1, 1, bias=True) basic_block = functools.partial(mutil.ResidualBlock_noBN, nf=nf) sel...
class MarkupLMForSequenceClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class TestTokenizers(): def test_gpt_tokenizer(self): tokenizers = ['gpt2', 'bert-base-uncased'] model_name = 'distilgpt2' config = util.load_config(model_name) tokenizer = AutoTokenizer.from_pretrained(tokenizers[0]) token_ids = tokenizer(' tokenization')['input_ids'] ...
class QMsumDataset(SummDataset): dataset_name = 'QMsum' description = '\n QMSum is a new human-annotated benchmark for query-based multi-domain meeting summarization task,\n which consists of 1,808 query-summary pairs over 232 meetings in multiple domains.\n ' is_dialogue_based = True is_multi_...
class ResNet_IBN(nn.Module): def __init__(self, last_stride, block, layers, num_classes=1000): scale = 64 self.inplanes = scale super(ResNet_IBN, self).__init__() self.conv1 = nn.Conv2d(3, scale, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(scale)...
def add_displace_modifier(mesh_object: bpy.types.Object, texture_name: str, vertex_group: str='', mid_level: float=0.5, strength: float=1.0) -> None: modifier = mesh_object.modifiers.new(name='Displace', type='DISPLACE') modifier.mid_level = mid_level modifier.strength = strength modifier.texture = bpy....
class GLJudge(object): def __init__(self): print('loading ping and ze dict.txt') f = open('data/pingsheng.txt', 'r') self.__ping = f.read() f.close() self.__ping = self.__ping f = open('data/zesheng.txt', 'r') self.__ze = f.read() f.close() sel...
def average_weights(w): w_avg = copy.deepcopy(w[0]) for key in w_avg.keys(): for i in range(1, len(w)): w_avg[key] += w[i][key] w_avg[key] = torch.div(w_avg[key], float(len(w))) return w_avg
class ShakeBlock(nn.Module): def __init__(self, in_ch, out_ch, stride=1): super(ShakeBlock, self).__init__() self.equal_io = (in_ch == out_ch) self.shortcut = ((self.equal_io and None) or Shortcut(in_ch, out_ch, stride=stride)) self.branch1 = self._make_branch(in_ch, out_ch, stride) ...
def _DGStrat_makeSequence(l: Iterable[DGStrat]) -> DGStrat: return _DGStrat_makeSequence_orig(_wrap(libpymod._VecDGStrat, l))
class Identical(nn.Module): def __init__(self) -> None: super().__init__() def forward(self, input): return input
class ConcatData(DataFlow): def __init__(self, df_lists): self.df_lists = df_lists def reset_state(self): for d in self.df_lists: d.reset_state() def size(self): return sum([x.size() for x in self.df_lists]) def get_data(self): for d in self.df_lists: ...
def gen_description(rule1_cat, d1, rule2_cat, d2): cat_order = ['size', 'color', 'material', 'shape'] if (cat_order.index(rule1_cat) > cat_order.index(rule2_cat)): (rule1_cat, rule2_cat) = (rule2_cat, rule1_cat) (d1, d2) = (d2, d1) d = ((d1 + ' ') + d2) if (rule2_cat != 'shape'): ...
def save_checkpoint(cfg: CheckpointConfig, trainer, epoch_itr, val_loss): from fairseq import meters if (trainer.data_parallel_rank == 0): os.makedirs(cfg.save_dir, exist_ok=True) prev_best = getattr(save_checkpoint, 'best', val_loss) if (val_loss is not None): best_function = (max if cf...
class SpecAugment(torch.nn.Module): def __init__(self, freq_mask=20, time_mask=50, freq_stripes=2, time_stripes=2, p=1.0): super().__init__() self.p = p self.freq_mask = freq_mask self.time_mask = time_mask self.freq_stripes = freq_stripes self.time_stripes = time_str...
def resnet50_k(channel_k=32): print('Constructing resnet50_k......') model = ResNet_k(Bottleneck, [3, 4, 6, 3], channel_k=channel_k) return model
class FlowControllerLinear(FlowController): def __init__(self, passes, options): self.passes = self._passes = passes self.options = options
def transform(t): return ''.join([i for i in t if (not i.isdigit())]).translate(table).strip(' ').lower()
class PerResidueLDDTCaPredictor(nn.Module): def __init__(self, no_bins, c_in, c_hidden): super(PerResidueLDDTCaPredictor, self).__init__() self.no_bins = no_bins self.c_in = c_in self.c_hidden = c_hidden self.layer_norm = LayerNorm(self.c_in) self.linear_1 = Linear(se...
def save_data(test_data_dir, prefix, names, data_list): if (isinstance(data_list, torch.autograd.Variable) or isinstance(data_list, torch.Tensor)): data_list = [data_list] for (i, d) in enumerate(data_list): d = d.data.cpu().numpy() save_tensor_proto(os.path.join(test_data_dir, '{0}_{1}....
def _get_info_from_anaconda_info(info, split=':'): info = info.strip('\n').replace(' ', '') info_dict = {} latest_key = '' for line in info.splitlines(): if (split in line): pair = line.split(split) info_dict[pair[0]] = pair[1] latest_key = pair[0] els...
class _SwapAlign2Nat(Function): def forward(ctx, X, lambda_val, pad_val): ctx.lambda_val = lambda_val ctx.input_shape = X.size() Y = _C.swap_align2nat_forward(X, lambda_val, pad_val) return Y _differentiable def backward(ctx, gY): lambda_val = ctx.lambda_val (...
def _close_handlers(logger: logging.Logger) -> None: for handler in list(logger.handlers): if isinstance(handler, (logging.FileHandler, logging.StreamHandler)): if isinstance(handler, logging.FileHandler): handler.close() logger.removeHandler(handler)
class EMAParametersFunc(torch.autograd.Function): def forward(ctx: FunctionCtx, p: torch.Tensor, q: torch.Tensor, gamma: torch.Tensor, h: Optional[torch.Tensor], length: int) -> Tuple[(torch.Tensor, Optional[torch.Tensor])]: with torch.no_grad(): log_q = q.log() (weight, bias, vander) = ...
class AttentionLayerBahdanauTest(AttentionLayerTest): def _create_layer(self): return AttentionLayerBahdanau(params={'num_units': self.attention_dim}, mode=tf.contrib.learn.ModeKeys.TRAIN) def test_layer(self): self._test_layer()
_module() class MobileNetV2(BaseBackbone): arch_settings = [[1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 2], [6, 64, 4, 2], [6, 96, 3, 1], [6, 160, 3, 2], [6, 320, 1, 1]] def __init__(self, widen_factor=1.0, out_indices=(7,), frozen_stages=(- 1), conv_cfg=None, norm_cfg=dict(type='BN'), act_cfg=dict(type='ReLU6'), ...
def llama_copy_state_data(ctx: llama_context_p, dst) -> int: return _lib.llama_copy_state_data(ctx, dst)
class NpzDataset(object): def __init__(self, name): self.name = os.path.expanduser(name) try: os.mkdir(name) except OSError: pass def write(self, example, i, r, image_type=None): if (r > 0.0): status = 'success' else: status...
class DefaultObservable(Observable): def __init__(self): self.observers = [] def register(self, observer: Observer): if (observer not in self.observers): self.observers.append(observer) def deregister(self, observer: Observer): if (observer in self.observers): ...
def mlp(t_in, widths, final_nonlinearity=False): weights = [] prev_width = t_in.get_shape()[(- 1)] prev_layer = t_in for (i_layer, width) in enumerate(widths): v_w = tf.get_variable(('w%d' % i_layer), shape=(prev_width, width), initializer=tf.uniform_unit_scaling_initializer(factor=RELU_SCALE)) ...
def encrypt_with_AES_CBC(plain_text, secret_key, salt, key_len=128, block_size=16): ct_bytes = encrypt_bytes_with_AES_CBC(plain_text.encode(), secret_key, salt, key_len, block_size) return base64.b64encode(ct_bytes).decode()
def _update_args(objs, obj_pos): for (obj, pos) in zip(objs, obj_pos): (_, arg, idx) = pos arg[idx] = obj
def run_fn_for_gptq(model, dataloader_for_calibration, *args): logger.info('Collecting calibration inputs...') for batch in tqdm(dataloader_for_calibration): batch = move_input_to_device(batch, device=None) try: if (isinstance(batch, tuple) or isinstance(batch, list)): ...
def parse_cmd_options(argv, opt=None): parser = argparse.ArgumentParser() parser.add_argument('--plainnet_struct', type=str, default=None, help='PlainNet structure string') parser.add_argument('--plainnet_struct_txt', type=str, default=None, help='PlainNet structure file name') parser.add_argument('--nu...
_module() class CyclicLrUpdaterHook(LrUpdaterHook): def __init__(self, by_epoch=False, target_ratio=(10, 0.0001), cyclic_times=1, step_ratio_up=0.4, anneal_strategy='cos', gamma=1, **kwargs): if isinstance(target_ratio, float): target_ratio = (target_ratio, (target_ratio / 100000.0)) eli...
def bias_variable(shape, pos_initial_bias): if pos_initial_bias: values = tf.abs(tf.truncated_normal(shape, stddev=0.1)) else: values = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(values)
def digit_version(version_str: str, length: int=4): version = parse(version_str) assert version.release, f'failed to parse version {version_str}' release = list(version.release) release = release[:length] if (len(release) < length): release = (release + ([0] * (length - len(release)))) i...
class BertAttention(nn.Module): def __init__(self, config): super(BertAttention, self).__init__() self.self = BertSelfAttention(config) self.output = BertSelfOutput(config) def prune_heads(self, heads): if (len(heads) == 0): return mask = torch.ones(self.self....
class DeleteObjCommand(BaseUserCommand): def run(self): token = HfFolder.get_token() if (token is None): print('Not logged in') exit(1) try: self._api.delete_obj(token, filename=self.args.filename) except HTTPError as e: print(e) ...
def get_mixins(kernel): if isinstance(kernel, gp_models.GeneralizedProjectionKernel): mixins = [] for k in kernel.kernel.kernels: mixins.append(k.outputscale.item()) return mixins elif isinstance(kernel, gpytorch.kernels.ScaleKernel): return get_mixins(kernel.base_ker...
_module() class PISASSDHead(SSDHead): def loss(self, cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore=None): featmap_sizes = [featmap.size()[(- 2):] for featmap in cls_scores] assert (len(featmap_sizes) == self.prior_generator.num_levels) device = cls_scores[0].devic...
def get_sys_writer_function(args): def writer_fn(num_round, ids, metrics, groups, num_samples): metrics_writer.print_metrics(num_round, ids, metrics, groups, num_samples, 'train', args.metrics_dir, '{}_{}'.format(args.metrics_name, 'sys')) return writer_fn
class rigid_SURREAL_for_Ours_full_permute(torch.utils.data.Dataset): def __init__(self, args, file_name, transform=None, soft_label=False, show=False, pick_out=None, train=None, npoints=None, ratio_list=[0.02, 0.04, 0.06, 0.08, 0.1], gaussian_noise=False, partition='train', factor=4): self.args = args ...
def test_isotropic_nfw_widrow_against_improved(): pot = potential.NFWPotential(amp=2.3, a=1.3) dfp = isotropicNFWdf(pot=pot) dfpw = isotropicNFWdf(pot=pot, widrow=True) Es = numpy.linspace(((- dfp._Etildemax) * 0.999), 0, 101, endpoint=False) assert numpy.all((numpy.fabs((1.0 - (dfp.fE(Es) / dfpw.fE...
def wrap_main(main_fn): world_size = torch.cuda.device_count() def main(**args): if ('RANK' in os.environ): mp.set_start_method('spawn') _torchrun_worker_fn(main_fn, args) else: os.environ['PYTHONUNBUFFERED'] = '1' os.environ['MASTER_ADDR'] = 'loca...
def main(): cfg = load_config(FLAGS.config) merge_config(FLAGS.opt) check_config(cfg) check_gpu(cfg.use_gpu) check_version() main_arch = cfg.architecture dataset = cfg.TestReader['dataset'] test_images = get_test_images(FLAGS.infer_dir, FLAGS.infer_img) dataset.set_images(test_images...
class StateCacher(object): def __init__(self, in_memory, cache_dir=None): self.in_memory = in_memory self.cache_dir = cache_dir if (self.cache_dir is None): import tempfile self.cache_dir = tempfile.gettempdir() elif (not os.path.isdir(self.cache_dir)): ...
def test_streamspraydf_setup_paramsAsQuantity(): from galpy.df import streamspraydf from galpy.orbit import Orbit from galpy.potential import LogarithmicHaloPotential from galpy.util import conversion (ro, vo) = (8.0, 220.0) lp = LogarithmicHaloPotential(normalize=1.0, q=0.9) obs = Orbit([1....
def ether_lock_can_send(op, stack, trace, debug): if (op in ['SUICIDE']): global stop_search MyGlobals.stop_search = True return (True, True) elif (MyGlobals.ETHER_LOCK_GOOD_IF_CAN_CALL and (op in ['CALL', 'CALLCODE', 'DELEGATECALL'])): global stop_search MyGlobals.stop_s...
class testLosses(unittest.TestCase): def setUp(self): self.device = torch.device('cuda:1') def testCase1(self): max_disp = 5 start_disp = (- 2) dilation = 2 (h, w) = (3, 4) d = (((max_disp + dilation) - 1) // dilation) variance = 2 gtDisp = ((torch...
class RealmTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, do_lowe...
class SGD(Optimizer): def __init__(self, params, lr=required, momentum=0, dampening=0, weight_decay=0, nesterov=False): if ((lr is not required) and (lr < 0.0)): raise ValueError('Invalid learning rate: {}'.format(lr)) if (momentum < 0.0): raise ValueError('Invalid momentum v...
def checkout_commit(repo, commit_id): current_head = (repo.head.commit if repo.head.is_detached else repo.head.ref) try: repo.git.checkout(commit_id) (yield) finally: repo.git.checkout(current_head)
def load_gguf_baichuan(loader: GGUFFileLoader, dtype: torch.dtype=torch.float): config = loader.config baichuan_config = BaiChuanConfig(vocab_size=len(config['tokenizer.ggml.tokens']), hidden_size=config['baichuan.embedding_length'], intermediate_size=config['baichuan.feed_forward_length'], num_hidden_layers=co...
class TestPadding(): .parametrize('mode', ['silence', 'wrap', 'reflect']) .parametrize('pad_section', ['start', 'end']) def test_padding_mono_1d(self, mode, pad_section): random.seed(546) samples = np.array([0.5, 0.6, (- 0.2), 1.0], dtype=np.float32) sample_rate = 16000 input...
class ProcessModelAction(nn.Module): def __init__(self, num_ensemble, dim_x, dim_a): super(ProcessModelAction, self).__init__() self.num_ensemble = num_ensemble self.dim_x = dim_x self.dim_a = dim_a self.bayes1 = LinearFlipout(in_features=self.dim_x, out_features=64) ...
def match_ion_state(line, all_lines): matches = match_ion_state_all(line, all_lines) N_matches = len(matches) if (N_matches == 0): msg = 'No matches found!' line_match = None elif (N_matches == 1): line_match = matches[0] msg = ('Found 1 match: %s' % line_match.tag) e...
class NATSpeechToTextDatasetCreator(SpeechToTextDatasetCreator): DEFAULT_TGT_TEXT = '' def _from_list(cls, split_name: str, is_train_split, samples: List[Dict], cfg: S2TDataConfig, tgt_dict, pre_tokenizer, bpe_tokenizer, n_frames_per_step, speaker_to_id, multitask: Optional[Dict]=None) -> NATSpeechToTextDataset...
.unused def vflip(img): if (not _is_pil_image(img)): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) return img.transpose(Image.FLIP_TOP_BOTTOM)
(version='2.0') class Distillation(Component): def __init__(self, conf_fname_or_obj=None): super(Distillation, self).__init__() if isinstance(conf_fname_or_obj, DistillationConf): self.conf = conf_fname_or_obj elif isinstance(conf_fname_or_obj, Config): self.conf = Di...
class Triples(): def __init__(self, data_dir='../code/triples'): self.data = self.load_data(data_dir) (self.entities, self.entity2id) = self.get_entities(self.data) (self.attributes, self.attribute2id) = self.get_attributes(self.data) (self.relations, self.relation2id) = self.get_rel...
class ShapeEncoderPC(nn.Module): def __init__(self, feature_dim=1024): super(ShapeEncoderPC, self).__init__() self.conv1 = torch.nn.Conv1d(3, 64, 1) self.conv2 = torch.nn.Conv1d(64, 128, 1) self.conv3 = torch.nn.Conv1d(128, feature_dim, 1) self.bn1 = torch.nn.BatchNorm1d(64) ...
def conv3x3(in_channels, out_channels, groups=1, stride=1): return nn.Conv2d(in_channels, out_channels, kernel_size=3, groups=groups, stride=stride, padding=1)
def main(args): files = [f for f in os.listdir(args.mmcif_dir) if ('.cif' in f)] fn = partial(parse_file, args=args) data = {} with Pool(processes=args.no_workers) as p: with tqdm(total=len(files)) as pbar: for d in p.imap_unordered(fn, files, chunksize=args.chunksize): ...
def order_sequence(tokens, start, end, variables): cpos = (start + 1) chunks = [(start, start)] in_quote = False while (cpos < end): for part in tokens[cpos].split('"'): in_quote = (not in_quote) in_quote = (not in_quote) sub = subquery_range(None, cpos, tokens, in_qu...
def xresnet34_2(pretrained=False, **kwargs): model = XResNet(BasicBlock, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['xresnet34'])) return model
def astroNNPath(dr=None): if (dr is None): dr = _default_dr() if (int(dr) < 14): raise ValueError('astroNN catalog for DR<14 not available') specReduxPath = apogeeSpectroReduxDirPath(dr=dr) if (dr == '14'): return os.path.join(specReduxPath, 'r8', 'stars', 'l31c', _redux_dr(dr=dr...
class GraphConvolution(nn.Module): def __init__(self, in_features, out_features, bias=True): super(GraphConvolution, self).__init__() self.in_features = in_features self.out_features = out_features self.weight = Parameter(torch.FloatTensor(in_features, out_features)) if bias:...
class NoiseResNet(nn.Module): def __init__(self, block, nblocks, nfilters, nclasses, pool, level, first_filter_size=3): super(NoiseResNet, self).__init__() self.in_planes = nfilters if (first_filter_size == 7): pool = 1 self.pre_layers = nn.Sequential(nn.Conv2d(3, nfi...
def load_model(teacher_str, student_str, dataset, device, ensemble): if ((dataset == 'cifar10') or (dataset == 'svhn')): num_classes = 10 elif (dataset == 'cifar100'): num_classes = 100 elif (dataset == 'tiny-imagenet'): num_classes = 200 elif (dataset == 'imagenet'): num...
def call_main(cfg: FairseqConfig, main, **kwargs): if (cfg.distributed_training.distributed_init_method is None): infer_init_method(cfg.distributed_training) if (cfg.distributed_training.distributed_init_method is not None): if (not cfg.distributed_training.distributed_no_spawn): sta...
def load_jsonl(file: Union[(str, Path)]) -> Iterable[Any]: with open(file, 'r', encoding='utf-8') as f: for line in f: try: (yield json.loads(line)) except: print('Error in loading:', line) exit()
class Env(object): metadata = {'render.modes': []} reward_range = ((- float('inf')), float('inf')) spec = None action_space = None observation_space = None def step(self, action): raise NotImplementedError def reset(self): raise NotImplementedError def render(self, mode='...
def resnet18_full(pretrained=False, **kwargs): model = ResNet_Full(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model
class ClassifierChoice(AutotabularChoice): def get_components(cls): components = OrderedDict() components.update(_classifiers) components.update(_addons.components) return components def get_available_components(cls, dataset_properties=None, include=None, exclude=None): i...
class NodeDistributedSampler(Sampler): def __init__(self, dataset, num_replicas=None, rank=None, local_rank=None, local_size=None, shuffle=True): if (num_replicas is None): if (not dist.is_available()): raise RuntimeError('Requires distributed package to be available') ...
class CNN(nn.Module): def __init__(self, pretrained=False, in_channel=1, out_channel=10): super(CNN, self).__init__() if (pretrained == True): warnings.warn('Pretrained model is not available') self.layer1 = nn.Sequential(nn.Conv1d(in_channel, 16, kernel_size=15), nn.BatchNorm1d(...
def get_dates(min_year, max_year): lo = date(min_year, 3, 1) hi = date(max_year, 11, 10) def date_to_str(d): return d[0].strftime('%Y-%m-%d') dates = [date_to_str(d) for d in date_range(lo, hi, 1) if (date_to_str(d) not in already_done)] return dates
def test_DropColumns() -> None: drop_columns = DropColumns(apply_to=['confound']) drop_columns.fit(X_with_types) X_trans = drop_columns.transform(X_with_types) support = drop_columns.get_support() non_confound = ['a__:type:__continuous', 'b__:type:__continuous', 'e__:type:__categorical', 'f__:type:_...
def conv_flops_counter_hook(conv_module, input, output): input = input[0] batch_size = input.shape[0] (output_height, output_width) = output.shape[2:] (kernel_height, kernel_width) = conv_module.kernel_size in_channels = conv_module.in_channels out_channels = conv_module.out_channels groups ...
def _superimpose_single(reference, coords): reference_np = reference.detach().cpu().numpy() coords_np = coords.detach().cpu().numpy() (superimposed, rmsd) = _superimpose_np(reference_np, coords_np) return (coords.new_tensor(superimposed), coords.new_tensor(rmsd))
def get_bel_type_override(bt): if (bt.endswith('6LUT') or (bt == 'LUT_OR_MEM6') or (bt == 'LUT6')): return 'SLICE_LUTX' elif (bt.endswith('5LUT') or (bt == 'LUT_OR_MEM5') or (bt == 'LUT5')): return 'SLICE_LUTX' elif ((len(bt) == 4) and bt.endswith('FF2')): return 'SLICE_FFX' elif...
class ToNumpy(): def __call__(self, pil_img): np_img = np.array(pil_img, dtype=np.uint8) if (np_img.ndim < 3): np_img = np.expand_dims(np_img, axis=(- 1)) np_img = np.rollaxis(np_img, 2) return np_img
def duplicate_dual_clean_bn(model): found_noise_bn = False if (not isinstance(model, dict)): model_state_dict = model.state_dict() else: model_state_dict = model for key in model_state_dict: if ('noise_bn' in key): found_noise_bn = True clean = model_state...