code stringlengths 101 5.91M |
|---|
def vgg16(conv_layer, linear_layer, init_type, **kwargs):
n = [i for i in cfgs['16'] if isinstance(i, int)][(- 1)]
model = VGG(make_layers(cfgs['16'], conv_layer, batch_norm=False), n, linear_layer, **kwargs)
initialize_weights(model, init_type)
return model |
class Deconv3DBlock(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size=3):
super().__init__()
self.block = nn.Sequential(SingleDeconv3DBlock(in_planes, out_planes), SingleConv3DBlock(out_planes, out_planes, kernel_size), nn.BatchNorm3d(out_planes), nn.ReLU(True))
def forward(self,... |
class SupportVectorComponentTest(BaseRegressionComponentTest):
__test__ = True
res = dict()
res['default_boston'] = (- 0.)
res['default_boston_iterative'] = None
res['default_boston_sparse'] = (- 0.)
res['default_boston_iterative_sparse'] = None
res['default_diabetes'] = 0.
res['default_... |
def global_version_update(version, patch=False):
for (pattern, fname) in REPLACE_FILES.items():
update_version_in_file(fname, version, pattern)
if (not patch):
update_version_in_examples(version) |
def random_truncated_masking(x, rand_func=None):
if (rand_func is None):
def tf_uniform_random(num):
return tf.random_uniform([num], minval=0.0, maxval=1.0)
rand_func = tf_uniform_random
input_shape = get_shape(x)
batch_size = input_shape[0]
input_channels = input_shape[(- 1)... |
def setup(args):
cfg = get_cfg()
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.freeze()
default_setup(cfg, args)
return cfg |
class MADMCRScheduler(Scheduler):
def __init__(self):
super().__init__()
self.utilHistory = []
self.utilHistoryContainer = []
def updateUtilHistoryContainer(self):
containerUtil = [(cid.getBaseIPS() if cid else 0) for cid in self.env.containerlist]
self.utilHistoryContain... |
def main():
parser = argparse.ArgumentParser(description='AutoLRS server.')
parser.add_argument('--min_lr', help='minimum LR', required=True)
parser.add_argument('--max_lr', help='maximum LR', required=True)
parser.add_argument('--host', help='host', default='localhost', type=str)
parser.add_argumen... |
class AMR():
def __init__(self, id=None, sentence=None, graph=None, tokens=None, lemmas=None, pos_tags=None, ner_tags=None, abstract_map=None, misc=None):
self.id = id
self.sentence = sentence
self.graph = graph
self.tokens = tokens
self.lemmas = lemmas
self.pos_tags ... |
def test_sequence_length():
class BadLen(RuntimeError):
pass
class SequenceLike():
def __getitem__(self, i):
return None
def __len__(self):
raise BadLen()
with pytest.raises(BadLen):
m.sequence_length(SequenceLike())
assert (m.sequence_length([1, 2... |
def ncf_model(user_num, item_num, factor_num, dropout, lr, num_layers, sparse_feats_input_dims, sparse_feats_embed_dims, num_dense_feats):
user = tf.keras.layers.Input(dtype=tf.int32, shape=())
item = tf.keras.layers.Input(dtype=tf.int32, shape=())
if (not isinstance(sparse_feats_embed_dims, list)):
... |
_metric
def kid50k(opts):
opts.dataset_kwargs.update(max_size=None)
kid = kernel_inception_distance.compute_kid(opts, max_real=50000, num_gen=50000, num_subsets=100, max_subset_size=1000)
return dict(kid50k=kid) |
class FlaxMBartModel(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
class Encoder(nn.Module):
def __init__(self, c_in=513, c_h1=128, c_h2=512, c_h3=128, ns=0.2, dp=0.5):
super(Encoder, self).__init__()
self.ns = ns
self.conv1s = nn.ModuleList([nn.Conv1d(c_in, c_h1, kernel_size=k) for k in range(1, 8)])
self.conv2 = nn.Conv1d(((len(self.conv1s) * c_h1... |
def infer_init_method(args):
if (args.distributed_init_method is not None):
return
if all(((key in os.environ) for key in ['MASTER_ADDR', 'MASTER_PORT', 'WORLD_SIZE', 'RANK'])):
args.distributed_init_method = 'env://'
args.distributed_world_size = int(os.environ['WORLD_SIZE'])
ar... |
def coding_humaneval_match_answer(task_data, response):
def _function_exists(code, func_name):
tree = ast.parse(code)
for node in ast.walk(tree):
if (isinstance(node, ast.FunctionDef) and (node.name == func_name)):
return True
return False
def _try_match(conte... |
class BlipImageBaseProcessor(BaseProcessor):
def __init__(self, mean=None, std=None):
if (mean is None):
mean = (0., 0.4578275, 0.)
if (std is None):
std = (0., 0., 0.)
self.normalize = transforms.Normalize(mean, std) |
def show_npimage(mtg, title=''):
if (mtg.dtype is not np.uint8):
if (np.max(mtg) < 1.2):
Image.fromarray((255 * np.clip(mtg, 0, 1)).astype(np.uint8)).show(title)
else:
Image.fromarray(np.clip(mtg, 0, 255).astype(np.uint8)).show(title)
else:
Image.fromarray(mtg).sh... |
def rgbd_loop_closure(depth_list, color_list, intrinsic, config):
device = o3c.Device('CUDA:0')
interval = config.odometry_loop_interval
n_files = len(depth_list)
key_indices = list(range(0, n_files, interval))
n_key_indices = len(key_indices)
edges = []
poses = []
infos = []
pairs =... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--tsv-file', required=True, nargs='+', type=str)
parser.add_argument('--spm-prefix', required=True, type=str)
parser.add_argument('--vocab-size', required=True, type=int)
parser.add_argument('--vocab-type', default='unigram', ... |
def check_args(args):
if (not os.path.exists(args.config_dir)):
os.makedirs(args.config_dir)
return args |
def PSPNet(backbone_name='vgg16', input_shape=(32, 32, 32, 3), classes=21, activation='softmax', weights=None, encoder_weights='imagenet', encoder_freeze=False, downsample_factor=8, psp_conv_filters=512, psp_pooling_type='avg', psp_use_batchnorm=True, psp_dropout=None, **kwargs):
global backend, layers, models, ker... |
class LegacyFairseqOptimizer(FairseqOptimizer):
def __init__(self, args):
self.args = args |
class OSBlock(nn.Module):
def __init__(self, in_channels, out_channels, IN=False, bottleneck_reduction=4, **kwargs):
super(OSBlock, self).__init__()
mid_channels = (out_channels // bottleneck_reduction)
self.conv1 = Conv1x1(in_channels, mid_channels)
self.conv2a = LightConv3x3(mid_ch... |
('paired-image-transform-folders')
class PairedImageTransformFolders(Dataset):
def __init__(self, root_path_1, root_path_2, **kwargs):
self.dataset_1 = ImageTransformFolder(root_path_1, **kwargs)
self.dataset_2 = ImageFolder(root_path_2, **kwargs)
def __len__(self):
return len(self.datas... |
class NormalizedHyperVolume(QualityIndicator):
def __init__(self, reference_point: Iterable[float], reference_front: np.array):
self.reference_point = reference_point
self._hv = HyperVolume(reference_point=reference_point)
self._reference_hypervolume = self._hv.compute(reference_front)
... |
class IndexType(LaVarType):
def __init__(self, desc=None, symbol=None):
LaVarType.__init__(self, VarTypeEnum.INDEX, desc, symbol) |
def _add_basic_block(x_in, out_channels, strides, dropout_rate=0.0):
is_channels_equal = (K.int_shape(x_in)[_get_channels_axis()] == out_channels)
bn1 = batch_norm()(x_in)
bn1 = Activation('relu')(bn1)
out = conv2d(out_channels, 3, strides)(bn1)
out = batch_norm()(out)
out = Activation('relu')(o... |
def findNextOnset(i):
for j in range(len(trialOnsetTimes[(i + 1):])):
if (not np.isnan(trialOnsetTimes[((j + i) + 1)])):
return trialOnsetTimes[((j + i) + 1)] |
class RegNetStage(nn.Module):
def __init__(self, config: RegNetConfig, in_channels: int, out_channels: int, stride: int=2, depth: int=2):
super().__init__()
layer = (RegNetXLayer if (config.layer_type == 'x') else RegNetYLayer)
self.layers = nn.Sequential(layer(config, in_channels, out_chann... |
class BPEVocabDict(VocabDictBase):
def __init__(self, name, file_name):
VocabDictBase.__init__(self, name, file_name)
self.bpe_model = None
def load(self):
self.bpe_model = yttm.BPE(model=self.file_name)
def convert_sent_to_ids(self, sent, eos=False):
enc_seqs = self.bpe_mode... |
def get_norm_layer(norm_type='instance'):
if (norm_type == 'batch'):
norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True)
elif (norm_type == 'instance'):
norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False)
elif (norm_typ... |
_module()
class NASFPN(BaseModule):
def __init__(self, in_channels, out_channels, num_outs, stack_times, start_level=0, end_level=(- 1), add_extra_convs=False, norm_cfg=None, init_cfg=dict(type='Caffe2Xavier', layer='Conv2d')):
super(NASFPN, self).__init__(init_cfg)
assert isinstance(in_channels, li... |
def script_submodules_(model: nn.Module, types: Optional[Sequence[type]]=None, attempt_trace: Optional[bool]=True, batch_dims: Optional[Tuple[int]]=None):
to_trace = set()
_script_submodules_helper_(model, types, attempt_trace, to_trace)
if (attempt_trace and (len(to_trace) > 0)):
_trace_submodules_... |
def save_bn_running(net):
means = [l.running_mean.clone() for l in get_model(net).modules() if (type(l) == torch.nn.modules.batchnorm.BatchNorm2d)]
variances = [l.running_var.clone() for l in get_model(net).modules() if (type(l) == torch.nn.modules.batchnorm.BatchNorm2d)]
return [means, variances] |
def running_config_to_str(running_config):
str_ = ''
for (running_config_key, running_config_value) in running_config.items():
str_ += ',{}={}'.format(simplify_config_key(str(running_config_key)), running_config_value)
return str_ |
def initialize_quaddobl_tracker(target, start, fixedgamma=True, regamma=0.0, imgamma=0.0):
from phcpy.phcpy2c3 import py2c_copy_quaddobl_container_to_target_system
from phcpy.phcpy2c3 import py2c_copy_quaddobl_container_to_start_system
from phcpy.phcpy2c3 import py2c_initialize_quaddobl_homotopy
from ph... |
_module()
class RFP(FPN):
def __init__(self, rfp_steps, rfp_backbone, aspp_out_channels, aspp_dilations=(1, 3, 6, 1), **kwargs):
super().__init__(**kwargs)
self.rfp_steps = rfp_steps
self.rfp_modules = nn.ModuleList()
for rfp_idx in range(1, rfp_steps):
rfp_module = build... |
def eval_epoch(args, model, test_dataloader, device, n_gpu):
top1 = AverageMeter()
top5 = AverageMeter()
if hasattr(model, 'module'):
model = model.module.to(device)
else:
model = model.to(device)
model.eval()
with torch.no_grad():
for (bid, batch) in enumerate(test_datal... |
def compute_mean(values):
if torch.is_tensor(values):
return values.float().mean()
if isinstance(values, (tuple, list)):
return torch.stack([torch.as_tensor(x).detach() for x in values]).float().mean()
raise ValueError() |
def calculate_fid_given_paths(paths, device=None, batch_size=50, dims=2048, num_workers=8):
if (device is None):
device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
else:
device = torch.device(device)
for p in paths:
if (not os.path.exists(p)):
raise R... |
def main(args: Any=None) -> None:
if (args is None):
args = sys.argv[1:]
parser = create_parser()
args = parser.parse_args(args)
description = ('entropy-estimation' if args.entropy_estimation else args.entropy_coder)
filepaths = collect_images(args.data_name, args.dataset, args.num_camera)
... |
class Dataloader():
def __init__(self, args):
self.args = args
self.loader_input = args.loader_input
self.loader_label = args.loader_label
self.split_test = args.split_test
self.split_train = args.split_train
self.dataset_test_name = args.dataset_test
self.dat... |
def add_ego_car(start_velocity):
traci.vehicle.add('ego', 'rampRoute', 'egoCar', departSpeed=start_velocity, departPos=40, arrivalPos=50)
traci.vehicle.setSpeedMode('ego', 22)
traci.vehicle.setSpeed('ego', start_velocity) |
def demo():
genome = [[[0], [1, 0], [0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0, 1], [0]], [[0], [0, 0], [0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0, 0], [1]], [[0], [0, 1], [1, 1, 0], [0, 0, 1, 1], [1, 0, 0, 1, 0], [0]]]
d = make_dot_genome(genome, title='Demo Genome', filename='test')
d.view() |
class Counter(WriteMixin, Infinite):
message = ''
hide_cursor = True
def update(self):
self.write(str(self.index)) |
def extract_features(waveforms, components_list, statistics_list=None, num_proc=1):
extractor_helper = partial(extract_features_from_waveform, components_list, statistics_list)
with Pool(num_proc) as pool:
output_feats_iter = tqdm(pool.imap(extractor_helper, waveforms), total=len(waveforms), desc='Extra... |
def parse_data_train(image, label):
image = tf.io.decode_jpeg(image, NUM_CHANNELS)
image = tf.image.resize(image, size=(WIDTH, HEIGHT))
image = tf.reshape(image, [WIDTH, HEIGHT, NUM_CHANNELS])
return (image, label) |
class DistilBertTokenizer(BertTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
model_input_names = ['attention_mask'] |
def weighted_loss(loss_func: Callable) -> Callable:
(loss_func)
def wrapper(pred: Tensor, target: Tensor, weight: Optional[Tensor]=None, reduction: str='mean', avg_factor: Optional[int]=None, **kwargs) -> Tensor:
loss = loss_func(pred, target, **kwargs)
loss = weight_reduce_loss(loss, weight, re... |
class nnUNetTrainerV2_reduceMomentumDuringTraining(nnUNetTrainerV2):
def initialize_optimizer_and_scheduler(self):
current_momentum = 0.99
min_momentum = 0.9
if (self.epoch > 800):
current_momentum = (current_momentum - (((current_momentum - min_momentum) / 200) * (self.epoch - 8... |
def step_5b(w):
if (w.endswith('ll') and R2(w).endswith('l')):
return w[:(- 1)]
return w |
def read_standard_system_and_solutions(filename):
from phcpy.phcpy2c3 import py2c_syscon_clear_symbol_table
from phcpy.phcpy2c3 import py2c_read_standard_start_system_from_file
from phcpy.phcpy2c3 import py2c_copy_start_system_to_container
from phcpy.phcpy2c3 import py2c_copy_start_solutions_to_containe... |
def main():
args = parse_args()
if (len(args.shape) == 1):
input_shape = (3, args.shape[0], args.shape[0])
elif (len(args.shape) == 2):
input_shape = ((3,) + tuple(args.shape))
else:
raise ValueError('invalid input shape')
cfg = Config.fromfile(args.config)
if (args.cfg_o... |
class DensePoseConfidenceModelConfig():
uv_confidence: DensePoseUVConfidenceConfig
segm_confidence: DensePoseSegmConfidenceConfig
def from_cfg(cfg: CfgNode) -> 'DensePoseConfidenceModelConfig':
return DensePoseConfidenceModelConfig(uv_confidence=DensePoseUVConfidenceConfig(enabled=cfg.MODEL.ROI_DENS... |
class GaussianKernel(Kernel):
def __init__(self) -> None:
super(GaussianKernel, self).__init__()
def similarity(self, distances: torch.Tensor, bandwidth: Union[(float, torch.Tensor)]) -> torch.Tensor:
return ((- distances) / bandwidth) |
class Resnet(nn.Module):
def __init__(self, orig_resnet):
super(Resnet, self).__init__()
self.conv1 = orig_resnet.conv1
self.bn1 = orig_resnet.bn1
self.relu1 = orig_resnet.relu1
self.conv2 = orig_resnet.conv2
self.bn2 = orig_resnet.bn2
self.relu2 = orig_resnet... |
class ProxylessBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, bn_eps, expansion):
super(ProxylessBlock, self).__init__()
self.use_bc = (expansion > 1)
mid_channels = (in_channels * expansion)
if self.use_bc:
self.bc_conv = conv1x1_blo... |
class Trainer(object):
def __init__(self, cuda, model_rgb, model_depth, model_clstm, optimizer_rgb, optimizer_depth, optimizer_clstm, train_loader, max_iter, snapshot, outpath, sshow, size_average=False):
self.cuda = cuda
self.model_rgb = model_rgb
self.model_depth = model_depth
self... |
def _gen_mnasnet_small(variant, channel_multiplier=1.0, pretrained=False, **kwargs):
arch_def = [['ds_r1_k3_s1_c8'], ['ir_r1_k3_s2_e3_c16'], ['ir_r2_k3_s2_e6_c16'], ['ir_r4_k5_s2_e6_c32_se0.25'], ['ir_r3_k3_s1_e6_c32_se0.25'], ['ir_r3_k5_s2_e6_c88_se0.25'], ['ir_r1_k3_s1_e6_c144']]
model_kwargs = dict(block_arg... |
def cal_normalized_tp_pos_fp_neg(output, target, nclass, score_thresh):
mini = 1
maxi = 1
nbins = 1
predict = (nd.sigmoid(output).asnumpy() > score_thresh).astype('int64')
if (len(target.shape) == 3):
target = nd.expand_dims(target, axis=1).asnumpy().astype('int64')
elif (len(target.shap... |
def Sequence_logo_multiple(matrix, data_type=None, figsize=None, ylabel=None, title=None, epsilon=0.0001, ncols=1, rows_per_weight=1, show=True, count_from=0, ticks_every=1, ticks_labels_size=14, title_size=20):
if (data_type is None):
if (matrix.min() >= 0):
data_type = 'mean'
else:
... |
def _get_predictor(args: argparse.Namespace) -> Predictor:
from stog.utils.archival import load_archive
archive = load_archive(args.archive_file, device=args.cuda_device, weights_file=args.weights_file)
return Predictor.from_archive(archive) |
class MinkLoc(torch.nn.Module):
def __init__(self, in_channels, feature_size, output_dim, planes, layers, num_top_down, conv0_kernel_size, block='BasicBlock', pooling_method='GeM'):
super().__init__()
self.in_channels = in_channels
self.feature_size = feature_size
self.output_dim = o... |
class Tester():
def __init__(self, opt, model, data, write_file, verbose=True, path='/home/jcxu/exp-ptb'):
self.opt = opt
self.model = model
self.test_bag = data
self.output_path = opt.output_path
self.n_batch = len(data)
self.word_dict = opt.word_dict
self.ve... |
def train_loop(train_model, eval_model, encoder_model, hparams):
qsar_process = []
with train_model.graph.as_default():
train_model.sess.run(train_model.model.iterator.initializer)
step = train_model.model.initilize(train_model.sess, overwrite_saves=hparams.overwrite_saves)
hparams_file_name... |
class Predict(object):
def add_subparser(self, name, parser):
subparser = parser.add_parser(name, help='Use a trained model to make predictions.')
subparser.add_argument('--fdata', default='data/test.conllx', help='path to dataset')
subparser.add_argument('--finit', default='data/test.conllx... |
class Net(nn.Module):
def __init__(self, scale):
super(Net, self).__init__()
multi_scale = True
group = 1
self.sub_mean = ops.MeanShift((0.4488, 0.4371, 0.404), sub=True)
self.add_mean = ops.MeanShift((0.4488, 0.4371, 0.404), sub=False)
self.entry = nn.Conv2d(3, 64, 3... |
def load_state(path, model, optimizer=None):
if os.path.isfile(path):
log("=> loading checkpoint '{}'".format(path))
checkpoint = torch.load(path, map_location={'cuda:0': 'cuda:{}'.format(torch.cuda.current_device())})
model.load_state_dict(checkpoint['state_dict'], strict=False)
if ... |
class ResBlock(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
super(ResBlock, self).__init__()
self.convs1 = nn.ModuleList([weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0], padding=get_padding(kernel_size, dilation[0]))), weight_norm(Co... |
def select_conv2d(in_chs, out_chs, kernel_size, **kwargs):
assert ('groups' not in kwargs)
if isinstance(kernel_size, list):
assert ('num_experts' not in kwargs)
m = MixedConv2d(in_chs, out_chs, kernel_size, **kwargs)
else:
depthwise = kwargs.pop('depthwise', False)
groups = ... |
def test_accellsrframe_vecfuncomegaz_2D():
lp = potential.LogarithmicHaloPotential(normalize=1.0)
omega = lp.omegac(1.0)
omegadot = 0.02
omega_func = [(lambda t: 0.0), (lambda t: 0.0), (lambda t: (lp.omegac(1.0) + (0.02 * t)))]
omegadot_func = [(lambda t: 0.0), (lambda t: 0.0), (lambda t: 0.02)]
... |
def dla_profile(lambda_, z_abs, nhi):
transmission = np.exp(((- compute_tau(lambda_, z_abs, nhi, LAMBDA_LYA, OSCILLATOR_STRENGTH_LYA, GAMMA_LYA)) - compute_tau(lambda_, z_abs, nhi, LAMBDA_LYB, OSCILLATOR_STRENGTH_LYB, GAMMA_LYB)))
return transmission |
def load_cifar10(data_dir, use_augmentation=False):
test_transform = transforms.Compose([transforms.ToTensor()])
if use_augmentation:
train_transform = transforms.Compose([transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(0.5), transforms.ToTensor()])
else:
train_transfor... |
class ImageModel(nn.Module):
def __init__(self, args):
super(ImageModel, self).__init__()
self.args = args
self.backbone = Network(pvtv2_pretrained=False, imgsize=self.args.trainsize)
def forward(self, frame):
seg = self.backbone(frame)
return seg |
def setup_localize_trainer(config, dataloader_object):
model_path = os.path.join(config.localization_model_path, 'model.pt')
print_msg(('FL Model Path: %s' % model_path), 'LocalizeTrainerSetup')
classify_evaluator = ClassificationEvaluator(config, config.output_dir)
dataloader_object.token_tokenizer = d... |
class RopchainJob(job_class):
def __init__(self):
super().__init__()
self.script_file = __file__
self.rop_tool = 'ropgadget'
def run_rop_tool(self):
rop_tool = ROPGadget(self.binary, self.input, self, self.ropchain, self.bad_chars)
rop_tool.run(self.timeout) |
def main(_):
summary_writer = SummaryWriter(os.path.join(FLAGS.save_dir, 'tb', str(FLAGS.seed)))
video_save_folder = (None if (not FLAGS.save_video) else os.path.join(FLAGS.save_dir, 'video', 'eval'))
(env, dataset) = make_env_and_dataset(FLAGS.env_name, FLAGS.seed, FLAGS.dataset_name, video_save_folder)
... |
_module()
class PointRend(TwoStageDetector):
def __init__(self, backbone, rpn_head, roi_head, train_cfg, test_cfg, neck=None, pretrained=None):
super(PointRend, self).__init__(backbone=backbone, neck=neck, rpn_head=rpn_head, roi_head=roi_head, train_cfg=train_cfg, test_cfg=test_cfg, pretrained=pretrained) |
class Crop(ImgLandmarksTransform):
def __init__(self, bbox_scale=1.2, bbox_square=True, det_format=True, border='constant', value=None):
self.bbox_scale = bbox_scale
self.bbox_square = bbox_square
self.det_format = det_format
if (border == 'repeat'):
self.border = cv2.BOR... |
def validation_step(model, batch, device):
(images, labels, clabels) = batch
(images, clabels) = (images.to(device), clabels.to(device))
out = model(images)
loss = F.cross_entropy(out, clabels)
acc = accuracy(out, clabels)
return {'Loss': loss.detach(), 'Acc': acc} |
class AsrDataset(FairseqDataset):
def __init__(self, aud_paths, aud_durations_ms, tgt, tgt_dict, ids, speakers, num_mel_bins=80, frame_length=25.0, frame_shift=10.0):
assert (frame_length > 0)
assert (frame_shift > 0)
assert all(((x > frame_length) for x in aud_durations_ms))
self.fr... |
def create_crossval_splits(args: Args):
data = get_data(args.data_path)
num_data = len(data)
if (args.split_type == 'random'):
all_indices = list(range(num_data))
fold_indices = split_indices(all_indices, args.num_folds, scaffold=False)
elif (args.split_type == 'scaffold'):
all_i... |
def get_at_indices(tensor, indices):
counter = tf.range(tf.shape(indices, out_type=indices.dtype)[0])
return tf.gather_nd(tensor, tf.stack((counter, indices), (- 1))) |
def decode_thermistors_message(bin_msg, print_decoded=False, print_debug_information=False):
if print_decoded:
print(' START DECODE THERMISTORS MESSAGE ')
assert (message_kind(bin_msg) == 'T')
assert (byte_to_char(bin_msg[(- 1)]) == 'E')
if print_debug_information:
print('received messag... |
def main():
server_executor = NeuralChatServerExecutor()
server_executor(config_file='./assisted_gen.yaml', log_file='./assisted_gen.log') |
def calculate_pixel_accuracy(out_value, mace_out_value, output_shape, output_data_format):
out_value = out_value.reshape(output_shape)
mace_out_value = mace_out_value.reshape(output_shape)
if ((len(output_shape) == 4) and (output_data_format == DataFormat.NCHW)):
out_value = out_value.transpose([0, ... |
class ScheduledOptim():
def __init__(self, optimizer, d_model, n_warmup_steps):
self._optimizer = optimizer
self.n_warmup_steps = n_warmup_steps
self.n_current_steps = 0
self.init_lr = np.power(d_model, (- 0.5))
def step_and_update_lr(self):
self._update_learning_rate()
... |
def is_cuda_and_apex_available():
is_using_cuda = (torch.cuda.is_available() and (torch_device == 'cuda'))
return (is_using_cuda and is_apex_available()) |
class NegativeGraph(object):
def __init__(self, dic):
self.historical_dic = dic
def __call__(self, graph, etype):
(utype, _, vtype) = etype
(src, _) = graph.edges(etype=etype)
dst = []
for i in tqdm(range(src.shape[0])):
s = int(src[i])
while True:... |
class DPMSolverSDEScheduler(metaclass=DummyObject):
_backends = ['torch', 'torchsde']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch', 'torchsde'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['torch', 'torchsde'])
def from_pretrained(cls, *args, *... |
class ConvLSTMCell(nn.Module):
def __init__(self, args, input_size, hidden_size, kernel_size, padding):
super(ConvLSTMCell, self).__init__()
self.use_gpu = args.use_gpu
self.input_size = input_size
self.hidden_size = hidden_size
self.Gates = nn.Conv2d((input_size + (2 * hidde... |
def launch(main_func, num_gpus_per_machine, num_machines=1, machine_rank=0, dist_url=None, args=()):
world_size = (num_machines * num_gpus_per_machine)
if (world_size > 1):
if (dist_url == 'auto'):
assert (num_machines == 1), 'dist_url=auto not supported in multi-machine jobs.'
p... |
def get_random_pos_on_map(free_space_indices, map_: OccupancyGrid, safe_dist: float, forbidden_zones: list=None):
def is_pos_valid(x_in_meters, y_in_meters):
for forbidden_zone in forbidden_zones:
if ((((x_in_meters - forbidden_zone[0]) ** 2) + ((y_in_meters - forbidden_zone[1]) ** 2)) < ((forbi... |
def clip_featurize_data(dataset, device, pretrained):
with torch.no_grad():
(Z, Y) = ([], [])
for (x, y) in tqdm.tqdm(DataLoader(dataset, batch_size=128, num_workers=16)):
Z += [pretrained.encode_image(x.to(device).half()).cpu().numpy()]
Y += [y.cpu().numpy()]
return (np.... |
def get_split(split_name, dataset_dir, file_pattern=None, reader=None):
if (split_name not in _SPLITS_TO_SIZES):
raise ValueError(('split name %s was not recognized.' % split_name))
if (not file_pattern):
file_pattern = _FILE_PATTERN
file_pattern = os.path.join(dataset_dir, (file_pattern % s... |
def load_hyperparameters_json(PATHS: dict, from_scratch: bool=False, config_name: str='default'):
if from_scratch:
doc_location = os.path.join(PATHS.get('hyperparams'), (config_name + '.json'))
else:
doc_location = os.path.join(PATHS.get('model'), 'hyperparameters.json')
if os.path.isfile(do... |
class AttentionLayer(nn.Module):
def __init__(self, image_dim, question_dim, **kwargs):
super(AttentionLayer, self).__init__()
combine_type = kwargs['modal_combine']['type']
combine_params = kwargs['modal_combine']['params']
modal_combine_layer = ModalCombineLayer(combine_type, image... |
def test_fps():
if (not torch.cuda.is_available()):
pytest.skip()
xyz = torch.tensor([[[(- 0.2748), 1.002, (- 1.1674)], [0.1015, 1.3952, (- 1.2681)], [(- 0.807), 2.4137, (- 0.5845)], [(- 1.0001), 2.1982, (- 0.5859)], [0.3841, 1.8983, (- 0.7431)]], [[(- 1.0696), 3.0758, (- 0.1899)], [(- 0.2559), 3.5521, ... |
def _create_shared_memory(name, create, size=0):
if (not create):
try:
return SharedMemory(name=name)
except FileNotFoundError:
return None
try:
shm = SharedMemory(name=name, create=create, size=size)
except FileExistsError:
shm = SharedMemory(name=nam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.