code
stringlengths
101
5.91M
def test_audio(): audio_path = os.path.join(os.path.dirname(__file__), 'jfk.flac') audio = load_audio(audio_path) assert (audio.ndim == 1) assert ((SAMPLE_RATE * 10) < audio.shape[0] < (SAMPLE_RATE * 12)) assert (0 < audio.std() < 1) mel_from_audio = log_mel_spectrogram(audio) mel_from_file ...
def _graph_and_latents_collate_func(args): (graphs, latent_space) = zip(*args) all_graphs = graphs[0].concatenate(graphs) latent_space = torch.from_numpy(np.stack(latent_space)) return (all_graphs, latent_space)
_lr_scheduler('tri_stage') class TriStageLRSchedule(FairseqLRScheduler): def __init__(self, args, optimizer): super().__init__(args, optimizer) if (len(args.lr) > 1): raise ValueError('Cannot use a fixed learning rate schedule with tri-stage lr. Consider --lr-scheduler=fixed instead.') ...
.parametrize('archive_type', ['grid', 'cvt', 'sliding', 'cvt_3d']) .parametrize('invalid_arg_cbar', ['None', 3.2, True, (3.2, None), [3.2, None]]) def test_heatmap_fails_on_invalid_cbar_option(archive_type, invalid_arg_cbar): archive = {'grid': (lambda : GridArchive(solution_dim=2, dims=[20, 20, 20], ranges=([((- 1...
class RejectionLog(): def __init__(self, file): self.file = file self.initialized = False def initialize_rejection_log(self, forest): raise RejectionLogError("Function 'initialize_rejection_log' was not overloaded by child class") def add_to_rejection_log(self, forest, rejection_stat...
def test_importing(): from pybind11_tests.modules import OD from collections import OrderedDict assert (OD is OrderedDict) assert (str(OD([(1, 'a'), (2, 'b')])) == "OrderedDict([(1, 'a'), (2, 'b')])")
class InvertedResidual(nn.Module): def __init__(self, in_channels, out_channels, stride, expand_ratio, dilation=1, conv_cfg=None, norm_cfg=dict(type='BN'), act_cfg=dict(type='ReLU6'), with_cp=False): super(InvertedResidual, self).__init__() self.stride = stride assert (stride in [1, 2]), f's...
def test_audio_dataset_init_val(fs, mocker): dataset = audio_dataset(fs, mocker, split='val') assert (len(dataset.file_list) == 10)
def create_optimizer(config, logger, model_params, state_dict=None): assert ('lr' in config.optim_params) config.optim_params.lr = float(config.optim_params.lr) if hasattr(torch.optim, config.optimizer): optim = getattr(torch.optim, config.optimizer) elif hasattr(torch_optimizer, config.optimize...
def parse_opt(): parser = argparse.ArgumentParser() parser.add_argument('--dataset', type=str, default='flickr', help='coco|flickr') parser.add_argument('--input_json', type=str, default='data/flickrtalk.json', help='path to the json file containing additional info and vocab') parser.add_argument('--inp...
def _bonferroni(p_values, num_comparison): adjust = np.vectorize((lambda pv: min(1.0, (pv * num_comparison)))) adjusted_p_values = adjust(p_values) assert np.all((adjusted_p_values[(~ np.isnan(adjusted_p_values))] <= 1.0)) assert np.all((adjusted_p_values[(~ np.isnan(adjusted_p_values))] >= 0.0)) re...
class VGGnet_test(Network): def __init__(self, trainable=True): self.inputs = [] self.data = tf.placeholder(tf.float32, shape=[None, None, None, 3]) self.im_info = tf.placeholder(tf.float32, shape=[None, 3]) self.keep_prob = tf.placeholder(tf.float32) self.layers = dict({'dat...
class NgramCounts(object): def __init__(self, ngram_order): self.ngram_order = ngram_order self.bos_symbol = (- 3) self.eos_symbol = (- 2) self.backoff_symbol = (- 1) self.counts = [] for n in range(ngram_order): self.counts.append(defaultdict((lambda : de...
class SenseRemover(): def __init__(self, node_utils): self.node_utils = node_utils self.stemmer = nltk.stem.SnowballStemmer('english').stem self.removed_instance_count = 0 self.amr_instance_count = 0 self.restore_count = 0 self.not_removed_instances = set() def re...
class MeanSquaredLogarithmicError(LossFunction): def __init__(self, bigdl_type='float'): super(MeanSquaredLogarithmicError, self).__init__(None, bigdl_type)
def generate_batch_splits(samples_idx: np.ndarray, batch_size: int) -> np.ndarray: nb_samples = len(samples_idx) samples_to_remove = (nb_samples % batch_size) if (samples_to_remove != 0): samples_idx = samples_idx[:(- samples_to_remove)] sections_split = (nb_samples // batch_size) batch_idx ...
def vgg13(num_classes=1000, pretrained='imagenet'): model = models.vgg13(pretrained=False) if (pretrained is not None): settings = pretrained_settings['vgg13'][pretrained] model = load_pretrained(model, num_classes, settings) return model
def get_loss_one_logit(student_logit, teacher_logit): t = 2.0 from torch.nn import functional as F return (F.kl_div(input=F.log_softmax((student_logit / t), dim=(- 1)), target=F.softmax((teacher_logit / t), dim=(- 1)), reduction='batchmean') * (t ** 2))
def ncompute(openfilepath): with open(openfilepath, encoding='utf-8') as f: id = 0 reader = pd.read_csv(f) data = {} for i in range(0, len(reader)): id = reader.iloc[i]['ID'] mn = reader.iloc[i]['Metric Name'] if (mn == 'gpu__time_duration.sum'): ...
def _add_variables_summaries(learning_rate): summaries = [] for variable in slim.get_model_variables(): summaries.append(tf.summary.histogram(variable.op.name, variable)) summaries.append(tf.summary.scalar('training/Learning Rate', learning_rate)) return summaries
def score_hard_rationale_predictions(truth: List[Rationale], pred: List[Rationale]) -> Dict[(str, Dict[(str, float)])]: scores = dict() truth = set(truth) pred = set(pred) micro_prec = (len((truth & pred)) / len(pred)) micro_rec = (len((truth & pred)) / len(truth)) micro_f1 = _f1(micro_prec, mic...
class RandomNegativeSkipGram(RandomNegativeCBOW): def __call__(self, batch) -> LongTensor: (x, y) = batch['context_words'].shape negatives = torch.multinomial(self.sampling_distn, num_samples=((self.number_of_samples * x) * y), replacement=True).resize(x, y, self.number_of_samples) batch['co...
.parametrize('data_key, hydrate', [('wbm_summary', True), ('wbm_initial_structures', True), ('wbm_computed_structure_entries', False), ('mp_elemental_ref_entries', True), ('mp_energies', True)]) def test_load(data_key: str, hydrate: bool, dummy_df_serialized: pd.DataFrame, capsys: CaptureFixture[str], tmp_path: Path) -...
class Normal(nn.Module): def __init__(self, mu=0, sigma=1): super(Normal, self).__init__() self.normalization = Variable(torch.Tensor([np.log((2 * np.pi))])) self.mu = Variable(torch.Tensor([mu])) self.logsigma = Variable(torch.Tensor([math.log(sigma)])) def _check_inputs(self, s...
def begin(cfg): if cfg.other.is_debug: set_debug(cfg) pl.seed_everything(cfg.seed) cfg.paths.work = str(Path.cwd()) cfg.other.git_hash = GIT_HASH logger.info(f'Workdir : {cfg.paths.work}.') if (cfg.data_pred.name == 'data_feat'): with omegaconf.open_dict(cfg): cfg.dat...
class DiceLoss(nn.Module): def __init__(self): super(DiceLoss, self).__init__() self.smooth = 1 def forward(self, input, target): axes = tuple(range(1, input.dim())) intersect = (input * target).sum(dim=axes) union = (torch.pow(input, 2).sum(dim=axes) + torch.pow(target, ...
def add_located(raw_data_dicts, srt_data, frame_cnt): data_dicts = copy.deepcopy(raw_data_dicts) nan_cnt = 0 for i in tqdm(range(len(data_dicts))): vid_name = data_dicts[i]['vid_name'] sub_text_list = srt_data['sub_text'][vid_name] sub_time = srt_data['sub_time'][vid_name] (t...
class TableModel(QtCore.QAbstractTableModel): def __init__(self, data): super(TableModel, self).__init__() self._data = data def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole): if (role != QtCore.Qt.DisplayRole): return QtCore.QVariant() if (orient...
def generate_my_simplicial_complex_d2(N, p1, p2): G = nx.fast_gnp_random_graph(N, p1, seed=None) if (not nx.is_connected(G)): giant = list(nx.connected_components(G))[0] G = nx.subgraph(G, giant) print(('not connected, but GC has order %i ans size %i' % (len(giant), G.size()))) trian...
class AsyncNoOverlapAlternatingActionServer(NoOverlapAlternatingActionServer): def serve_actions_evaluation(self, itr): obs_ready = self.sync.obs_ready obs_ready_pair = self.obs_ready_pair act_ready_pair = self.act_ready_pair (step_np, step_np_pair) = (self.eval_step_buffer_np, self....
(name='test_team_batting_html') def _test_team_batting_html(get_data_file_contents: Callable[([str], str)]) -> str: return get_data_file_contents('team_batting.html')
def test_interpolation_potential_density_notinterpolated(): rzpot = potential.interpRZPotential(RZPot=potential.MWPotential, rgrid=(0.01, 2.0, 101), zgrid=(0.0, 0.2, 101), logR=False, interpDens=False, zsym=True) rs = [0.5, 1.5] zs = [0.075, 0.15] for r in rs: for z in zs: assert (nu...
class SequentialSchedule(Scheduler): def __init__(self, iteration_per_epoch: int) -> None: from bigdl.dllib.optim.optimizer import SequentialSchedule as BSequentialSchedule self.scheduler = BSequentialSchedule(iteration_per_epoch) def get_scheduler(self) -> 'optimizer.SequentialSchedule': ...
class AutoObject(NestedSpace): def __call__(self, *args, **kwargs): if (not self._inited): self._inited = True self._instance = self.init() return self._instance.__call__(*args, **kwargs) def init(self): config = self.cs.get_default_configuration().get_dictionary(...
class VanConfig(PretrainedConfig): model_type = 'van' def __init__(self, image_size=224, num_channels=3, patch_sizes=[7, 3, 3, 3], strides=[4, 2, 2, 2], hidden_sizes=[64, 128, 320, 512], depths=[3, 3, 12, 3], mlp_ratios=[8, 8, 4, 4], hidden_act='gelu', initializer_range=0.02, layer_norm_eps=1e-06, layer_scale_i...
def compute_loss(model, device, data_loader): model.eval() loss = 0 scores = {} with torch.no_grad(): for (id_list, X1, X2, target) in data_loader: (X1, X2, target) = (X1.to(device), X2.to(device), target.to(device)) target = target.view((- 1), 1).float() y = ...
class AdamP(Optimizer): def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, delta=0.1, wd_ratio=0.1, nesterov=False): defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, delta=delta, wd_ratio=wd_ratio, nesterov=nesterov) super(AdamP, self).__init__...
def rlaus_resnet50(rla_channel=32): print('Constructing rlaus_resnet50......') model = RLAus_ResNet(RLAus_Bottleneck, [3, 4, 6, 3]) return model
def ffprob_shot_segmentation(video_path='data', video_name='Cosmus_Laundromat.mp4'): shot_seg_text_file = os.path.join(video_path, 'shot_segmentation.txt') if (not os.path.isfile(shot_seg_text_file)): print('Ffmpeg shot segmentation in action...') video_path_in_linux_style = '/'.join(video_path....
def add_params(parser): parser.add_argument('--job_name', help='ElasticJob name', required=True) parser.add_argument('--namespace', default='default', type=str, help='The name of the Kubernetes namespace where ElasticJob pods will be created') parser.add_argument('--platform', default='pyk8s', type=str, hel...
class WordNgram(): def __init__(self, lang, device): self.lang = Path(lang) self.device = device self.is_cuda = (device.type == 'cuda') self.symbol_table = k2.SymbolTable.from_file((self.lang / 'words.txt')) self.oovid = int(open((self.lang / 'oov.int')).read().strip()) ...
def simxSetArrayParameter(clientID, paramIdentifier, paramValues, operationMode): c_paramValues = (ct.c_float * 3)(*paramValues) return c_SetArrayParameter(clientID, paramIdentifier, c_paramValues, operationMode)
class SubMobileSPADEGenerator(BaseNetwork): def modify_commandline_options(parser, is_train): return parser def __init__(self, opt, config): super(SubMobileSPADEGenerator, self).__init__() self.opt = opt self.config = config nf = opt.ngf (self.sw, self.sh) = self....
_criterion('masked_lm') class MaskedLmLoss(FairseqCriterion): def forward(self, model, sample, reduce=True): masked_tokens = sample['target'].ne(self.padding_idx) sample_size = masked_tokens.int().sum().item() if (sample_size == 0): masked_tokens = None logits = model(**s...
def extract_comments(node, code, comments, lang): if (len(node.children) == 0): if (node.type in comment_node_name[lang]): comment_dict = {'content': code[node.start_byte:node.end_byte].decode('UTF-8'), 'range': list(range((node.start_point[0] + 1), (node.end_point[0] + 2))), 'start_byte': node....
def training_params(is_gcloud=False, output_dir=None): if (not output_dir): output_dir = util.construct_experiment_output_dir(__file__) num_gpus = 1 stop_after = 7 dynamic_batch_size = {2: 128, 3: 128, 4: 64, 5: 32, 6: 16, 7: 6, 8: 3} imgs_per_phase = 384000 dynamic_steps_per_phase = {ph...
def get_inceptionresnetv2(model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs): net = InceptionResNetV2(**kwargs) if pretrained: if ((model_name is None) or (not model_name)): raise ValueError('Parameter `model_name` should be properly initialized for load...
class Completion(TypedDict): id: str object: Literal['text_completion'] created: int model: str choices: List[CompletionChoice] usage: CompletionUsage
def discount_path(path, h): curr = 0 rets = [] for i in range(len(path)): curr = ((curr * h) + path[((- 1) - i)]) rets.append(curr) rets = ch.stack(list(reversed(rets)), 0) return rets
class Seq2SeqMoEModelOutput(ModelOutput): last_hidden_state: torch.FloatTensor = None past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None decoder_router_logits...
_model('fconv_lm') class FConvLanguageModel(FairseqLanguageModel): def __init__(self, decoder): super().__init__(decoder) def add_args(parser): parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--decoder-embed-dim', type=int, metav...
def test1(): station1 = Node('Westminster') station2 = Node('Waterloo', None, [station1]) station3 = Node('Trafalgar Square', None, [station1, station2]) station4 = Node('Canary Wharf', None, [station2, station3]) station5 = Node('London Bridge', None, [station4, station3]) station6 = Node('Tott...
def _check_file_path(path: Union[(str, Path)], model_dir: Path) -> Path: if (path is None): return None p = (Path(path) if isinstance(path, str) else path) if (not p.is_file()): p = (model_dir / p.name) assert p.is_file(), p return p
def mod2pi(x): v = np.mod(x, np.copysign((2.0 * math.pi), x)) if (v < (- math.pi)): v += (2.0 * math.pi) elif (v > math.pi): v -= (2.0 * math.pi) return v
def test_points_in_boxes_gpu(): if (not torch.cuda.is_available()): pytest.skip('test requires GPU and torch+cuda') boxes = torch.tensor([[[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.3]], [[(- 10.0), 23.0, 16.0, 10, 20, 20, 0.5]]], dtype=torch.float32).cuda() pts = torch.tensor([[[1, 2, 3.3], [1.2, 2.5, 3.0], ...
class TFNextSentencePredictorOutput(ModelOutput): logits: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None
def weights_init_classifier(m): classname = m.__class__.__name__ if (classname.find('Linear') != (- 1)): init.normal_(m.weight.data, std=0.001) init.constant_(m.bias.data, 0.0)
class FangraphsMonth(EnumBase): ALL = 0 MARCH_APRIL = 4 MARCH = MARCH_APRIL APRIL = MARCH_APRIL MAY = 5 JUNE = 6 JULY = 7 AUGUST = 8 SEPTEMBER_OCTOBER = 9 SEPTEMBER = SEPTEMBER_OCTOBER OCTOBER = SEPTEMBER_OCTOBER
class RecurrentCrossAttentionLayer(Module): def __init__(self, attention, d_model, n_heads, d_keys=None, d_values=None, d_model_keys=None, event_dispatcher=''): super(RecurrentCrossAttentionLayer, self).__init__() d_keys = (d_keys or (d_model // n_heads)) d_values = (d_values or (d_model // ...
def check_model_list(): models_dir = os.path.join(PATH_TO_DIFFUSERS, 'models') _models = [] for model in os.listdir(models_dir): model_dir = os.path.join(models_dir, model) if (os.path.isdir(model_dir) and ('__init__.py' in os.listdir(model_dir))): _models.append(model) model...
def download_file_from_google_drive(id, destination): URL = ' session = requests.Session() response = session.get(URL, params={'id': id}, stream=True) token = get_confirm_token(response) if token: params = {'id': id, 'confirm': token} response = session.get(URL, params=params, stream...
class _MockDistribution(): def __init__(self, action): self._action = action def rsample_with_pre_tanh_value(self, **kwargs): del kwargs return (self._action, self._action) def rsample(self, **kwargs): del kwargs return (self._action, self._action) def log_prob(se...
class MultiPatternInferenceEPL(): def __init__(self, numCores, numExcNeuronsPerCore, numInhNeuronsPerCore, inputBiases=None, gcInputBias=None, conn_prob=0.2, delayMCToGC=16, numMCToGCDelays=4, doOnlyInference=True, debug=False, log=True): self.net = nx.NxNet() self.numCores = numCores self.n...
def seresnet1001_svhn(num_classes=10, **kwargs): return get_seresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True, model_name='seresnet1001_svhn', **kwargs)
def horizon(params: dict, detector: Union[(Detector, Network)], target_SNR: int=9, waveform_model: str=WAVEFORM_MODEL, cosmology_model: cosmology.Cosmology=Planck18): if (('redshift' in params) or ('luminosity_distance' in params)): warnings.warn('The redshift and distance parameters will not be used in thi...
class KandinskyV22CombinedPipeline(DiffusionPipeline): model_cpu_offload_seq = 'prior_text_encoder->prior_image_encoder->unet->movq' _load_connected_pipes = True def __init__(self, unet: UNet2DConditionModel, scheduler: DDPMScheduler, movq: VQModel, prior_prior: PriorTransformer, prior_image_encoder: CLIPVi...
class ArithmeticSharedTensor(object): def __init__(self, tensor=None, size=None, precision=None, src=0, device=None): self.rep_share = None if (src == SENTINEL): return assert (isinstance(src, int) and (src >= 0) and (src < comm.get().get_world_size())), 'invalid tensor source' ...
def get_offset(beta2, rho_inf): if (not (beta2 > 0.6)): raise ValueError('beta2 ({}) must be greater than 0.6'.format(beta2)) offset = 1 while True: if (rho_fn(offset, beta2, rho_inf) > 4): return offset offset += 1
def load_testing(root_path, dir, batch_size, kwargs): transform = transforms.Compose([transforms.Resize([224, 224]), transforms.ToTensor()]) data = datasets.ImageFolder(root=os.path.join(root_path, dir), transform=transform) test_loader = torch.utils.data.DataLoader(data, batch_size=batch_size, shuffle=True...
class FlattenParameter(message.Message): __metaclass__ = reflection.GeneratedProtocolMessageType DESCRIPTOR = _FLATTENPARAMETER
def _gen_mixnet_s(variant, channel_multiplier=1.0, pretrained=False, **kwargs): arch_def = [['ds_r1_k3_s1_e1_c16'], ['ir_r1_k3_a1.1_p1.1_s2_e6_c24', 'ir_r1_k3_a1.1_p1.1_s1_e3_c24'], ['ir_r1_k3.5.7_s2_e6_c40_se0.5_nsw', 'ir_r3_k3.5_a1.1_p1.1_s1_e6_c40_se0.5_nsw'], ['ir_r1_k3.5.7_p1.1_s2_e6_c80_se0.25_nsw', 'ir_r2_k3...
def load_data(loc): df = pd.read_csv(loc, engine='python', encoding='utf-8') df.fillna('') df = np.asarray(df) return df
def conv3x3(in_planes: int, out_planes: int, stride: int=1, groups: int=1, dilation: int=1) -> HalutConv2d: return HalutConv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation, split_factor=4)
class RFPoseDecode(nn.Module): def __init__(self): super(RFPoseDecode, self).__init__() self.convt1 = nn.ConvTranspose3d(in_channels=64, out_channels=64, kernel_size=(3, 6, 6), stride=(1, 2, 2), padding=(1, 2, 2)) self.convt2 = nn.ConvTranspose3d(in_channels=64, out_channels=64, kernel_size=...
class SimulTransAgent(Agent): def __init__(self, args): self.load_model(args) self.build_word_splitter(args) self.max_len = args.max_len self.eos = DEFAULT_EOS def add_args(parser): parser.add_argument('--model-path', type=str, required=True, help='path to your pretrained...
def conv2d(x, y, **kwargs): return __replicated_secret_sharing_protocol('conv2d', x, y, **kwargs)
def to_bigdl_2d_padding(border_mode, *args): if (border_mode == 'same'): if (len(args) == 0): return ((- 1), (- 1)) elif (len(args) == 4): (h, kh, dh, dilation_h) = args pad_h = __calculate_2d_same_padding(h, kh, dh, dilation_h) return (pad_h, 0) ...
def test_tell_fails_when_ask_tell_mismatch_dqd(scheduler_fixture): (scheduler, *_) = scheduler_fixture _ = scheduler.ask_dqd() with pytest.raises(RuntimeError): scheduler.tell(None, None)
def parse_bookshelf_pl(pl, node_dict): with open(pl, 'r') as f: lines = [l for l in (line.strip() for line in f) if l] lines_iter = iter(lines[1:]) for l in lines_iter: if l.startswith('#'): continue tokens = l.split() assert (len(tokens) > 3) (name, x, y)...
def adjacency(graph, directed=False, reversed=False, stochastic=False, heuristic=None): if ((graph._adjacency is not None) and (graph._adjacency[1:] == (directed, reversed, stochastic, (heuristic and heuristic.__code__)))): return graph._adjacency[0] map = {} for n in graph.nodes: map[n.id] ...
def display_tree_mnist(embeddings, true_labels=None, transparency=None, legend_labels=None, numeric_labels=True, distinct=False): dotsize = 10 if (transparency is None): if (true_labels is None): transparency = 0.05 else: transparency = (300 / float(len(true_labels))) ...
class Generator(nn.Module): def __init__(self): super().__init__() self.layer1 = nn.Sequential(nn.Linear(in_features=100, out_features=256), nn.LeakyReLU()) self.layer2 = nn.Sequential(nn.Linear(in_features=256, out_features=512), nn.LeakyReLU()) self.layer3 = nn.Sequential(nn.Linear...
def _test(): import torch in_size = (480, 480) aux = False pretrained = False models = [(pspnet_resnetd50b_voc, 21), (pspnet_resnetd101b_voc, 21), (pspnet_resnetd50b_coco, 21), (pspnet_resnetd101b_coco, 21), (pspnet_resnetd50b_ade20k, 150), (pspnet_resnetd101b_ade20k, 150), (pspnet_resnetd50b_citysc...
def graph_keys_dict(): graph_keys_dict_raw = dict(tf.GraphKeys.__dict__) graph_keys_dict_raw['AUX_LOSS'] = 'aux_loss' graph_keys_dict_clean = dict() for (k, v) in graph_keys_dict_raw.items(): if (not (k.startswith('__') and k.endswith('__'))): if isinstance(v, str): g...
((not torch.cuda.is_available()), 'Skip cpu ut, only run on gpu.') ((torch_version() < (2, 0, 0)), 'AtorchTrainer need torch2.0 .') class AtorchTrainerTest(unittest.TestCase): def test_atorch_trainer(self): world_size = 4 os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = st...
def ProcessAppendDescriptor(segment, parent_node_name, affix, edge_attributes=None): dot_graph = [] names = [] desc_name = 'Append_{0}'.format(affix) for i in range(len(segment['sub_segments'])): sub_segment = segment['sub_segments'][i] part_name = '{0}{1}{2}'.format(desc_name, sub_segme...
class TFLibrary(Library): def __init__(self, output_dir, diff_bound=1e-05, time_bound=10, time_thresold=0.001) -> None: super().__init__(output_dir) self.diff_bound = diff_bound self.time_bound = time_bound self.time_thresold = time_thresold def test_with_oracle(self, api: TFAPI,...
class TestCommunication(unittest.TestCase): def setUp(self) -> None: self.queue = MessageQueue() def test_request(self) -> None: method = 'GET' operation = '/api/a/b/x' data = self._get_random_dict() request = Request(method, operation, data) self.assertEqual(meth...
class SLSTM(SpikingNeuron): def __init__(self, input_size, hidden_size, bias=True, threshold=1.0, spike_grad=None, surrogate_disable=False, init_hidden=False, inhibition=False, learn_threshold=False, reset_mechanism='none', state_quant=False, output=False): super().__init__(threshold, spike_grad, surrogate_...
def _make_beit_backbone(model, features=[96, 192, 384, 768], size=[384, 384], hooks=[0, 4, 8, 11], vit_features=768, use_readout='ignore', start_index=1, start_index_readout=1): backbone = make_backbone_default(model, features, size, hooks, vit_features, use_readout, start_index, start_index_readout) backbone.m...
def _check_and_coerce_cfg_value_type(replacement, original, key, full_key): original_type = type(original) replacement_type = type(replacement) if (replacement_type == original_type): return replacement def conditional_cast(from_type, to_type): if ((replacement_type == from_type) and (or...
def tabulate(rows: List[List[Union[(str, int)]]], headers: List[str]) -> str: col_widths = [max((len(str(x)) for x in col)) for col in zip(*rows, headers)] row_format = ('{{:{}}} ' * len(headers)).format(*col_widths) lines = [] lines.append(row_format.format(*headers)) lines.append(row_format.format...
def adjacency_matrix(senders, receivers, dim): one_hot_senders = tf.one_hot(senders, dim) one_hot_receivers = tf.one_hot(receivers, dim) adj_mat = tf.einsum('ki,kj->ij', one_hot_senders, one_hot_receivers) return adj_mat
def plot_anomalies_value(y_true, y_pred, pattern_ano_index, trend_ano_index): df = pd.DataFrame({'y_true': y_true.squeeze(), 'y_pred': y_pred.squeeze()}) df['p_ano_index'] = 0 df.loc[(df.index[pattern_ano_index], 'ano_index')] = 1 df['t_ano_index'] = 0 df.loc[(df.index[trend_ano_index], 'ano_index')...
_legacy_interface(weights=('pretrained', EfficientNet_B4_Weights.IMAGENET1K_V1)) def efficientnet_b4(*, weights: Optional[EfficientNet_B4_Weights]=None, progress: bool=True, **kwargs: Any) -> EfficientNet: weights = EfficientNet_B4_Weights.verify(weights) (inverted_residual_setting, last_channel) = _efficientne...
def build_model(cfg): model = build_detector(cfg.model, test_cfg=cfg.get('test_cfg')) model = revert_sync_batchnorm(model) model = MMDataParallel(model) return model
def read_metadata(path): ids = [] with open(path) as f: for (i, line) in enumerate(f): groups = line.strip().split() ids.append(' '.join(groups[:4])) return ids
class KarrasDiffusionSchedulers(Enum): DDIMScheduler = 1 DDPMScheduler = 2 PNDMScheduler = 3 LMSDiscreteScheduler = 4 EulerDiscreteScheduler = 5 HeunDiscreteScheduler = 6 EulerAncestralDiscreteScheduler = 7 DPMSolverMultistepScheduler = 8 DPMSolverSinglestepScheduler = 9 KDPM2Dis...
def get_batch_size(inputs): if isinstance(inputs, (list, tuple)): return get_batch_size(inputs[0]) return inputs.size()[0]
class Attn_Net(nn.Module): def __init__(self, L=1024, D=256, dropout=False, n_classes=1): super().__init__() self.module = [nn.Linear(L, D), nn.Tanh()] if dropout: self.module.append(nn.Dropout(0.25)) self.module.append(nn.Linear(D, n_classes)) self.module = nn.Se...