code stringlengths 17 6.64M |
|---|
def tta_backward(x_aug):
'\n Inverts `tta_forward` and averages the 8 images.\n\n Parameters\n ----------\n x_aug: stack of 8-fold augmented images.\n\n Returns\n -------\n average of de-augmented x_aug.\n '
x_deaug = [x_aug[0], np.rot90(x_aug[1], (- 1)), np.rot90(x_aug[2], (- 2)), np.... |
def test_tifffile():
current = Path(__file__)
image_lzw = Path(current.parent, 'test_data/flybrain_lzw.tiff')
image = tifffile.imread(image_lzw)
assert (image.shape == (256, 256, 3))
|
def _int64_feature(value):
if (not isinstance(value, Iterable)):
value = [value]
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
|
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
|
def dump(fn_root, tfrecord_dir, max_res, expected_images, shards, write):
'Main converter function.'
resolution_log2 = int(np.log2(max_res))
tfr_prefix = os.path.join(tfrecord_dir, os.path.basename(tfrecord_dir))
print('Checking in', fn_root)
img_fn_list = os.listdir(fn_root)
img_fn_list = [im... |
def parse_tfrecord_tf(record, res, rnd_crop):
features = tf.parse_single_example(record, features={'shape': tf.FixedLenFeature([3], tf.int64), 'data': tf.FixedLenFeature([], tf.string), 'label': tf.FixedLenFeature([1], tf.int64)})
(data, label, shape) = (features['data'], features['label'], features['shape'])... |
def input_fn(tfr_file, shards, rank, pmap, fmap, n_batch, resolution, rnd_crop, is_training):
files = tf.data.Dataset.list_files(tfr_file)
if (('lsun' not in tfr_file) or is_training):
files = files.shard(shards, rank)
if is_training:
files = files.shuffle(buffer_size=_FILES_SHUFFLE)
d... |
def get_tfr_file(data_dir, split, res_lg2):
data_dir = os.path.join(data_dir, split)
tfr_prefix = os.path.join(data_dir, os.path.basename(data_dir))
tfr_file = (tfr_prefix + ('-r%02d-s-*-of-*.tfrecords' % res_lg2))
files = glob.glob(tfr_file)
assert (len(files) == int(files[0].split('-')[(- 1)].sp... |
def get_data(sess, data_dir, shards, rank, pmap, fmap, n_batch_train, n_batch_test, n_batch_init, resolution, rnd_crop):
assert (resolution == (2 ** int(np.log2(resolution))))
train_file = get_tfr_file(data_dir, 'train', int(np.log2(resolution)))
valid_file = get_tfr_file(data_dir, 'validation', int(np.lo... |
def make_batch(sess, itr, itr_batch_size, required_batch_size):
(ib, rb) = (itr_batch_size, required_batch_size)
k = int(np.ceil((rb / ib)))
(xs, ys) = ([], [])
data = itr.get_next()
for i in range(k):
(x, y) = sess.run(data)
xs.append(x)
ys.append(y)
(x, y) = (np.conca... |
def downsample(x, resolution):
assert (x.dtype == np.float32)
assert ((x.shape[1] % resolution) == 0)
assert ((x.shape[2] % resolution) == 0)
if (x.shape[1] == x.shape[2] == resolution):
return x
s = x.shape
x = np.reshape(x, [s[0], resolution, (s[1] // resolution), resolution, (s[2] /... |
def x_to_uint8(x):
x = np.clip(np.floor(x), 0, 255)
return x.astype(np.uint8)
|
def shard(data, shards, rank):
(x, y) = data
assert (x.shape[0] == y.shape[0])
assert ((x.shape[0] % shards) == 0)
assert (0 <= rank < shards)
size = (x.shape[0] // shards)
ind = (rank * size)
return (x[ind:(ind + size)], y[ind:(ind + size)])
|
def get_data(problem, shards, rank, data_augmentation_level, n_batch_train, n_batch_test, n_batch_init, resolution):
if (problem == 'mnist'):
from keras.datasets import mnist
((x_train, y_train), (x_test, y_test)) = mnist.load_data()
y_train = np.reshape(y_train, [(- 1)])
y_test = ... |
def make_batch(iterator, iterator_batch_size, required_batch_size):
(ib, rb) = (iterator_batch_size, required_batch_size)
k = int(np.ceil((rb / ib)))
(xs, ys) = ([], [])
for i in range(k):
(x, y) = iterator()
xs.append(x)
ys.append(y)
(x, y) = (np.concatenate(xs)[:rb], np.c... |
def gradients_speed(ys, xs, grad_ys=None, **kwargs):
return gradients(ys, xs, grad_ys, checkpoints='speed', **kwargs)
|
def gradients_memory(ys, xs, grad_ys=None, **kwargs):
return gradients(ys, xs, grad_ys, checkpoints='memory', **kwargs)
|
def gradients_collection(ys, xs, grad_ys=None, **kwargs):
return gradients(ys, xs, grad_ys, checkpoints='collection', **kwargs)
|
def gradients(ys, xs, grad_ys=None, checkpoints='collection', **kwargs):
'\n Authors: Tim Salimans & Yaroslav Bulatov\n\n memory efficient gradient implementation inspired by "Training Deep Nets with Sublinear Memory Cost"\n by Chen et al. 2016 (https://arxiv.org/abs/1604.06174)\n\n ys,xs,grad_ys,kwar... |
def tf_toposort(ts, within_ops=None):
all_ops = ge.get_forward_walk_ops([x.op for x in ts], within_ops=within_ops)
deps = {}
for op in all_ops:
for o in op.outputs:
deps[o] = set(op.inputs)
sorted_ts = toposort(deps)
ts_sorted_lists = []
for l in sorted_ts:
keep = l... |
def fast_backward_ops(within_ops, seed_ops, stop_at_ts):
bwd_ops = set(ge.get_backward_walk_ops(seed_ops, stop_at_ts=stop_at_ts))
ops = bwd_ops.intersection(within_ops).difference([t.op for t in stop_at_ts])
return list(ops)
|
@contextlib.contextmanager
def capture_ops():
'Decorator to capture ops created in the block.\n with capture_ops() as ops:\n # create some ops\n print(ops) # => prints ops created.\n '
micros = int((time.time() * (10 ** 6)))
scope_name = str(micros)
op_list = []
with tf.name_scope(sc... |
def _to_op(tensor_or_op):
if hasattr(tensor_or_op, 'op'):
return tensor_or_op.op
return tensor_or_op
|
def _to_ops(iterable):
if (not _is_iterable(iterable)):
return iterable
return [_to_op(i) for i in iterable]
|
def _is_iterable(o):
try:
_ = iter(o)
except Exception:
return False
return True
|
def debug_print(s, *args):
'Like logger.log, but also replaces all TensorFlow ops/tensors with their\n names. Sensitive to value of DEBUG_LOGGING, see enable_debug/disable_debug\n\n Usage:\n debug_print("see tensors %s for %s", tensorlist, [1,2,3])\n '
if DEBUG_LOGGING:
formatted_args = ... |
def format_ops(ops, sort_outputs=True):
'Helper method for printing ops. Converts Tensor/Operation op to op.name,\n rest to str(op).'
if (hasattr(ops, '__iter__') and (not isinstance(ops, str))):
l = [(op.name if hasattr(op, 'name') else str(op)) for op in ops]
if sort_outputs:
... |
def my_add_control_inputs(wait_to_do_ops, inputs_to_do_before):
for op in wait_to_do_ops:
ci = [i for i in inputs_to_do_before if ((op.control_inputs is None) or (i not in op.control_inputs))]
ge.add_control_inputs(op, ci)
|
def polyak(params, beta):
ema = tf.train.ExponentialMovingAverage(decay=beta, zero_debias=True)
avg_op = tf.group(ema.apply(params))
updates = []
for i in range(len(params)):
p = params[i]
avg = ema.average(p)
tmp = (0.0 + (avg * 1.0))
with tf.control_dependencies([tmp]... |
def adam(params, cost_or_grads, alpha=0.0003, hps=None, epsilon=1e-08):
updates = []
if (type(cost_or_grads) is not list):
gs = tf.gradients(cost_or_grads, params)
else:
gs = cost_or_grads
beta2 = (1 - (1.0 / (hps.train_its * hps.polyak_epochs)))
grads = [Z.allreduce_mean(g) for g ... |
def adam2(params, cost_or_grads, alpha=0.0003, hps=None, epsilon=1e-08):
updates = []
if (type(cost_or_grads) is not list):
gs = tf.gradients(cost_or_grads, params)
else:
gs = cost_or_grads
beta2 = (1 - (1.0 / (hps.train_its * hps.polyak_epochs)))
grads1 = [Z.allreduce_mean(g) for ... |
def adam2_old(params, cost_or_grads, lr=0.0003, mom1=0.9, mom2=0.999, epsilon=1e-08):
updates = []
if (type(cost_or_grads) is not list):
gs = tf.gradients(cost_or_grads, params)
else:
gs = cost_or_grads
grads1 = [Z.allreduce_mean(g) for g in gs]
grads2 = [Z.allreduce_mean(tf.square... |
def adamax(params, cost_or_grads, alpha=0.0003, hps=None, epsilon=1e-08):
updates = []
if (type(cost_or_grads) is not list):
gs = tf.gradients(cost_or_grads, params)
else:
gs = cost_or_grads
beta2 = (1 - (1.0 / (hps.train_its * hps.polyak_epochs)))
grads = [Z.allreduce_mean(g) for ... |
def _print(*args, **kwargs):
if (hvd.rank() == 0):
print(*args, **kwargs)
|
def init_visualizations(hps, model, logdir):
def sample_batch(y, eps):
n_batch = hps.local_batch_train
xs = []
for i in range(int(np.ceil((len(eps) / n_batch)))):
xs.append(model.sample(y[(i * n_batch):((i * n_batch) + n_batch)], eps[(i * n_batch):((i * n_batch) + n_batch)]))
... |
def get_data(hps, sess):
if (hps.image_size == (- 1)):
hps.image_size = {'mnist': 32, 'cifar10': 32, 'imagenet-oord': 64, 'imagenet': 256, 'celeba': 256, 'lsun_realnvp': 64, 'lsun': 256}[hps.problem]
if (hps.n_test == (- 1)):
hps.n_test = {'mnist': 10000, 'cifar10': 10000, 'imagenet-oord': 500... |
def process_results(results):
stats = ['loss', 'bits_x', 'bits_y', 'pred_loss']
assert (len(stats) == results.shape[0])
res_dict = {}
for i in range(len(stats)):
res_dict[stats[i]] = '{:.4f}'.format(results[i])
return res_dict
|
def main(hps):
hvd.init()
sess = tensorflow_session()
tf.set_random_seed((hvd.rank() + (hvd.size() * hps.seed)))
np.random.seed((hvd.rank() + (hvd.size() * hps.seed)))
(train_iterator, test_iterator, data_init) = get_data(hps, sess)
(hps.train_its, hps.test_its, hps.full_test_its) = get_its(hp... |
def infer(sess, model, hps, iterator):
if hps.direct_iterator:
iterator = iterator.get_next()
print('Running inference on {} data points'.format((hps.full_test_its * hps.n_batch_test)))
logpz = []
grad_logpz = []
for it in range(hps.full_test_its):
if hps.direct_iterator:
... |
def train(sess, model, hps, logdir, visualise):
_print(hps)
_print('Starting training. Logging to', logdir)
_print('epoch n_processed n_images ips dtrain dtest dsample dtot train_results test_results msg')
sess.graph.finalize()
n_processed = 0
n_images = 0
train_time = 0.0
test_loss_be... |
def get_its(hps):
train_its = int(np.ceil((hps.n_train / (hps.n_batch_train * hvd.size()))))
test_its = int(np.ceil((hps.n_test / (hps.n_batch_train * hvd.size()))))
train_epoch = ((train_its * hps.n_batch_train) * hvd.size())
if (hvd.rank() == 0):
print(hps.n_test, hps.local_batch_test, hvd.s... |
def tensorflow_session():
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.visible_device_list = str(hvd.local_rank())
sess = tf.Session(config=config)
return sess
|
class ResultLogger(object):
def __init__(self, path, *args, **kwargs):
self.f_log = open(path, 'w')
self.f_log.write((json.dumps(kwargs) + '\n'))
def log(self, **kwargs):
self.f_log.write((json.dumps(kwargs) + '\n'))
self.f_log.flush()
def close(self):
self.f_log... |
def gen_bar_updater():
pbar = tqdm(total=None)
def bar_update(count, block_size, total_size):
if ((pbar.total is None) and total_size):
pbar.total = total_size
progress_bytes = (count * block_size)
pbar.update((progress_bytes - pbar.n))
return bar_update
|
def check_integrity(fpath, md5=None):
if (md5 is None):
return True
if (not os.path.isfile(fpath)):
return False
md5o = hashlib.md5()
with open(fpath, 'rb') as f:
for chunk in iter((lambda : f.read((1024 * 1024))), b''):
md5o.update(chunk)
md5c = md5o.hexdigest(... |
def makedir_exist_ok(dirpath):
'\n Python2 support for os.makedirs(.., exist_ok=True)\n '
try:
os.makedirs(dirpath)
except OSError as e:
if (e.errno == errno.EEXIST):
pass
else:
raise
|
def download_url(url, root, filename=None, md5=None):
'Download a file from a url and place it in root.\n\n Args:\n url (str): URL to download file from\n root (str): Directory to place downloaded file in\n filename (str, optional): Name to save the file under. If None, use the basename of... |
def list_dir(root, prefix=False):
'List all directories at a given root\n\n Args:\n root (str): Path to directory whose folders need to be listed\n prefix (bool, optional): If true, prepends the path to each result, otherwise\n only returns the name of the directories found\n '
... |
def list_files(root, suffix, prefix=False):
'List all files ending with a suffix at a given root\n\n Args:\n root (str): Path to directory whose folders need to be listed\n suffix (str or tuple): Suffix of the files to match, e.g. \'.png\' or (\'.jpg\', \'.png\').\n It uses the Python ... |
def download_file_from_google_drive(file_id, root, filename=None, md5=None):
'Download a Google Drive file from and place it in root.\n\n Args:\n file_id (str): id of file to be downloaded\n root (str): Directory to place downloaded file in\n filename (str, optional): Name to save the fil... |
def _get_confirm_token(response):
for (key, value) in response.cookies.items():
if key.startswith('download_warning'):
return value
return None
|
def _save_response_content(response, destination, chunk_size=32768):
with open(destination, 'wb') as f:
pbar = tqdm(total=None)
progress = 0
for chunk in response.iter_content(chunk_size):
if chunk:
f.write(chunk)
progress += len(chunk)
... |
class VisionDataset(data.Dataset):
_repr_indent = 4
def __init__(self, root):
if isinstance(root, torch._six.string_classes):
root = os.path.expanduser(root)
self.root = root
def __getitem__(self, index):
raise NotImplementedError
def __len__(self):
raise... |
def dsm(energy_net, samples, sigma=1):
samples.requires_grad_(True)
vector = (torch.randn_like(samples) * sigma)
perturbed_inputs = (samples + vector)
logp = (- energy_net(perturbed_inputs))
dlogp = ((sigma ** 2) * autograd.grad(logp.sum(), perturbed_inputs, create_graph=True)[0])
kernel = vec... |
def dsm_score_estimation(scorenet, samples, sigma=0.01):
perturbed_samples = (samples + (torch.randn_like(samples) * sigma))
target = (((- 1) / (sigma ** 2)) * (perturbed_samples - samples))
scores = scorenet(perturbed_samples)
target = target.view(target.shape[0], (- 1))
scores = scores.view(scor... |
def anneal_dsm_score_estimation(scorenet, samples, labels, sigmas, anneal_power=2.0):
used_sigmas = sigmas[labels].view(samples.shape[0], *([1] * len(samples.shape[1:])))
perturbed_samples = (samples + (torch.randn_like(samples) * used_sigmas))
target = (((- 1) / (used_sigmas ** 2)) * (perturbed_samples -... |
def single_sliced_score_matching(energy_net, samples, noise=None, detach=False, noise_type='radermacher'):
samples.requires_grad_(True)
if (noise is None):
vectors = torch.randn_like(samples)
if (noise_type == 'radermacher'):
vectors = vectors.sign()
elif (noise_type == 'sp... |
def partial_sliced_score_matching(energy_net, samples, noise=None, detach=False, noise_type='radermacher'):
samples.requires_grad_(True)
if (noise is None):
vectors = torch.randn_like(samples)
if (noise_type == 'radermacher'):
vectors = vectors.sign()
elif (noise_type == 'g... |
def sliced_score_matching(energy_net, samples, n_particles=1):
dup_samples = samples.unsqueeze(0).expand(n_particles, *samples.shape).contiguous().view((- 1), *samples.shape[1:])
dup_samples.requires_grad_(True)
vectors = torch.randn_like(dup_samples)
vectors = (vectors / torch.norm(vectors, dim=(- 1)... |
def sliced_score_matching_vr(energy_net, samples, n_particles=1):
dup_samples = samples.unsqueeze(0).expand(n_particles, *samples.shape).contiguous().view((- 1), *samples.shape[1:])
dup_samples.requires_grad_(True)
vectors = torch.randn_like(dup_samples)
logp = (- energy_net(dup_samples).sum())
gr... |
def sliced_score_estimation(score_net, samples, n_particles=1):
dup_samples = samples.unsqueeze(0).expand(n_particles, *samples.shape).contiguous().view((- 1), *samples.shape[1:])
dup_samples.requires_grad_(True)
vectors = torch.randn_like(dup_samples)
vectors = (vectors / torch.norm(vectors, dim=(- 1... |
def sliced_score_estimation_vr(score_net, samples, n_particles=1):
'\n Be careful if the shape of samples is not B x x_dim!!!!\n '
dup_samples = samples.unsqueeze(0).expand(n_particles, *samples.shape).contiguous().view((- 1), *samples.shape[1:])
dup_samples.requires_grad_(True)
vectors = torch.... |
def anneal_sliced_score_estimation_vr(scorenet, samples, labels, sigmas, n_particles=1):
used_sigmas = sigmas[labels].view(samples.shape[0], *([1] * len(samples.shape[1:])))
perturbed_samples = (samples + (torch.randn_like(samples) * used_sigmas))
dup_samples = perturbed_samples.unsqueeze(0).expand(n_part... |
def parse_args_and_config():
parser = argparse.ArgumentParser(description=globals()['__doc__'])
parser.add_argument('--runner', type=str, default='AnnealRunner', help='The runner to execute')
parser.add_argument('--config', type=str, default='anneal.yml', help='Path to the config file')
parser.add_arg... |
def dict2namespace(config):
namespace = argparse.Namespace()
for (key, value) in config.items():
if isinstance(value, dict):
new_value = dict2namespace(value)
else:
new_value = value
setattr(namespace, key, new_value)
return namespace
|
def main():
(args, config) = parse_args_and_config()
logging.info('Writing log file to {}'.format(args.log))
logging.info('Exp instance id = {}'.format(os.getpid()))
logging.info('Exp comment = {}'.format(args.comment))
logging.info('Config =')
print(('>' * 80))
print(config)
print(('<... |
class InceptionV3(nn.Module):
'Pretrained InceptionV3 network returning feature maps'
DEFAULT_BLOCK_INDEX = 3
BLOCK_INDEX_BY_DIM = {64: 0, 192: 1, 768: 2, 2048: 3}
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False):
'Build pre... |
def get_norm_layer(norm_type='instance'):
'Return a normalization layer\n\n Parameters:\n norm_type (str) -- the name of the normalization layer: batch | instance | none\n\n For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).\n For InstanceNorm, we do not ... |
def get_scheduler(optimizer, opt):
"Return a learning rate scheduler\n\n Parameters:\n optimizer -- the optimizer of the network\n opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions.\u3000\n opt.lr_policy is the name ... |
def init_weights(net, init_type='normal', init_gain=0.02):
"Initialize network weights.\n\n Parameters:\n net (network) -- network to be initialized\n init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal\n init_gain (float) -- scaling factor ... |
def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]):
'Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights\n Parameters:\n net (network) -- the network to be initialized\n init_type (str) -- the name of an initializatio... |
def define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]):
"Create a generator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n ngf (... |
def define_D(input_nc, ndf, netD, n_layers_D=3, norm='batch', init_type='normal', init_gain=0.02, gpu_ids=[]):
"Create a discriminator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n ndf (int) -- the number of filters in the first conv layer\n netD... |
class GANLoss(nn.Module):
'Define different GAN objectives.\n\n The GANLoss class abstracts away the need to create the target label tensor\n that has the same size as the input.\n '
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
' Initialize the GANLoss class.\n... |
def cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0):
"Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028\n\n Arguments:\n netD (network) -- discriminator network\n real_data (tensor array) ... |
class ResnetGenerator(nn.Module):
"Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.\n\n We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)\n "
def __init__(self, input_nc... |
class ResnetBlock(nn.Module):
'Define a Resnet block'
def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):
'Initialize the Resnet block\n\n A resnet block is a conv block with skip connections\n We construct a conv block with build_conv_block function,\n and ... |
class UnetGenerator(nn.Module):
'Create a Unet-based generator'
def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False):
'Construct a Unet generator\n Parameters:\n input_nc (int) -- the number of channels in input images\n ... |
class UnetSkipConnectionBlockWithResNet(nn.Module):
'Defines the Unet submodule with skip connection.\n X -------------------identity----------------------\n |-- downsampling -- |submodule| -- upsampling --|\n '
def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=... |
class UnetSkipConnectionBlock(nn.Module):
'Defines the Unet submodule with skip connection.\n X -------------------identity----------------------\n |-- downsampling -- |submodule| -- upsampling --|\n '
def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=False, inn... |
class NLayerDiscriminator(nn.Module):
'Defines a PatchGAN discriminator'
def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):
'Construct a PatchGAN discriminator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n ndf (int... |
class PixelDiscriminator(nn.Module):
'Defines a 1x1 PatchGAN discriminator (pixelGAN)'
def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d):
'Construct a 1x1 PatchGAN discriminator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n nd... |
class ConvResBlock(nn.Module):
def __init__(self, in_channel, out_channel, resize=False, act='relu'):
super().__init__()
self.resize = resize
def get_act():
if (act == 'relu'):
return nn.ReLU(inplace=True)
elif (act == 'softplus'):
... |
class DeconvResBlock(nn.Module):
def __init__(self, in_channel, out_channel, resize=False, act='relu'):
super().__init__()
self.resize = resize
def get_act():
if (act == 'relu'):
return nn.ReLU(inplace=True)
elif (act == 'softplus'):
... |
class ResScore(nn.Module):
def __init__(self, config):
super().__init__()
self.nef = config.model.nef
self.ndf = config.model.ndf
act = 'elu'
self.convs = nn.Sequential(nn.Conv2d(3, self.nef, 3, 1, 1), ConvResBlock(self.nef, self.nef, act=act), ConvResBlock(self.nef, (2 * ... |
class ResNetScore(nn.Module):
"Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.\n\n We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)\n "
def __init__(self, config):
... |
class UNetResScore(nn.Module):
def __init__(self, config):
'Construct a Unet generator\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n num_downs (int) -- the number of downsamp... |
class UNetScore(nn.Module):
def __init__(self, config):
'Construct a Unet generator\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n num_downs (int) -- the number of downsamplin... |
class ResEnergy(nn.Module):
def __init__(self, config):
super().__init__()
self.nef = config.model.nef
self.ndf = config.model.ndf
act = 'softplus'
self.convs = nn.Sequential(nn.Conv2d(1, self.nef, 3, 1, 1), ConvResBlock(self.nef, self.nef, act=act), ConvResBlock(self.nef,... |
class MLPScore(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.main = nn.Sequential(nn.Linear((10 * 10), 1024), nn.LayerNorm(1024), nn.ELU(), nn.Linear(1024, 1024), nn.LayerNorm(1024), nn.ELU(), nn.Linear(1024, 512), nn.LayerNorm(512), nn.ELU(), nn.Lin... |
class LargeScore(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
nef = config.model.nef
self.u_net = nn.Sequential(nn.Conv2d(config.data.channels, nef, 16, stride=2, padding=2), nn.GroupNorm(4, nef), nn.ELU(), nn.Conv2d(nef, (nef * 2), 4, stride=2, ... |
class Score(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
nef = config.model.nef
self.u_net = nn.Sequential(nn.Conv2d(config.data.channels, nef, 4, stride=2, padding=1), nn.GroupNorm(4, nef), nn.ELU(), nn.Conv2d(nef, (nef * 2), 4, stride=2, paddin... |
class SmallScore(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
nef = (config.model.nef * 4)
self.u_net = nn.Sequential(nn.Conv2d(config.data.channels, nef, 4, stride=2, padding=1), nn.GroupNorm(4, nef), nn.ELU(), nn.Conv2d(nef, (nef * 2), 3, strid... |
class BaselineRunner():
def __init__(self, args, config):
self.args = args
self.config = config
def get_optimizer(self, parameters):
if (self.config.optim.optimizer == 'Adam'):
return optim.Adam(parameters, lr=self.config.optim.lr, weight_decay=self.config.optim.weight_de... |
class ScoreNetRunner():
def __init__(self, args, config):
self.args = args
self.config = config
def get_optimizer(self, parameters):
if (self.config.optim.optimizer == 'Adam'):
return optim.Adam(parameters, lr=self.config.optim.lr, weight_decay=self.config.optim.weight_de... |
class OnlineEvaluator(Callback):
'Attaches a classifier to evaluate a specific representation from the model during training.\n\n Args:\n optimizer: Config to instantiate an optimizer and optionally a scheduler.\n classifier: Config to instantiate a classifier.\n input_name: Name of the re... |
class BaseDataModule(LightningDataModule, ABC):
"Abstract class that inherits from LightningDataModule to follow standardized preprocessing for all\n datamodules in eztorch.\n\n Args:\n datadir: Where to save/load the data.\n train: Configuration for the training data to define the loading of ... |
class CIFARDataModule(BaseDataModule, ABC):
'Base datamodule for the CIFAR datasets.\n\n Args:\n datadir: Where to save/load the data.\n train: Configuration for the training data to define the loading of data, the transforms and the dataloader.\n val: Configuration for the validation data... |
class CIFAR10DataModule(CIFARDataModule):
'Datamodule for the CIFAR10 dataset.\n\n Args:\n datadir: Where to save/load the data.\n train: Configuration for the training data to define the loading of data, the transforms and the dataloader.\n val: Configuration for the validation data to de... |
class CIFAR100DataModule(CIFARDataModule):
'Datamodule for the CIFAR100 dataset.\n\n Args:\n datadir: Where to save/load the data.\n train: Configuration for the training data to define the loading of data, the transforms and the dataloader.\n val: Configuration for the validation data to ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.