code stringlengths 101 5.91M |
|---|
class TestStochasticNPHawkesProcessClass(unittest.TestCase):
def setUp(self):
self.history = EventSeq([0.0, 1.0, 2.0, 3.0], [0.0, 4.0])
def test_neg_ll(self):
bg_intensity = 1.0
hawkes = NonparametricHawkesProcessWithStochasticApproximation(bg_intensity=bg_intensity, n_inducing_points=5)... |
def cheetah():
locals().update(default())
env = 'HalfCheetah-v1'
max_length = 1000
steps = .0
return locals() |
()
def make_predictions(args: PredictArgs, smiles: List[str]=None) -> List[List[Optional[float]]]:
print('Loading training args')
(scaler, features_scaler) = load_scalers(args.checkpoint_paths[0])
train_args = load_args(args.checkpoint_paths[0])
(num_tasks, task_names) = (train_args.num_tasks, train_arg... |
def pyaudio_featurize(file, basedir):
curdir = os.getcwd()
shutil.copy(((curdir + '/') + file), ((basedir + '/helpers/') + file))
os.chdir((basedir + '/helpers/'))
os.system(('python3 %s/helpers/pyaudio_help.py %s' % (basedir, file)))
jsonfile = (file[0:(- 4)] + '.json')
g = json.load(open(jsonf... |
def split_shard_dim_with_reshuffle_check(input_, shard_dim, group=None, ranks=None):
return _SplitShardDimReshuffleCheck.apply(input_, shard_dim, group, ranks) |
def main():
args = parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = ','.join((str(gpu) for gpu in args.gpus))
cfg = Config.fromfile(args.config)
cfg.gpus = len(args.gpus)
cfg.load_from = args.load_from
cfg.finetune_from = args.finetune_from
cfg.view = args.view
cfg.work_dirs = ((args.wo... |
def test_cvrp__equivalence_dense_sparse_reward(cvrp_dense_reward: CVRP, cvrp_sparse_reward: CVRP) -> None:
dense_step_fn = jax.jit(cvrp_dense_reward.step)
sparse_step_fn = jax.jit(cvrp_sparse_reward.step)
key = jax.random.PRNGKey(0)
(state, timestep) = cvrp_dense_reward.reset(key)
return_dense = tim... |
def process_one_sentence(sent_parse: TreeNode, abs_str: str) -> List:
abs_list = abs_str.split(' ')
sent_tree = read_single_parse_tree(sent_parse)
tree_len = len(sent_tree.text)
abs_len = len(abs_str.split(' '))
sent_str = ' '.join(sent_tree.text)
rt_del_spans = []
del_spans = find_deletable... |
def train_single_epoch(epoch, model, train_loader, transform, optimizer, eval_loader, plotfilename=None):
model.train()
(errs, losses) = ([], [])
start = datetime.now()
for (idx, (x, y, clas)) in enumerate(train_loader):
x = torch.unsqueeze(x, dim=1)
optimizer.zero_grad()
(x, y, ... |
def _count_tokens(files, file_byte_limit=1000000.0, correct_strip=True):
token_counts = collections.defaultdict(int)
for filepath in files:
with tf.io.gfile.GFile(filepath, mode='r') as reader:
file_byte_budget = file_byte_limit
counter = 0
lines_to_skip = int((reader... |
class FewShotSeg(nn.Module):
def __init__(self, pretrained_weights='deeplabv3'):
super().__init__()
self.encoder = Res101Encoder(replace_stride_with_dilation=[True, True, False], pretrained_weights=pretrained_weights)
self.device = torch.device('cuda')
self.scaler = 20.0
self... |
class Seq2SeqQuestionAnsweringModelOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
start_logits: torch.FloatTensor = None
end_logits: torch.FloatTensor = None
past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
... |
def zero_padding(text_tensor, tar_dim, device=None):
padding_size = (tar_dim - text_tensor.shape[1])
zero_tensor = torch.zeros((text_tensor.shape[0], padding_size), device=device)
padded_tensor = torch.cat([text_tensor, zero_tensor], dim=1)
return padded_tensor |
def test_inv_link_monoclassification0():
scores = np.array([[]])
expected = np.array([[1.0]])
result = inv_link(scores, 'monoclassification')
assert np.all((result == expected)) |
def get_existing_item(var_full_name, collection_name):
var_list = tf.get_collection(collection_name)
for v in var_list:
if (v.name == var_full_name):
return v
return None |
class SparseGraphConvolution(nn.Module):
def __init__(self, in_features: int, out_features: int, bias: bool=False):
super(SparseGraphConvolution, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = Parameter(torch.FloatTensor(in_features, ou... |
class LOSComputationGraph():
class Node():
def __init__(self, resolution, idx, residual=False):
(self.resolution, self.idx, self.residual) = (resolution, idx, residual)
self.residual_node = None
def __repr__(self):
residual_str = (', saves residual' if self.residu... |
def reset_sim(sim):
arcsim.init_physics('conf/rigidcloth/absparse/abqr_make.json', 'qr_out/out', False) |
class Mosei_Dataset(Dataset):
def __init__(self, name, args, token_to_ix=None, dataroot='data'):
super(Mosei_Dataset, self).__init__()
assert (name in ['train', 'valid', 'test', 'private'])
self.name = name
self.args = args
self.private_set = (name == 'private')
self.... |
def optimal_transport_dist(txt_emb, img_emb, txt_pad, img_pad, beta=0.5, iteration=50, k=1):
cost = cost_matrix_cosine(txt_emb, img_emb)
joint_pad = (txt_pad.unsqueeze((- 1)) | img_pad.unsqueeze((- 2)))
cost.masked_fill_(joint_pad, 0)
txt_len = (txt_pad.size(1) - txt_pad.sum(dim=1, keepdim=False)).to(dt... |
def _block_shuffle(lst, block_size):
blocks = [lst[i:(i + block_size)] for i in range(0, len(lst), block_size)]
random.shuffle(blocks)
return [ele for block in blocks for ele in block] |
def test_iterator_cycle():
dataset = _construct_dataset(100)
ep_iter = dataset.get_episode_iterator(cycle=True, shuffle=False, group_by_scene=False)
for i in range(200):
episode = next(ep_iter)
assert (episode.episode_id == dataset.episodes[(i % 100)].episode_id)
ep_iter = dataset.get_ep... |
class stochastic_energy_latency_50(nn.Module):
def __init__(self):
super(stochastic_energy_latency_50, self).__init__()
self.name = 'stochastic_energy_latency_50'
self.find = nn.Sequential(NPNLinear((50 * 52), 128, False), NPNRelu(), NPNLinear(128, 128), NPNRelu(), NPNLinear(128, 64), NPNRel... |
def log_optimal_transport(scores: torch.Tensor, alpha: torch.Tensor, iters: int) -> torch.Tensor:
(b, m, n) = scores.shape
one = scores.new_tensor(1)
(ms, ns) = ((m * one).to(scores), (n * one).to(scores))
bins0 = alpha.expand(b, m, 1)
bins1 = alpha.expand(b, 1, n)
alpha = alpha.expand(b, 1, 1)
... |
class TFKubernetesWorker():
def __init__(self, args):
self._args = args
task_conf = get_conf(py_conf=args.conf)
self._task_conf = task_conf
self.estimator_server_started = False
self.init_executor(task_conf)
def init_executor(self, task_conf):
logger.info('init_ex... |
def get_post_fmean(gp, X, Z, params=None):
ndata = X.shape[0]
ndims = X.shape[1]
ntest = Z.shape[0]
(lik_params, prior_params) = gp.decomp_params(params)
alpha = gp.stats[1]
fmu = gp.prior.get_mean(ntest)
G = gp.prior.get_cov(X=Z, Z=X, params=prior_params)
return (G.dot(alpha) + fmu) |
def test_find_1d_closest_idx_to_origin() -> None:
x = np.array([0., 0., 0., (- 0.)])
pos_idx = synthetic_crosswalk_generator.find_1d_closest_idx_to_origin(x, 'positive')
assert (pos_idx == 2)
neg_idx = synthetic_crosswalk_generator.find_1d_closest_idx_to_origin(x, 'negative')
assert (neg_idx == 3) |
def filter_answers(answers_dset, min_occurence):
occurence = {}
for ans_entry in answers_dset:
gtruth = ans_entry.get('multiple_choice_answer', None)
if (gtruth is None):
gtruth = ans_entry['answers'][0]['answer']
gtruth = preprocess_answer(gtruth)
if (gtruth not in o... |
def create_dataset_zundamon(filename):
textful_dir_list = glob.glob('dataset/textful/*')
textless_dir_list = glob.glob('dataset/textless/*')
textful_dir_list.sort()
textless_dir_list.sort()
Correspondence_list = list()
output_file_list = list()
output_file_list_val = list()
output_file_l... |
_model
def mobilenetv3_small_100(pretrained=False, **kwargs):
model = _gen_mobilenet_v3('mobilenetv3_small_100', 1.0, pretrained=pretrained, **kwargs)
return model |
def test_series_captured(capture):
with capture:
m.captured_output('a')
m.captured_output('b')
assert (capture == 'ab') |
def train(model, train_data_loader, test_data_loader, epochs, criterion, optimizer, filename='test_cm'):
for epoch in range(epochs):
model.train()
total_loss = 0.0
total = 0
correct = 0
for (i, data) in enumerate(train_data_loader):
(inputs, labels) = data
... |
def convert_model_th_to_tf(torch_module, checkpoint):
import onnx
from onnx_tf.backend import prepare
import tensorflow as tf
class TFStoredModel():
def __init__(self, model, output_type, output_names):
self.model = model
self.output_type = output_type
self.ou... |
class HuggingFaceBgeEmbeddings(langchain_core.pydantic_v1.BaseModel, langchain_core.embeddings.Embeddings):
client: Any
model_name: str = DEFAULT_BGE_MODEL
cache_folder: Optional[str] = None
model_kwargs: Dict[(str, Any)] = langchain_core.pydantic_v1.Field(default_factory=dict)
encode_kwargs: Dict[(... |
def parse_faiss_specs(specs_str):
specs = []
for ss in specs_str.split():
comps = ss.split('_')
pca = 0
norm = False
n_clus = 0
sphere = False
for c in comps:
if c.startswith('PCA'):
pca = int(c[3:])
elif (c == 'NORM'):
... |
def test_build():
model = Myeffnet(clip_pretrain_path='/mnt/lustre/zhangyuanhan/architech/efficientnet_b4_ra2_320-7eb33cd5.pth')
image = torch.rand(2, 3, 224, 224)
output = model(image)
print(output.shape) |
class AttenResNet5(nn.Module):
def __init__(self, atten_activation, atten_channel=16, temperature=1, size1=(257, 1091), size2=(249, 1075), size3=(233, 1043), size4=(201, 979), size5=(137, 851)):
super(AttenResNet5, self).__init__()
self.temperature = temperature
self.pre = nn.Sequential(nn.C... |
class GCN(nn.Module):
def __init__(self, g, num_layers, in_dim, num_hidden, num_classes, heads, activation, feat_drop, attn_drop, negative_slope, residual):
super(GCN, self).__init__()
self.g = g
self.gat_layers = []
self.num_layers = num_layers
self.gat_layers = nn.ModuleLis... |
def validate(val_loader, config) -> None:
val_losses = defaultdict(list)
i_val_step = 0
for input in val_loader:
i_val_step += 1
input = input.to(config.device)
(loss_dict, anomaly_map, anomaly_score, input_recon) = vae_val_step(input)
for (k, v) in loss_dict.items():
... |
def preprocess_for_reward_modeling(df: pd.DataFrame, prompt_dict: dict, tokenizer: transformers.PreTrainedTokenizer, df_postprocessor: Optional[Callable]=None, end_sequence_with_eos: bool=False, verbose=True) -> dict[(str, torch.Tensor)]:
if (df_postprocessor is not None):
df = df_postprocessor(df)
list... |
class PGReLU(torch.nn.Module):
def __init__(self):
super(PGReLU, self).__init__()
def forward(self, x):
return PGReLUFunc.apply(x) |
class InfiniteDataLoader():
def __init__(self, dataset, weights, batch_size, num_workers):
super().__init__()
self.dataset = dataset
if weights:
sampler = torch.utils.data.WeightedRandomSampler(weights, replacement=True, num_samples=batch_size)
else:
sampler =... |
def dataset_generation():
data_dir = tf.keras.utils.get_file('flower_photos', origin=flower_dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)
train_ds = tf.keras.utils.image_dataset_from_directory(data_dir, validation_split=0.2, subset='training', seed=123, image_size=(img_height, img_width), batch... |
def evaluate_3rd_item_task_fastgcnnew(valid_batch_index, model, sess, valid_data, is_training):
(evaluate_loss, evaluate_pearson) = (0.0, 0.0)
(valid_target_item, valid_k_shot_user, valid_second_order_items, valid_third_order_users, valid_oracle_item_ebd, valid_mask_num_second_order_item, valid_mask_num_third_o... |
def main(args):
config = Config.load_config_json(os.path.join(args.log_dir, 'config.json'))
if config.caption_model.endswith('_prune'):
config.caption_model = replace_from_right(config.caption_model, '_prune', '', 1)
config.update({k: v for (k, v) in vars(args).items() if (v is not None)})
ckpt_... |
def train_one_epoch(model: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, log_writer=None, args=None):
model.train(True)
metric_logger = misc.MetricLogger(delimiter=' ')
metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1,... |
def download_at(at_hash, path, archive_name):
r = at.get(at_hash, datastore=path, showlogs=True)
with zipfile.ZipFile(os.path.join(r, archive_name), 'r') as zip_ref:
zip_ref.extractall(os.path.join(r))
os.remove(os.path.join(r, archive_name)) |
def histogram_cli_args(base_cli_dir_args: typing.List[str], temp_dir: pathlib.Path) -> typing.List[str]:
return (base_cli_dir_args + f'-o {temp_dir}/hist.png'.split()) |
class Normalize():
def __init__(self, mean=(122.675, 116.669, 104.008)):
self.mean = mean
def __call__(self, img):
imgarr = np.asarray(img)
proc_img = np.empty_like(imgarr, np.float32)
proc_img[(..., 0)] = (imgarr[(..., 2)] - self.mean[2])
proc_img[(..., 1)] = (imgarr[(..... |
class BasicNet(nn.Module):
def __init__(self, do_batchnorm, channels, weight, pool, num_classes=10, initial_channels=1, new_num_classes=None, **kw):
super().__init__()
self.new_num_classes = new_num_classes
self.prep = ConvBN(do_batchnorm, initial_channels, channels['prep'], **kw)
se... |
def build_lr_scheduler(cfg: CfgNode, optimizer: torch.optim.Optimizer) -> torch.optim.lr_scheduler._LRScheduler:
name = cfg.SOLVER.LR_SCHEDULER_NAME
if (name == 'WarmupMultiStepLR'):
steps = [x for x in cfg.SOLVER.STEPS if (x <= cfg.SOLVER.MAX_ITER)]
if (len(steps) != len(cfg.SOLVER.STEPS)):
... |
def qkv_attention(query, key, value, mask=None, dropout=None):
d_k = query.size((- 1))
scores = (torch.matmul(query, key.transpose((- 2), (- 1))) / sqrt(d_k))
if (mask is not None):
scores.data.masked_fill_(mask.data.eq(0), (- .0))
p_attn = F.softmax(scores, dim=(- 1))
if (dropout is not Non... |
def rand_augment_transform(config_str, hparams, use_cmc=False):
magnitude = _MAX_LEVEL
num_layers = 2
weight_idx = None
config = config_str.split('-')
assert (config[0] == 'rand')
config = config[1:]
for c in config:
cs = re.split('(\\d.*)', c)
if (len(cs) < 2):
c... |
def squeezenet1_1(pretrained=False, **kwargs):
model = SqueezeNet(1.1)
if pretrained:
model.load_state_dict(torch.load(os.path.join(models_dir, squeeze1_1_model_name)))
return model |
def transform_key_func(generator, n, vocab_size, eff_vocab_size=None):
pi = torch.randperm(vocab_size, generator=generator)
xi = torch.rand((n, 1), generator=generator)
return (xi, pi) |
def convert_trax_checkpoint_to_pytorch(trax_model_pkl_path, config_file, pytorch_dump_path):
config = ReformerConfig.from_json_file(config_file)
print('Building PyTorch model from configuration: {}'.format(str(config)))
model = ReformerModelWithLMHead(config)
with open(trax_model_pkl_path, 'rb') as f:
... |
def resnet_v1_101(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, reuse=None, scope='resnet_v1_101'):
blocks = [resnet_utils.Block('block1', bottleneck, (([(256, 64, 1)] * 2) + [(256, 64, 2)])), resnet_utils.Block('block2', bottleneck, (([(512, 128, 1)] * 3) + [(512, 128, 2)])), re... |
class NeptuneCallback(TrainerCallback):
integration_version_key = 'source_code/integrations/transformers'
model_parameters_key = 'model_parameters'
trial_name_key = 'trial'
trial_params_key = 'trial_params'
trainer_parameters_key = 'trainer_parameters'
flat_metrics = {'train/epoch'}
def __in... |
def checkpoint_best_train_cb(checkpoint_path, steps_per_epoch=(- 1), num_epochs=10):
checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(filepath=os.path.join(checkpoint_path, 'cp-best-train.ckpt'), monitor='loss', verbose=0, save_best_only=True, save_weights_only=False, mode='auto', save_freq=('epoch' if (ste... |
def write_position_dependent_lexicon(lexiconp, separator):
for (word, prob, phones) in lexiconp:
phones_length = len(phones)
suffix_list = ['_I' for i in range(phones_length)]
if is_end(word, separator):
suffix_list[(- 1)] = '_E'
phones_list = [(phone + suffix) for (p... |
class Registry():
def __init__(self, name, build_func=None, parent=None, scope=None):
self._name = name
self._module_dict = dict()
self._children = dict()
self._scope = (self.infer_scope() if (scope is None) else scope)
if (build_func is None):
if (parent is not N... |
def single_process_main(args):
(args, (trainset, valset, num_train, num_val), model) = setup(args)
criterion = nn.CrossEntropyLoss()
if is_master(args.rank):
logging(('# of Parameters: %d' % sum([param.numel() for param in model.parameters()])), args.log)
if is_distributed(args.rank):
mo... |
def split_glas(args):
os.makedirs(args.fold_folder, exist_ok=True)
classes = ['benign', 'malignant']
datasetname = args.dataset
dict_classes_names = {'benign': 0, 'malignant': 1}
baseurl = args.baseurl
pre = 'Warwick_QU_Dataset_(Released_2016_07_08)'
trainsamples = dict()
testsamples = d... |
def reweighting_all_cliques(mc):
from itertools import combinations
cd = []
for c in mc:
for d in range(2, (len(c) + 1)):
cd.extend(list(combinations(c, d)))
cd = list(set(cd))
cd = dict.fromkeys(cd, 0)
for c in mc:
for d in range(2, (len(c) + 1)):
for com... |
def getnodes(tree, nodelist):
nodelist.append(tree)
for (child_name, child) in tree.children():
getnodes(child, nodelist) |
def add_bel_io(x, y, z):
bel = len(bel_name)
bel_name.append((x, y, ('io%d' % z)))
bel_type.append('SB_IO')
bel_pos.append((x, y, z))
bel_wires.append(list())
wire_cen = wire_names[(x, y, 'io_global/cen')]
wire_iclk = wire_names[(x, y, 'io_global/inclk')]
wire_latch = wire_names[(x, y, '... |
class MultiHeadAttention(nn.Module):
def __init__(self, embed_dim, num_attention_heads, dropout, output_dim=None) -> None:
super().__init__()
self.embed_dim = embed_dim
self.num_attention_heads = num_attention_heads
self.head_dim = (self.embed_dim // self.num_attention_heads)
... |
class PVRCNN_M_DB_3(Detector3DTemplate_M_DB_3):
def __init__(self, model_cfg, num_class, num_class_s2, num_class_s3, dataset, dataset_s2, dataset_s3, source_one_name, source_1):
super().__init__(model_cfg=model_cfg, num_class=num_class, num_class_s2=num_class_s2, num_class_s3=num_class_s3, dataset=dataset, ... |
def get_slim_ratio_schedule(train_slim_ratios: list, mode: str, client_num):
if mode.startswith('ln'):
ws = sorted(train_slim_ratios)
min_w = min(train_slim_ratios)
from scipy.stats import lognorm
(s, scale) = [float(v) for v in mode[len('ln'):].split('_')]
rv = lognorm(s=s, ... |
class Sensor(object):
def __init__(self, transform, config):
self.type_id = 'sensor.camera.rgb'
self.transform = transform
self.attributes = dict()
self.attributes['role_name'] = 'front'
self.attributes['image_size_x'] = str(config['img_length'])
self.attributes['imag... |
class ResNet101(nn.Module):
def __init__(self, block, layers, num_classes, phase):
self.inplanes = 64
self.phase = phase
super(ResNet101, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64, affine=affine... |
def spline_iter(xs, ys, is_training, spline_deg=2, filter_ratio=0.03, num_of_iter=10, bound=0.5):
bound = xs[int(((len(xs) - 1) * bound))]
if is_training:
num_of_iter = 10
else:
num_of_iter = 1
for _ in range(num_of_iter):
spline_ys = UnivariateSpline(xs, ys, k=spline_deg)(xs)
... |
class argument(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs |
def save_checkpoint(state, is_best, checkpoint, filename='checkpoint.pth.tar'):
filepath = os.path.join(checkpoint, filename)
torch.save(state, filepath)
if is_best:
shutil.copyfile(filepath, os.path.join(checkpoint, 'model_best.pth.tar')) |
def plot(x, y, yhat, loss, err, filename):
subplots = [221, 222, 223, 224]
plt.figure(1, figsize=(10, 8))
plt.subplots_adjust(top=0.88)
for i in range(4):
(x_, y_, yhat_) = (x.detach().numpy()[i][0], y.detach().numpy()[i], yhat.detach().numpy()[i])
plt.subplot(subplots[i])
plt.pl... |
def get_labels(path):
if path:
with open(path, 'r') as f:
labels = f.read().splitlines()
if ('O' not in labels):
labels = (['O'] + labels)
labels.append('CTC_PRED:0')
labels.append('CTC_PRED:1')
labels.append('pred_seg_label:O')
labels.append('... |
class NLayerDiscriminator(BaseNetwork):
def modify_commandline_options(parser, is_train):
parser.add_argument('--n_layers_D', type=int, default=4, help='# layers in each discriminator')
return parser
def __init__(self, opt):
super().__init__()
self.opt = opt
kw = 4
... |
def compute_embedding(backbone, data_loader):
device = next(backbone.parameters()).device
embs_l = []
imgs_l = []
labels = []
for (img, y) in data_loader:
img = img.to(device)
embs_l.append(backbone(img).detach().cpu())
imgs_l.append(((img * 0.224) + 0.45).cpu())
labe... |
def test_deterministic_tensorflow():
deterministic.set_seed(0)
with tf.compat.v1.Session() as sess:
rand_tensor = sess.run(tf.random.uniform((5, 5), seed=0))
deterministic_tensor = np.array([[0., 0.9701668, 0.8487642, 0., 0.], [0., 0.844468, 0., 0.5099584, 0.6552025], [0.9881507, 0., 0., 0., 0.], [0... |
(autouse=True, name='remove')
def _remove(monkeypatch: MonkeyPatch, logging_side_effect: Callable) -> MagicMock:
mock = MagicMock(side_effect=logging_side_effect('os.remove'))
monkeypatch.setattr(os, 'remove', mock)
return mock |
class RandomSpectralKernel(AbstractSpectralKernel):
def __init__(self, measure, manifold):
super().__init__(measure, manifold)
manifold.generate_lb_eigenspaces(measure)
point = self.manifold.rand()
self.normalizer = self.forward(point, point, normalize=False)[(0, 0)]
def compute_... |
def tensor_to_pil(tensor_imgs):
if (type(tensor_imgs) == list):
tensor_imgs = torch.cat(tensor_imgs)
tensor_imgs = ((tensor_imgs / 2) + 0.5).clamp(0, 1)
to_pil = T.ToPILImage()
pil_imgs = [to_pil(img) for img in tensor_imgs]
return pil_imgs |
def train(dst_path):
((x_train, y_train), (x_test, y_test)) = tf.keras.datasets.cifar10.load_data()
input_shape = x_train.shape[1:]
x_train = (x_train.astype('float32') / 255)
x_test = (x_test.astype('float32') / 255)
x_train_mean = np.mean(x_train, axis=0)
x_train -= x_train_mean
x_test -= ... |
_task('audio_pretraining')
class AudioPretrainingTask(FairseqTask):
def add_args(parser):
parser.add_argument('data', help='path to data directory')
parser.add_argument('--sample-rate', default=16000, type=int, help='target sample rate. audio files will be up/down sampled to this rate')
pars... |
class TinyDiscriminator(nn.Module):
def __init__(self, n_features, n_classes=1, d_hidden=128):
super(TinyDiscriminator, self).__init__()
self.n_features = n_features
self.n_classes = n_classes
self.d_hidden = d_hidden
self.l1 = nn.Linear(n_features, d_hidden)
self.l2 ... |
class ClicEdmSingleGammaHitsPf(tfds.core.GeneratorBasedBuilder):
VERSION = tfds.core.Version('1.5.0')
RELEASE_NOTES = {'1.1.0': 'Remove track referencepoint feature', '1.2.0': 'Keep all interacting genparticles', '1.5.0': 'Regenerate with ARRAY_RECORD'}
MANUAL_DOWNLOAD_INSTRUCTIONS = '\n For the raw inpu... |
def main(_run, ds_name, train_test_split, verbose, gpu, sanity_dim, scaling, tfms, clf, grid_search, rescaling, disintegrations, num_augments, augment_out, num_projections, projection_channels, window, depth, sig_tfm, normalisation, save_best_model):
try:
_run.save_dir = '{}/{}'.format(save_dir, _run._id)
... |
class TFFunnelBaseModel():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
def extract_spatial_feats(feat_dir, out_dir):
info_json_path = os.path.join(feat_dir, 'gqa_spatial_info.json')
info_dict = json.load(open(info_json_path, 'r'))
file_mapping = {k: [] for k in range(16)}
for (k, v) in info_dict.items():
file_mapping[v['file']] += [(k, v)]
for i in range(16):
... |
def _import_file(module_name, file_path, make_importable=False):
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
if make_importable:
sys.modules[module_name] = module
return module |
def main():
(args, config) = parse_args_and_config()
log_progress = open(os.path.join(args.log, 'log_progress'), 'w')
sys.stdout = log_progress
logging.info('Config =')
print(('>' * 80))
print(config)
print(('<' * 80))
try:
runner = eval(args.runner)(args, config)
runner.... |
def get_model_modules():
_ignore_modules = ['modeling_auto', 'modeling_encoder_decoder', 'modeling_marian', 'modeling_mmbt', 'modeling_outputs', 'modeling_retribert', 'modeling_utils', 'modeling_flax_auto', 'modeling_flax_encoder_decoder', 'modeling_flax_utils', 'modeling_speech_encoder_decoder', 'modeling_flax_vis... |
class SEWDConfig(PretrainedConfig):
model_type = 'sew-d'
def __init__(self, vocab_size=32, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, squeeze_factor=2, max_position_embeddings=512, position_buckets=256, share_att_key=True, relative_attention=True, pos_att_type=('p2c',... |
def read_image_list_file(image_list_file):
with open(image_list_file, 'r') as f:
for line in f:
(yield line.strip().replace('.jpg', '')) |
def cli_main():
parser = make_parser()
args = options.parse_args_and_arch(parser)
main(args) |
def train():
logging.info('Training phase.')
rng = np.random.RandomState(FLAGS.seed)
n_completed_steps = get_number_of_already_completed_steps(FLAGS.logdir)
t_train = build_graph(TRAIN, rng=util.new_rng(rng), n_epochs=FLAGS.epochs, n_completed_steps=n_completed_steps)
logging.info(f'Number of traina... |
def load_topset(topset_path) -> Dict[(str, OpConfig)]:
conf = OmegaConf.load(topset_path)['topset']
ret = {}
for (k, v) in conf.items():
ret[k] = OpConfig(in_dtypes=[tuple([DType[t] for t in dtypes]) for dtypes in v['in_dtypes']], out_dtypes=[tuple([DType[t] for t in dtypes]) for dtypes in v['out_dt... |
def main(config='config/blendcnn/mrpc/eval.json', args=None):
cfg = Config(**json.load(open(config, 'r')))
cfg_data = data.Config(**json.load(open(cfg.cfg_data, 'r')))
cfg_model = models.Config(**json.load(open(cfg.cfg_model, 'r')))
cfg_optim = trainer.Config(**json.load(open(cfg.cfg_optim, 'r')))
s... |
class FGSM(Attacker):
def __init__(self, eps=0.15, clip_max=0.5, clip_min=(- 0.5)):
super(FGSM, self).__init__(clip_max, clip_min)
self.eps = eps
def perturb(self, model, x, y):
model.eval()
nx = torch.unsqueeze(x, 0)
ny = torch.unsqueeze(y, 0)
nx.requires_grad_()... |
def vat(network, x, eps_list, xi=10, Ip=1):
with torch.no_grad():
y = network(x)
d = torch.randn((x.size()[0], x.size()[1]))
d = F.normalize(d, p=2, dim=1)
for ip in range(Ip):
d_var = d
d_var = d_var.to(x.device)
d_var.requires_grad_(True)
y_p = network((x + ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.