code stringlengths 101 5.91M |
|---|
def SARE_loss(q_vec, pos_vecs, neg_vecs):
num_pos = pos_vecs.get_shape()[1]
query_copies_p = tf.tile(q_vec, [1, int(num_pos), 1])
num_neg = neg_vecs.get_shape()[1]
dif_p = (- tf.reduce_sum(tf.squared_difference(pos_vecs, query_copies_p), 2))
print('dif_p', dif_p)
p_exp = tf.reduce_sum(tf.exp(dif... |
class DrQv2Value(nn.Module):
def __init__(self, observation_space: gym.Space, action_space: gym.Space, feature_dim: int=50, hidden_layers: List[int]=(1024, 1024), ensemble_size: int=1, **kwargs):
super().__init__()
self.trunk = nn.Sequential(nn.Linear(observation_space.shape[0], feature_dim), nn.Lay... |
def main(args):
data_path = Path(args.data_path)
output_path = Path(args.out_path)
os.makedirs(str(output_path), exist_ok=True)
convert(data_path, 'val', output_path, args.coco_path, 0, 0) |
def preprocess_function(examples):
args = (examples[sentence1_key], examples[sentence2_key])
result = tokenizer(*args, padding=padding, max_length=max_seq_length, truncation=True)
return result |
class MultiControlNetModel(ModelMixin):
def __init__(self, controlnets: Union[(List[ControlNetModel], Tuple[ControlNetModel])]):
super().__init__()
self.nets = nn.ModuleList(controlnets)
def forward(self, sample: torch.FloatTensor, timestep: Union[(torch.Tensor, float, int)], encoder_hidden_stat... |
def leaky_relu(x, alpha=0.2):
return tf.where(tf.greater_equal(x, 0.0), x, tf.multiply(alpha, x)) |
class MapFeatures(SourcewiseTransformer):
def __init__(self, data_stream, fn, **kwargs):
super(MapFeatures, self).__init__(data_stream, produces_examples=False, which_sources='features')
self.fn = fn
def transform_source_batch(self, source_batch, source_name):
if (source_name != 'feature... |
class CustomPolicy(FeedForwardPolicy):
def __init__(self, *args, **kwargs):
super(CustomPolicy, self).__init__(*args, **kwargs, net_arch=[64, 64, 64], act_fun=tf.nn.relu, feature_extraction='mlp') |
def recall(gt, pr, class_weights=1, class_indexes=None, smooth=SMOOTH, per_image=False, threshold=None, **kwargs):
backend = kwargs['backend']
(gt, pr) = gather_channels(gt, pr, indexes=class_indexes, **kwargs)
pr = round_if_needed(pr, threshold, **kwargs)
axes = get_reduce_axes(per_image, **kwargs)
... |
def gaussian_sample(x, mu=None, log_sigma=None):
if ((mu is None) or (log_sigma is None)):
return x
return (mu + (torch.exp(log_sigma) * x)) |
class CIFAR10Policy(object):
def __init__(self, fillcolor=(128, 128, 128), magnitude_factor=1):
print(f'AutoAugment CIFAR10 - Magnitude {magnitude_factor}')
self.policies = [SubPolicy(0.1, 'invert', 7, 0.2, 'contrast', 6, fillcolor, magnitude_factor), SubPolicy(0.7, 'rotate', 2, 0.3, 'translateX', 9... |
def test(args):
processor = data_utils.AscProcessor()
label_list = processor.get_labels()
tokenizer = BertTokenizer.from_pretrained(args.pretrained_model_dir)
eval_examples = processor.get_test_examples(args.data_dir, 'test_rels.json', method=args.method)
eval_features = data_utils.convert_examples_... |
def _scope_all(scope, default_scope=None):
with tf.variable_scope(scope, default_name=default_scope) as s, tf.name_scope(s.original_name_scope):
(yield s) |
_lr_scheduler('inverse_linear')
class InverseLinearRootSchedule(FairseqLRScheduler):
def __init__(self, args, optimizer):
super().__init__(args, optimizer)
warmup_end_lr = args.lr
if (args.warmup_init_lr < 0):
args.warmup_init_lr = warmup_end_lr
self.lr_step = ((warmup_en... |
class MemcachedBackend(BaseStorageBackend):
def __init__(self, server_list_cfg, client_cfg, sys_path=None):
if (sys_path is not None):
import sys
sys.path.append(sys_path)
try:
import mc
except ImportError:
raise ImportError('Please install mem... |
def CheckCaffeDataLayerSetUp(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
ix = line.find('DataLayer<Dtype>::LayerSetUp')
if ((ix >= 0) and ((line.find('void AnnotatedDataLayer<Dtype>::LayerSetUp') != (- 1)) or (line.find('void DataLayer<Dtype>::LayerSetUp') != (- 1)) or (line.f... |
def nlvr2_triplet_eval_collate(inputs):
(qids, batch) = ([], [])
for (id_, *tensors) in inputs:
qids.append(id_)
batch.append(tensors)
batch = nlvr2_triplet_collate(batch)
batch['qids'] = qids
return batch |
def tf_mobilenetv3_small_075(pretrained=False, **kwargs):
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_mobilenet_v3('tf_mobilenetv3_small_075', 0.75, pretrained=pretrained, **kwargs)
return model |
def generate_cca_projection():
(images, sentences) = [torch.cat(l) for l in zip(*[(d[0], d[1][0]) for d in train_loader])]
emb = fn_to_emb(sentences.int())
(corr, (im_proj, emb_proj)) = cca([images, emb], k=40)
print('Largest eigen value from CCA: {:.3f}'.format(corr[0]))
torch.save(images.mean(dim=... |
def _download_single_image(label_path: Path, img_tuple: tuple, i: int, timeout: int=4) -> None:
suffix = re.findall('\\.\\w+?(?=(?:\\?|$))', img_Tuple[1])
suffix = (suffix[0].lower() if (len(suffix) > 0) else '.jpg')
fname = f'{i:08d}{suffix}'
download_url(img_Tuple[1], (label_path / fname), timeout=tim... |
def get_bijection(layer_config, x_shape):
if (layer_config['type'] == 'acl'):
return get_acl_bijection(config=layer_config, x_shape=x_shape)
elif (layer_config['type'] == 'squeeze'):
return Squeeze2dBijection(x_shape=x_shape, factor=layer_config['factor'])
elif (layer_config['type'] == 'logi... |
class OutConv(nn.Module):
def __init__(self, in_channels, out_channels):
super(OutConv, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)
def forward(self, x):
return self.conv(x) |
def resnet152gn(pretrained=False, **kwargs):
model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))
return model |
def spheric2cartesian(r, theta, phi):
x = ((r * np.cos(phi)) * np.cos(theta))
y = ((r * np.sin(phi)) * np.cos(theta))
z = (r * np.sin(theta))
return (x, y, z) |
class StudentT(Normal):
def __init__(self, dofs, means=None, covs=None, covariance_type='diag', min_cov=None, inertia=0.0, frozen=False, check_data=True):
self.name = 'StudentT'
dofs = _check_parameter(_cast_as_tensor(dofs), 'dofs', min_value=1, ndim=0, dtypes=(torch.int32, torch.int64))
sel... |
def constrain_norm(grad: P, norm_constraint: chex.Numeric=0.001) -> P:
sq_norm_scaled_grads = tree_inner_product(grad, grad)
sq_norm_scaled_grads = utils.distribute.pmean_if_pmap(sq_norm_scaled_grads)
norm_scale_factor = jnp.sqrt((norm_constraint / sq_norm_scaled_grads))
coefficient = jnp.minimum(norm_s... |
def test_sort_parents(a_pcmci):
(pcmci, _) = a_pcmci
orig_parents = []
n_parents = 10
for i in range(n_parents):
orig_parents.append((i, i))
parent_vals = {}
sign = 1
for (val, par) in enumerate(orig_parents):
sign *= (- 1)
parent_vals[par] = (val * sign)
sorted_p... |
class PolyOptimizer(torch.optim.SGD):
def __init__(self, params, lr, weight_decay, max_step, momentum=0.9):
super().__init__(params, lr, weight_decay)
self.global_step = 0
self.max_step = max_step
self.momentum = momentum
self.__initial_lr = [group['lr'] for group in self.par... |
class KLDivLoss(nn.Module):
def __init__(self, reduction='batchmean', log_target=False):
super().__init__()
self.kld = nn.KLDivLoss(reduction=reduction, log_target=log_target)
def forward(self, pred, target):
return self.kld(pred.log_softmax(dim=1), target) |
_torch
_vision
class CLIPImageProcessingTest(ImageProcessingSavingTestMixin, unittest.TestCase):
image_processing_class = (CLIPImageProcessor if is_vision_available() else None)
def setUp(self):
self.image_processor_tester = CLIPImageProcessingTester(self)
def image_processor_dict(self):
ret... |
class NLayerDiscriminator(nn.Module):
def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, use_sigmoid=False, gpu_ids=[]):
super(NLayerDiscriminator, self).__init__()
self.gpu_ids = gpu_ids
kw = 4
padw = int(np.ceil(((kw - 1) / 2)))
sequence = [nn.Conv2... |
def rla_mobilenetv2_k6_eca(eca=True):
print('Constructing rla_mobilenetv2_k6_eca......')
model = RLA_MobileNetV2(rla_channel=6, ECA=eca)
return model |
class WDS(nn.Module):
def __init__(self, in_channels, num_classes):
super(WDS, self).__init__()
self.b1_1 = basic_block(in_channels, 64)
self.b1_2 = basic_block(64, 64)
self.b1_3 = basic_block(64, 64)
self.b1_4 = basic_block(64, 64)
self.b1_5 = nn.MaxPool2d(2, stride=... |
class KITTI_Odo(object):
def __init__(self, data_dir):
self.data_dir = data_dir
self.train_seqs = ['00', '01', '02', '03', '04', '05', '06', '07', '08']
def __len__(self):
raise NotImplementedError
def prepare_data_mp(self, output_dir, stride=1):
num_processes = 16
pr... |
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = (out_features or in_features)
hidden_features = (hidden_features or in_features)
self.fc1 = nn.Linear(in_features, hidden_fea... |
def conv_resblock_two(in_channels, out_channels, stride=1):
return nn.Sequential(conv3x3(in_channels, out_channels, stride), nn.ReLU(), ResBlock(out_channels), ResBlock(out_channels)) |
class FactoryType(ValueType):
def __init__(self, name, typeMap):
self.name = name
self.typeMap = typeMap
self.nameMap = {}
for (key, value) in typeMap.items():
self.nameMap[value] = key
def from_xml(self, node):
cur_type = self.typeMap.get(node.tag)
if... |
def is_spark_below_2_2():
import pyspark
if hasattr(pyspark, 'version'):
full_version = pyspark.version.__version__
parts = full_version.split('.')
spark_version = ((parts[0] + '.') + parts[1])
if (compare_version(spark_version, '2.2') >= 0):
return False
return T... |
def run_circuit(num_qubits):
reg = iqs.QubitRegister(num_qubits, 'base', 0, 0)
for i in range(num_qubits):
reg.ApplyHadamard(i)
reg.ApplyRotationZ(i, (np.pi / 3))
return reg |
def train_autokeras(X_train, X_test, y_train, y_test, mtype, common_name_model, problemtype, classes, default_featurenames, transform_model, settings, model_session):
files = list()
model_name = common_name_model
if (mtype == 'c'):
if ('structured_data_classifier' in os.listdir()):
shuti... |
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default... |
def mixture_function(X, w0=1.0, w1=1.0):
X_sum = X.sum(axis=0)
return ((w0 * numpy.sqrt(X_sum).sum()) + (w1 * numpy.log1p(X_sum).sum())) |
_module
class FMF_Concat_VN(SingleStageDetector):
def __init__(self, reader, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None):
super(FMF_Concat_VN, self).__init__(reader, backbone, neck, bbox_head, train_cfg, test_cfg, pretrained)
def extract_feat(self, data):
input_fea... |
class ResBlock_SFT(nn.Module):
def __init__(self):
super(ResBlock_SFT, self).__init__()
self.sft0 = SFTLayer()
self.conv0 = nn.Conv2d(64, 64, 3, 1, 1)
self.sft1 = SFTLayer()
self.conv1 = nn.Conv2d(64, 64, 3, 1, 1)
def forward(self, x):
fea = self.sft0(x)
f... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp15():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym'] ... |
def sample_actions(rng: PRNGKey, actor_def: nn.Module, actor_params: Params, observations: np.ndarray, temperature: float=1.0) -> Tuple[(PRNGKey, jnp.ndarray)]:
return _sample_actions(rng, actor_def, actor_params, observations, temperature) |
def get_local_db_shimmer(amplitudes, frequencies, max_a_factor, p_floor, p_ceil, max_p_factor):
cumsum = 0
counter = 0
for ((freq1, freq2), (amp1, amp2)) in zip(shifted_sequence(frequencies, 2), shifted_sequence(amplitudes, 2)):
if validate_amplitudes([amp1, amp2], [freq1, freq2], max_a_factor, p_fl... |
def check_part_score(coco_dt, part):
flag_no_part_score = False
for k in coco_dt.anns.keys():
if ('{}_score'.format(part) not in coco_dt.anns[k]):
flag_no_part_score = True
coco_dt.anns[k]['{}_score'.format(part)] = coco_dt.anns[k]['score']
if flag_no_part_score:
warn... |
def nature2022():
if (sf.backend() == 'tensorflow'):
loss = 'sparse_categorical_crossentropy'
else:
loss = 'CrossEntropy'
return sf.ModelParams(model='xception', tile_px=299, tile_um=302, batch_size=128, epochs=[1], early_stop=True, early_stop_method='accuracy', dropout=0.1, uq=False, hidden... |
def get_xla_device_type(device: 'torch.device') -> Optional[str]:
if is_torch_tpu_available():
return xm.xla_real_devices([device])[0].split(':')[0]
return None |
class Up34(nn.Module):
def __init__(self, in_channels, out_channels, bilinear=True):
super().__init__()
if bilinear:
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
else:
self.up = nn.ConvTranspose2d((in_channels // 2), (in_channels // 2), k... |
_config
def cfg_navigation():
uuid = 'gibson_visualnavigation'
cfg = {}
cfg['learner'] = {'algo': 'ppo', 'clip_param': 0.1, 'entropy_coef': 0.0001, 'eps': 1e-05, 'gamma': 0.99, 'internal_state_size': 512, 'lr': 0.0001, 'num_steps': 512, 'num_mini_batch': 8, 'num_stack': 4, 'max_grad_norm': 0.5, 'ppo_epoch':... |
_model
def vit_base_resnet50d_224(pretrained=False, **kwargs):
backbone = resnet50d(pretrained=pretrained, in_chans=kwargs.get('in_chans', 3), features_only=True, out_indices=[4])
model_kwargs = dict(embed_dim=768, depth=12, num_heads=12, **kwargs)
model = _create_vision_transformer_hybrid('vit_base_resnet5... |
class ExamplesTests(TestCasePlus):
def test_run_glue(self):
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f'''
run_glue.py
--model_name_or_path distilbert-base-uncased
... |
def MakeJigsawsMultiDecoder(model, decoder, num_images=4, h_dim=(12, 16)):
h = Input((h_dim[0], h_dim[1], 64), name='h_in')
xs = []
for i in range(num_images):
xi = h
xi = AddConv2D(xi, 64, [5, 5], stride=1, dropout_rate=0.0)
xi = AddConv2D(xi, model.encoder_channels, [5, 5], stride=... |
class TransformerCore(nn.Module):
def __init__(self, embed, num_layers, latent_dim, hidden_size, heads, dropout=0.0, max_length=100):
super(TransformerCore, self).__init__()
self.embed = embed
self.padding_idx = embed.padding_idx
embed_dim = embed.embedding_dim
self.embed_sca... |
def test_load_image_accepts_pil(mocker):
preprocess_mocker = mocker.patch('imagededup.utils.image_utils.preprocess_image')
load_image(PATH_SINGLE_IMAGE)
preprocess_mocker.assert_called_once_with(Image.open(PATH_SINGLE_IMAGE), target_size=None, grayscale=False) |
def assert_filetree(args):
gt_folders = set(os.listdir(args.gt_folder))
pred_folders = set(os.listdir(args.pred_folder))
assert (gt_folders == pred_folders), '{} and {} contains different PDF files!'.format(args.gt_folder, args.pred_folder) |
_schema(TranspileConfigSchema)
class TranspileConfig(BaseModel):
def __init__(self, optimization_level, **kwargs):
self.optimization_level = optimization_level
super().__init__(**kwargs) |
def custom_mlp_args(parser):
custom_mlp_args = parser.add_argument_group('custom mlp args', 'architecture arguments for the custom mlp')
custom_mlp_args.add_argument('--body', type=str, default='', metavar='{num}-{num}-...', help='architecture of the shared latent network, each number representing the number of... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments, OptimizationArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args, optim_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
el... |
class DGEMO(MOBO):
config = {'surrogate': 'gp', 'acquisition': 'identity', 'solver': 'discovery', 'selection': 'dgemo'} |
def load_D_model(args, model):
logging.info('')
if args.D_resume:
if os.path.isfile(args.D_ckpt_path):
checkpoint = torch.load(args.D_ckpt_path)
args.last_step = (checkpoint['step'] if ('step' in checkpoint) else None)
model.load_state_dict(checkpoint['state_dict'])
... |
def parse_annotation(anno_file):
with open(anno_file, 'r') as f:
annotations = json.load(f)['annotations']
q_2_anno = dict([(a['question_id'], a) for a in annotations])
return q_2_anno |
def download_by_url():
import argparse
parser = argparse.ArgumentParser(description='Use this to download pretrained models. This script is intended to download models via url only. If you want to download one of our pretrained models, please use nnUNet_download_pretrained_model. CAREFUL: This script will overw... |
def send_graph_to_cpu(g):
labels = g.node_attr_schemes()
for l in labels.keys():
g.ndata[l] = g.ndata.pop(l).cpu()
labels = g.edge_attr_schemes()
for l in labels.keys():
g.edata[l] = g.edata.pop(l).cpu()
return g |
class TestPruningPatterns(unittest.TestCase):
model = torchvision.models.resnet18()
def test_pruning_pattern(self):
local_configs = [{'op_names': ['layer1.*'], 'target_sparsity': 0.5, 'pattern': '5:8', 'pruning_type': 'magnitude'}, {'op_names': ['layer2.*'], 'pattern': '1xchannel', 'pruning_scope': 'glo... |
class AccumMetaLoader(object):
def __init__(self, loaders, distributed=False):
assert isinstance(loaders, dict)
self.name2loader = {}
self.name2iter = {}
self.sampling_pools = []
for (idx, (n, l)) in enumerate(loaders.items()):
if isinstance(l, tuple):
... |
class InvLrUpdaterHook(LrUpdaterHook):
def __init__(self, gamma, power=1.0, **kwargs):
self.gamma = gamma
self.power = power
super(InvLrUpdaterHook, self).__init__(**kwargs)
def get_lr(self, trainer, base_lr):
progress = (trainer.epoch if self.by_epoch else trainer.iter)
... |
def main():
(train_loader, test_loader, criterion, model, optimizer, scheduler, starting_epoch, logfilename, model_path, device, writer) = prologue(args)
for epoch in range(starting_epoch, args.epochs):
before = time.time()
(train_loss, train_acc) = train(train_loader, model, criterion, optimize... |
def compress(model, ratio=0.5):
if isinstance(model.estimators_, CompressedEstimators):
raise Exception('The model is already compressed.')
model.estimators_ = CompressedEstimators(model, ratio) |
def unsplit_query(query, qrepr, vocab_inv):
PAD_WORD_INDEX = 0
if (qrepr == 'word'):
return ' '.join([vocab_inv[int(w)] for w in query if (w != PAD_WORD_INDEX)])
elif (qrepr == 'char'):
return ''.join([vocab_inv[int(w)] for w in query if (w != PAD_WORD_INDEX)])
elif qrepr.endswith('gram'... |
def main():
parser = HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
(model_args, data_args, training_args) = parser.parse_args_into_dataclasses()
if (os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and (not training_args.over... |
def main():
args = get_arguments()
for (arg_name, arg_var) in args.__dict__.items():
print(f'{arg_name:<16} : {arg_var}')
seq_lens = [(2 ** i) for i in range(10, 18)]
attn_method = args.attn_method
mode = args.mode
(batch_size, head_size, dim) = (1, 32, 64)
print(f'mode: {mode}, attn... |
def _get_inputs(input_queue, num_classes):
read_data_list = input_queue.dequeue()
label_id_offset = 1
def extract_images_and_targets(read_data):
image = read_data[fields.InputDataFields.image]
location_gt = read_data[fields.InputDataFields.groundtruth_boxes]
classes_gt = tf.cast(read... |
_model
def skresnet34(pretrained=False, **kwargs):
sk_kwargs = dict(min_attn_channels=16, attn_reduction=8, split_input=True)
model_args = dict(block=SelectiveKernelBasic, layers=[3, 4, 6, 3], block_args=dict(sk_kwargs=sk_kwargs), zero_init_last_bn=False, **kwargs)
return _create_skresnet('skresnet34', pret... |
def _find_roctracer_config(rocm_install_path):
def roctracer_version_numbers(path):
possible_version_files = ['include/roctracer/roctracer.h', 'roctracer/include/roctracer.h']
version_file = None
for f in possible_version_files:
version_file_path = os.path.join(path, f)
... |
class MazeGenerator():
def __init__(self, params) -> None:
self.params = params
def has_el_prev_row(self, grid, row_idx, cell_idx):
return ((row_idx > 0) and (grid[(row_idx - 1)][cell_idx] == 1))
def has_el_next_row(self, grid, row_idx, cell_idx):
return ((row_idx < (len(grid) - 1)) ... |
def build_low_latency_conv(input_frames, input_bins, n_classes=12, dropout=0.5):
from keras.layers import Conv2D, Dense, Dropout, Flatten
input_shape = (input_frames, input_bins, 1)
model = keras.Sequential([Conv2D(186, (input_frames, 8), strides=(1, 1), padding='valid', activation='relu', use_bias=True, in... |
class FB15KLoader(BaseLoader):
def __init__(self, dataset_path, download=False):
super().__init__(dataset_path, download, raw_data_path='FB15K/raw_data', processed_data_path='FB15K/processed_data', train_name='freebase_mtr100_mte100-train.txt', valid_name='freebase_mtr100_mte100-valid.txt', test_name='freeb... |
class Normal(Dist):
def __init__(self, device='cpu'):
super().__init__()
self.device = device
self.c = ((2 * np.pi) * torch.ones(1).to(self.device))
self._dist = dist.normal.Normal(torch.zeros(1).to(self.device), torch.ones(1).to(self.device))
self.name = 'gauss'
def samp... |
class DTLZ5(DTLZ1):
def __init__(self, number_of_variables: int=12, number_of_objectives=3):
super(DTLZ5, self).__init__(number_of_variables, number_of_objectives)
def evaluate(self, solution: FloatSolution) -> FloatSolution:
k = ((self.number_of_variables() - self.number_of_objectives()) + 1)
... |
def get_fname(line):
p = os.path.basename(line.split('\t')[0])
p = os.path.splitext(p)[0]
return p |
class DistillKL(nn.Module):
def __init__(self, args):
super(DistillKL, self).__init__()
self.T = args.temperature
def forward(self, y_s, y_t):
p_s = F.log_softmax((y_s / self.T), dim=1)
p_t = F.softmax((y_t / self.T), dim=1)
loss = ((F.kl_div(p_s, p_t.detach(), reduction=... |
_module()
class ATSS(SingleStageDetector):
'Implementation of `ATSS <
def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None):
super(ATSS, self).__init__(backbone, neck, bbox_head, train_cfg, test_cfg, pretrained) |
def extract_total_degree(result):
(poly, poly_horner, p_x_expected, p_x, p_x_horner) = result
return poly.total_degree |
def set_requires_grad(model, requires_grad: bool) -> None:
for param in model.parameters():
param.requires_grad = requires_grad |
def test_encode_image_2_dim_array_encoded(cnn):
arr_inp = np.array(Image.open(TEST_IMAGE_GRAY))
encoding = cnn.encode_image(image_array=arr_inp)
assert (encoding.shape == (1, 576)) |
def main():
model = create_network().to(device)
optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)
EvalAttack = config.create_evaluation_attack_method(device)
now_train_time = 0
for epoch in range(1, (args.epochs + 1)):
adjust_learni... |
(scope='module')
def rleaky_hidden_instance():
return snn.RLeaky(beta=0.5, V=0.5, all_to_all=False, init_hidden=True) |
def taskonomy_features_transform_collated(task_path, dtype=np.float32):
net = TaskonomyEncoder().cuda()
net.eval()
checkpoint = torch.load(task_path)
net.load_state_dict(checkpoint['state_dict'])
def encode(x):
with torch.no_grad():
x = torch.Tensor(x).cuda()
if isins... |
def test_fsm_logging():
env = FiniteStateMachineEnv(num_steps=2, network=Network(), initial_stage=0, stages=[FSMStage(0, [], None, [1]), FSMStage(1, [], None, [0])])
episode = MockEpisode()
base_env = MockBaseEnv(env)
callback = RLlibMetricLogger({'stage_0_metric': MockMetric(0, 'sum', fsm_stages=[0]), ... |
def AutogradCrypTensor(tensor, requires_grad=True):
raise DeprecationWarning('AutogradCrypTensor is deprecated. Please set the requires_grad attribute on the CrypTensor instead.')
if torch.is_tensor(tensor):
tensor = crypten.cryptensor(tensor)
tensor.requires_grad = requires_grad
return tensor |
def train(model, criterion, optimizer, scheduler, train_loader):
model.train()
acc_losses = {}
for (i, (x, _)) in enumerate(train_loader):
optimizer.zero_grad()
x = x.to(args.device)
output = model(x)
(loss, diagnostics) = criterion(x, output, model)
loss.backward(ret... |
def snapshot(dir_path, run_name, is_best, state):
snapshot_file = os.path.join(dir_path, (run_name + '-model_best.pth'))
if is_best:
torch.save(state, snapshot_file)
logger.info('Snapshot saved to {}\n'.format(snapshot_file)) |
class HDF5OutputParameter(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _HDF5OUTPUTPARAMETER |
def efficientnet_b3b(in_size=(300, 300), **kwargs):
return get_efficientnet(version='b3', in_size=in_size, tf_mode=True, bn_eps=0.001, model_name='efficientnet_b3b', **kwargs) |
def PreResNet110(num_class=10, block=None, attention_module=None):
if (block == PreBasicBlock):
n_blocks = [18, 18, 18]
elif (block == PreBottleNect):
n_blocks = [12, 12, 12]
return PreResNetWrapper(num_blocks=n_blocks, num_class=num_class, block=block, attention_module=attention_module) |
class _NCEGenerator(object):
def __init__(self, dataset, batch_size, context_size, num_noise_words, state):
self.dataset = dataset
self.batch_size = batch_size
self.context_size = context_size
self.num_noise_words = num_noise_words
self._vocabulary = self.dataset.fields['text... |
class ZeroPadding3D(ZooKerasLayer):
def __init__(self, padding=(1, 1, 1), dim_ordering='th', input_shape=None, **kwargs):
super(ZeroPadding3D, self).__init__(None, padding, dim_ordering, (list(input_shape) if input_shape else None), **kwargs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.