code stringlengths 17 6.64M |
|---|
class DiceLoss(nn.Module):
def __init__(self, smooth=0.001, p=2, reduction='mean'):
super(DiceLoss, self).__init__()
self.smooth = smooth
self.p = p
self.reduction = reduction
def forward(self, predict, target):
assert (predict.shape[0] == target.shape[0]), "predict &... |
def pairwise_distance(x1, x2, p=2, eps=1e-06):
'\n Computes the batchwise pairwise distance between vectors v1,v2:\n .. math ::\n \\Vert x \\Vert _p := \\left( \\sum_{i=1}^n \\vert x_i \\vert ^ p \\right) ^ {1/p}\n Args:\n x1: first input tensor\n x2: second inpu... |
def triplet_margin_loss_gor_one(anchor, positive, negative, beta=1.0, margin=1.0, p=2, eps=1e-06, swap=False):
assert (anchor.size() == positive.size()), 'Input sizes between positive and negative must be equal.'
assert (anchor.size() == negative.size()), 'Input sizes between anchor and negative must be equal... |
def triplet_margin_loss_gor(anchor, positive, negative1, negative2, beta=1.0, margin=1.0, p=2, eps=1e-06, swap=False):
assert (anchor.size() == positive.size()), 'Input sizes between positive and negative must be equal.'
assert (anchor.size() == negative1.size()), 'Input sizes between anchor and negative must... |
def distance_matrix_vector(anchor, positive):
'Given batch of anchor descriptors and positive descriptors calculate distance matrix'
D = anchor.shape[(- 1)]
d1_sq = torch.sum((anchor * anchor), dim=1).unsqueeze((- 1))
d2_sq = torch.sum((positive * positive), dim=1).unsqueeze((- 1))
eps = 0.001
... |
def percentile(t, q):
'\n Return the ``q``-th percentile of the flattened input tensor\'s data.\n\n CAUTION:\n * Needs PyTorch >= 1.1.0, as ``torch.kthvalue()`` is used.\n * Values are not interpolated, which corresponds to\n ``numpy.percentile(..., interpolation="nearest")``.\n\n :param t:... |
def sos_reg(anchor, positive, KNN=True, k=1, eps=1e-08):
dist_matrix_a = (distance_matrix_vector(anchor, anchor) + eps)
dist_matrix_b = (distance_matrix_vector(positive, positive) + eps)
if KNN:
k_max = percentile(dist_matrix_b, k)
mask = dist_matrix_b.lt(k_max)
dist_matrix_a = (di... |
def _mix_rbf_kernel(X, Y, sigmas=[1.0], wts=None):
if (wts is None):
wts = ([1] * len(sigmas))
XX = tf.matmul(X, X, transpose_b=True)
XY = tf.matmul(X, Y, transpose_b=True)
YY = tf.matmul(Y, Y, transpose_b=True)
X_sqnorms = tf.diag_part(XX)
Y_sqnorms = tf.diag_part(YY)
r = (lambda ... |
def _mmd2(K_XX, K_XY, K_YY, const_diagonal=False, biased=False):
m = tf.cast(tf.shape(K_XX)[0], tf.float32)
n = tf.cast(tf.shape(K_YY)[0], tf.float32)
if biased:
mmd2 = (((tf.reduce_sum(K_XX, keep_dims=True) / (m * m)) + (tf.reduce_sum(K_YY, keep_dims=True) / (n * n))) - ((2 * tf.reduce_sum(K_XY, ... |
def mix_rbf_mmd2(X, Y, sigmas=[1.0], wts=None, biased=True):
(K_XX, K_XY, K_YY, d) = _mix_rbf_kernel(X, Y, sigmas, wts)
return _mmd2(K_XX, K_XY, K_YY, const_diagonal=d, biased=biased)
|
def rbf_mmd2(X, Y, sigma=1.0, biased=True):
return mix_rbf_mmd2(X, Y, sigmas=[sigma], biased=biased)
|
class Max_over_time(Layer):
def __init__(self, **kwargs):
self.supports_masking = True
super(Max_over_time, self).__init__(**kwargs)
def call(self, x, mask=None):
if (mask is not None):
mask = K.cast(mask, K.floatx())
mask = K.expand_dims(mask)
x =... |
class KL_loss(Layer):
def __init__(self, batch_size, **kwargs):
super(KL_loss, self).__init__(**kwargs)
self.batch_size = batch_size
def call(self, x, mask=None):
a = x[0]
b = x[1]
a = K.mean(a, axis=0, keepdims=True)
b = K.mean(b, axis=0, keepdims=True)
... |
class mmd_loss(Layer):
def __init__(self, batch_size, **kwargs):
super(mmd_loss, self).__init__(**kwargs)
self.batch_size = batch_size
def call(self, x, mask=None):
a = x[0]
b = x[1]
mmd = rbf_mmd2(a, b)
mmd = K.repeat_elements(mmd, self.batch_size, axis=0)
... |
class Ensemble_pred_loss(Layer):
def __init__(self, **kwargs):
super(Ensemble_pred_loss, self).__init__(**kwargs)
def call(self, x, mask=None):
pred = x[0]
target = x[1]
weight = x[2]
error = K.categorical_crossentropy(target, pred)
loss = (error * weight)
... |
class Conv1DWithMasking(Conv1D):
def __init__(self, **kwargs):
self.supports_masking = True
super(Conv1DWithMasking, self).__init__(**kwargs)
def compute_mask(self, x, mask):
return mask
|
def get_optimizer(args):
clipvalue = 0
clipnorm = 10
if (args.algorithm == 'rmsprop'):
optimizer = opt.RMSprop(lr=0.0005, rho=0.9, epsilon=1e-06, clipnorm=clipnorm, clipvalue=clipvalue)
elif (args.algorithm == 'sgd'):
optimizer = opt.SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False... |
def create_data(vocab, file_path, skip_top, skip_len, replace_non_vocab):
data = []
f = codecs.open(file_path, 'r', 'utf-8')
(num_hit, unk_hit, skip_top_hit, total) = (0.0, 0.0, 0.0, 0.0)
max_len = 0
for line in f:
word_indices = []
words = line.split()
if ((skip_len > 0) a... |
def prepare_data(source_domain, target_domain, n_class, vocab_size=0, skip_len=0, skip_top=0, replace_non_vocab=1):
file_list = [('../data/amazon/%s/pos.txt' % source_domain), ('../data/amazon/%s/neg.txt' % source_domain), ('../data/amazon/%s/un_pos.txt' % source_domain), ('../data/amazon/%s/un_neg.txt' % source_... |
def get_data(dataset, source_domain, target_domain, n_class, vocab_size=0):
(vocab, data_list, overall_maxlen) = prepare_data(source_domain, target_domain, n_class, vocab_size)
data_list = [sequence.pad_sequences(d, maxlen=overall_maxlen) for d in data_list]
for d in data_list:
np.random.shuffle(d... |
def train_class_batch(model, samples, target, criterion):
outputs = model(samples)
loss = criterion(outputs, target)
return (loss, outputs)
|
def get_loss_scale_for_deepspeed(model):
optimizer = model.optimizer
return (optimizer.loss_scale if hasattr(optimizer, 'loss_scale') else optimizer.cur_scale)
|
def train_one_epoch(args, model: torch.nn.Module, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, cur_single_client, max_norm: float=0, proxy_single_client=None, log_writer=None, model_ema: Optional[ModelEma]=None, mixup_fn: Optional[... |
@torch.no_grad()
def evaluate(data_loader, model, device):
criterion = torch.nn.CrossEntropyLoss()
metric_logger = misc.MetricLogger(delimiter=' ')
header = 'Test:'
model.eval()
for batch in metric_logger.log_every(data_loader, 10, header):
images = batch[0]
target = batch[(- 1)]
... |
def train_one_epoch(args, model: torch.nn.Module, d_vae: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, cur_single_client, max_norm: float=0, proxy_single_client=None, log_writer=None, criterion=None, lr_scheduler=None, start_steps=None, lr_sch... |
def get_args():
parser = argparse.ArgumentParser('Fed-BEiT pre-training', add_help=False)
parser.add_argument('--batch_size', default=64, type=int)
parser.add_argument('--save_ckpt_freq', default=50, type=int)
parser.add_argument('--discrete_vae_weight_path', default='/home/yan/data/SSL-FL/tokenizer_w... |
def get_model(args):
print(f'Creating model: {args.model}')
model = create_model(args.model, pretrained=False, drop_path_rate=args.drop_path, drop_block_rate=None, use_shared_rel_pos_bias=args.rel_pos_bias, use_abs_pos_emb=args.abs_pos_emb, init_values=args.layer_scale_init_value)
patch_size = model.patch... |
def main(args, model):
misc.init_distributed_mode(args)
print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__))))
print('{}'.format(args).replace(', ', ',\n'))
device = torch.device(args.device)
misc.fix_random_seeds(args)
cudnn.benchmark = True
os.makedirs(args.output_dir, ... |
def get_args():
parser = argparse.ArgumentParser('Fed-BEiT fine-tuning and evaluation script for image classification', add_help=False)
parser.add_argument('--batch_size', default=64, type=int)
parser.add_argument('--update_freq', default=1, type=int)
parser.add_argument('--save_ckpt_freq', default=20... |
def get_model(args):
print(f'Creating model: {args.model}')
model = create_model(args.model, pretrained=False, num_classes=args.nb_classes, drop_rate=args.drop, drop_path_rate=args.drop_path, attn_drop_rate=args.attn_drop_rate, drop_block_rate=None, use_mean_pooling=args.use_mean_pooling, init_scale=args.init... |
def main(args, model):
misc.init_distributed_mode(args)
device = torch.device(args.device)
misc.fix_random_seeds(args)
cudnn.benchmark = True
create_dataset_and_evalmetrix(args, mode='finetune')
if args.disable_eval_during_finetuning:
dataset_val = None
else:
dataset_val = ... |
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, max_norm: float=0, proxy_single_client=None, mixup_fn: Optional[Mixup]=None, log_writer=None, args=None):
model.train(True)
metric_log... |
@torch.no_grad()
def evaluate(data_loader, model, device):
criterion = torch.nn.CrossEntropyLoss()
metric_logger = misc.MetricLogger(delimiter=' ')
header = 'Test:'
model.eval()
for batch in metric_logger.log_every(data_loader, 10, header):
images = batch[0]
target = batch[(- 1)]
... |
def train_one_epoch(model: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, cur_single_client, max_norm: float=0, proxy_single_client=None, log_writer=None, args=None):
model.train(True)
metric_logger = misc.MetricLogger(delimiter=' ')
... |
def get_args():
parser = argparse.ArgumentParser('Fed-MAE fine-tuning for image classification', add_help=False)
parser.add_argument('--batch_size', default=64, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus')
parser.add_argument('--save_ckpt_freq', default=20... |
def main(args, model):
misc.init_distributed_mode(args)
device = torch.device(args.device)
misc.fix_random_seeds(args)
cudnn.benchmark = True
create_dataset_and_evalmetrix(args, mode='finetune')
if args.disable_eval_during_finetuning:
dataset_val = None
else:
dataset_val = ... |
def get_args():
parser = argparse.ArgumentParser('Fed-MAE pre-training', add_help=False)
parser.add_argument('--batch_size', default=64, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus')
parser.add_argument('--save_ckpt_freq', default=20, type=int)
parser.a... |
def main(args, model):
misc.init_distributed_mode(args)
print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__))))
print('{}'.format(args).replace(', ', ',\n'))
device = torch.device(args.device)
misc.fix_random_seeds(args)
cudnn.benchmark = True
os.makedirs(args.output_dir, ... |
def Partial_Client_Selection(args, model, mode='pretrain'):
device = torch.device(args.device)
if (args.num_local_clients == (- 1)):
args.proxy_clients = args.dis_cvs_files
args.num_local_clients = len(args.dis_cvs_files)
else:
args.proxy_clients = [('train_' + str(i)) for i in ran... |
def average_model(args, model_avg, model_all):
model_avg.cpu()
print('Calculate the model avg----')
params = dict(model_avg.named_parameters())
for (name, param) in params.items():
for client in range(len(args.proxy_clients)):
single_client = args.proxy_clients[client]
... |
class AverageMeter(object):
'Computes and stores the average and current value'
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += (val... |
def simple_accuracy(preds, labels):
return (preds == labels).mean()
|
def save_model(args, model):
model_to_save = (model.module if hasattr(model, 'module') else model)
client_name = os.path.basename(args.single_client).split('.')[0]
model_checkpoint = os.path.join(args.output_dir, ('%s_%s_checkpoint.bin' % (args.name, client_name)))
torch.save(model_to_save.state_dict(... |
def valid(args, model, data_loader):
criterion = torch.nn.CrossEntropyLoss()
metric_logger = misc.MetricLogger(delimiter=' ')
header = 'Test:'
model.eval()
print('++++++ Running Validation ++++++')
for batch in metric_logger.log_every(data_loader, 10, header):
images = batch[0]
... |
def metric_evaluation(args, eval_result):
if (args.nb_classes == 1):
if (args.best_acc[args.single_client] < eval_result):
Flag = False
else:
Flag = True
elif (args.best_acc[args.single_client] < eval_result):
Flag = True
else:
Flag = False
retur... |
class RandomResizedCrop(transforms.RandomResizedCrop):
"\n RandomResizedCrop for matching TF/TPU implementation: no for-loop is used.\n This may lead to results different with torchvision's version.\n Following BYOL's TF code:\n https://github.com/deepmind/deepmind-research/blob/master/byol/utils/data... |
@attr.s(eq=False, repr=False)
class DecoderBlock(nn.Module):
n_in: int = attr.ib(validator=(lambda i, a, x: (x >= 1)))
n_out: int = attr.ib(validator=(lambda i, a, x: ((x >= 1) and ((x % 4) == 0))))
n_layers: int = attr.ib(validator=(lambda i, a, x: (x >= 1)))
device: torch.device = attr.ib(default=No... |
@attr.s(eq=False, repr=False)
class Decoder(nn.Module):
group_count: int = 4
n_init: int = attr.ib(default=128, validator=(lambda i, a, x: (x >= 8)))
n_hid: int = attr.ib(default=256, validator=(lambda i, a, x: (x >= 64)))
n_blk_per_group: int = attr.ib(default=2, validator=(lambda i, a, x: (x >= 1)))... |
@attr.s(eq=False, repr=False)
class EncoderBlock(nn.Module):
n_in: int = attr.ib(validator=(lambda i, a, x: (x >= 1)))
n_out: int = attr.ib(validator=(lambda i, a, x: ((x >= 1) and ((x % 4) == 0))))
n_layers: int = attr.ib(validator=(lambda i, a, x: (x >= 1)))
device: torch.device = attr.ib(default=No... |
@attr.s(eq=False, repr=False)
class Encoder(nn.Module):
group_count: int = 4
n_hid: int = attr.ib(default=256, validator=(lambda i, a, x: (x >= 64)))
n_blk_per_group: int = attr.ib(default=2, validator=(lambda i, a, x: (x >= 1)))
input_channels: int = attr.ib(default=3, validator=(lambda i, a, x: (x >... |
@attr.s(eq=False)
class Conv2d(nn.Module):
n_in: int = attr.ib(validator=(lambda i, a, x: (x >= 1)))
n_out: int = attr.ib(validator=(lambda i, a, x: (x >= 1)))
kw: int = attr.ib(validator=(lambda i, a, x: ((x >= 1) and ((x % 2) == 1))))
use_float16: bool = attr.ib(default=True)
device: torch.devic... |
def map_pixels(x: torch.Tensor) -> torch.Tensor:
if (x.dtype != torch.float):
raise ValueError('expected input to have type float')
return (((1 - (2 * logit_laplace_eps)) * x) + logit_laplace_eps)
|
def unmap_pixels(x: torch.Tensor) -> torch.Tensor:
if (len(x.shape) != 4):
raise ValueError('expected input to be 4d')
if (x.dtype != torch.float):
raise ValueError('expected input to have type float')
return torch.clamp(((x - logit_laplace_eps) / (1 - (2 * logit_laplace_eps))), 0, 1)
|
class DataAugmentationForPretrain(object):
' data transformations for pre-training'
def __init__(self, args):
if (args.data_set == 'Retina'):
(mean, std) = (RETINA_MEAN, RETINA_STD)
else:
(mean, std) = ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
if (args.mod... |
def build_transform(is_train, mode, args):
' data transformations for fine-tuning'
if (args.data_set == 'Retina'):
(mean, std) = (RETINA_MEAN, RETINA_STD)
else:
(mean, std) = ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
if (mode == 'finetune'):
if is_train:
if (ar... |
class LARS(torch.optim.Optimizer):
'\n LARS optimizer, no rate scaling or weight decay for parameters <= 1D.\n '
def __init__(self, params, lr=0, weight_decay=0, momentum=0.9, trust_coefficient=0.001):
defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum, trust_coefficient=trust_... |
def param_groups_lrd(model, weight_decay=0.05, no_weight_decay_list=[], layer_decay=0.75):
'\n Parameter groups for layer-wise lr decay\n Following BEiT: https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L58\n '
param_group_names = {}
param_groups = {}
num_layers = (len(mod... |
def get_layer_id_for_vit(name, num_layers):
'\n Assign a parameter with its layer id\n Following BEiT: https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L33\n '
if (name in ['cls_token', 'pos_embed']):
return 0
elif name.startswith('patch_embed'):
return 0
e... |
def adjust_learning_rate(optimizer, epoch, args):
'Decay the learning rate with half-cycle cosine after warmup'
if (epoch < args.warmup_epochs):
lr = ((args.lr * epoch) / args.warmup_epochs)
else:
lr = (args.min_lr + (((args.lr - args.min_lr) * 0.5) * (1.0 + math.cos(((math.pi * (epoch - a... |
def fix_random_seeds(args):
'\n Fix random seeds.\n '
seed = (args.seed + get_rank())
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
|
class SmoothedValue(object):
'Track a series of values and provide access to smoothed values over a\n window or the global series average.\n '
def __init__(self, window_size=20, fmt=None):
if (fmt is None):
fmt = '{median:.4f} ({global_avg:.4f})'
self.deque = deque(maxlen=wi... |
class MetricLogger(object):
def __init__(self, delimiter='\t'):
self.meters = defaultdict(SmoothedValue)
self.delimiter = delimiter
def update(self, **kwargs):
for (k, v) in kwargs.items():
if (v is None):
continue
if isinstance(v, torch.Tensor... |
class TensorboardLogger(object):
def __init__(self, log_dir):
self.writer = SummaryWriter(logdir=log_dir)
self.step = 0
def set_step(self, step=None):
if (step is not None):
self.step = step
else:
self.step += 1
def update(self, head='scalar', ste... |
def _load_checkpoint_for_ema(model_ema, checkpoint):
'\n Workaround for ModelEma._load_checkpoint to accept an already-loaded object\n '
mem_file = io.BytesIO()
torch.save(checkpoint, mem_file)
mem_file.seek(0)
model_ema._load_checkpoint(mem_file)
|
def setup_for_distributed(is_master):
'\n This function disables printing when not in master process\n '
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop('force', False)
if (is_master or force):
builtin_p... |
def is_dist_avail_and_initialized():
if (not dist.is_available()):
return False
if (not dist.is_initialized()):
return False
return True
|
def get_world_size():
if (not is_dist_avail_and_initialized()):
return 1
return dist.get_world_size()
|
def get_rank():
if (not is_dist_avail_and_initialized()):
return 0
return dist.get_rank()
|
def is_main_process():
return (get_rank() == 0)
|
def save_on_master(*args, **kwargs):
if is_main_process():
torch.save(*args, **kwargs)
|
def init_distributed_mode(args):
if args.dist_on_itp:
args.rank = int(os.environ['OMPI_COMM_WORLD_RANK'])
args.world_size = int(os.environ['OMPI_COMM_WORLD_SIZE'])
args.gpu = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK'])
args.dist_url = ('tcp://%s:%s' % (os.environ['MASTER_ADDR'], ... |
def load_state_dict(model, state_dict, prefix='', ignore_missing='relative_position_index'):
missing_keys = []
unexpected_keys = []
error_msgs = []
metadata = getattr(state_dict, '_metadata', None)
state_dict = state_dict.copy()
if (metadata is not None):
state_dict._metadata = metadat... |
class NativeScalerWithGradNormCount():
state_dict_key = 'amp_scaler'
def __init__(self):
self._scaler = torch.cuda.amp.GradScaler()
def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True):
self._scaler.scale(loss).backward(create_graph=c... |
def get_grad_norm_(parameters, norm_type: float=2.0) -> torch.Tensor:
if isinstance(parameters, torch.Tensor):
parameters = [parameters]
parameters = [p for p in parameters if (p.grad is not None)]
norm_type = float(norm_type)
if (len(parameters) == 0):
return torch.tensor(0.0)
dev... |
def cosine_scheduler(base_value, final_value, epochs, niter_per_ep, max_communication_rounds=100, warmup_epochs=0, start_warmup_value=0, warmup_steps=(- 1)):
warmup_schedule = np.array([])
warmup_iters = (warmup_epochs * niter_per_ep)
if (warmup_steps > 0):
warmup_iters = warmup_steps
print(('... |
def save_model(args, epoch, model, model_without_ddp, optimizer, loss_scaler, model_ema=None):
output_dir = Path(args.output_dir)
epoch_name = str(epoch)
if (loss_scaler is not None):
checkpoint_paths = [(output_dir / ('checkpoint-%s.pth' % epoch_name))]
for checkpoint_path in checkpoint_p... |
def load_model(args, model_without_ddp, optimizer, loss_scaler, model_ema=None):
output_dir = Path(args.output_dir)
if args.resume:
if args.resume.startswith('https'):
checkpoint = torch.hub.load_state_dict_from_url(args.resume, map_location='cpu', check_hash=True)
else:
... |
def all_reduce_mean(x):
world_size = get_world_size()
if (world_size > 1):
x_reduce = torch.tensor(x).cuda()
dist.all_reduce(x_reduce)
x_reduce /= world_size
return x_reduce.item()
else:
return x
|
def auto_load_model(args, model, model_without_ddp, optimizer, loss_scaler, model_ema=None):
output_dir = Path(args.output_dir)
if (args.auto_resume and (len(args.resume) == 0)):
import glob
all_checkpoints = glob.glob(os.path.join(output_dir, 'checkpoint-*.pth'))
latest_ckpt = (- 1)
... |
def create_d_vae(weight_path, d_vae_type, image_size, device):
if (d_vae_type == 'dall-e'):
return get_dalle_vae(weight_path, image_size, device)
elif (d_vae_type == 'customized'):
return get_d_vae(weight_path, image_size, device)
else:
raise NotImplementedError()
|
def get_dalle_vae(weight_path, image_size, device):
vae = Dalle_VAE(image_size)
vae.load_model(model_dir=weight_path, device=device)
return vae
|
def get_d_vae(weight_path, image_size, device):
NUM_TOKENS = 8192
NUM_LAYERS = 3
EMB_DIM = 512
HID_DIM = 256
state_dict = torch.load(os.path.join(weight_path, 'pytorch_model.bin'), map_location='cpu')['weights']
model = DiscreteVAE(image_size=image_size, num_layers=NUM_LAYERS, num_tokens=NUM_T... |
def create_ds_config(args):
args.deepspeed_config = os.path.join(args.output_dir, 'deepspeed_config.json')
with open(args.deepspeed_config, mode='w') as writer:
ds_config = {'train_batch_size': ((args.batch_size * args.update_freq) * get_world_size()), 'train_micro_batch_size_per_gpu': args.batch_size... |
def top_k(logits, thres=0.5):
num_logits = logits.shape[(- 1)]
k = max(int(((1 - thres) * num_logits)), 1)
(val, ind) = torch.topk(logits, k)
probs = torch.full_like(logits, float('-inf'))
probs.scatter_(1, ind, val)
return probs
|
def exists(val):
return (val is not None)
|
def default(val, d):
return (val if exists(val) else d)
|
def eval_decorator(fn):
def inner(model, *args, **kwargs):
was_training = model.training
model.eval()
out = fn(model, *args, **kwargs)
model.train(was_training)
return out
return inner
|
class BasicVAE(nn.Module):
def get_codebook_indices(self, images):
raise NotImplementedError()
def decode(self, img_seq):
raise NotImplementedError()
def get_codebook_probs(self, img_seq):
raise NotImplementedError()
def get_image_tokens_size(self):
pass
def ge... |
class ResBlock(nn.Module):
def __init__(self, chan_in, hidden_size, chan_out):
super().__init__()
self.net = nn.Sequential(nn.Conv2d(chan_in, hidden_size, 3, padding=1), nn.ReLU(), nn.Conv2d(hidden_size, hidden_size, 3, padding=1), nn.ReLU(), nn.Conv2d(hidden_size, chan_out, 1))
def forward(... |
class DiscreteVAE(BasicVAE):
def __init__(self, image_size=256, num_tokens=512, codebook_dim=512, num_layers=3, hidden_dim=64, channels=3, smooth_l1_loss=False, temperature=0.9, straight_through=False, kl_div_loss_weight=0.0):
super().__init__()
assert (num_layers >= 1), 'number of layers must be... |
def vae_load_model(path: str, device: torch.device=None) -> nn.Module:
if (path.startswith('http://') or path.startswith('https://')):
resp = requests.get(path)
resp.raise_for_status()
with io.BytesIO(resp.content) as buf:
return torch.load(buf, map_location=device)
else:
... |
class Dalle_VAE(BasicVAE):
def __init__(self, image_size):
super().__init__()
self.encoder = None
self.decoder = None
self.image_size = image_size
def load_model(self, model_dir, device):
print('pickel_file_location: ,', model_dir, 'encoder.pkl')
self.encoder ... |
def get_num_layer_for_vit(var_name, num_max_layer):
if (var_name in ('cls_token', 'mask_token', 'pos_embed')):
return 0
elif var_name.startswith('patch_embed'):
return 0
elif var_name.startswith('rel_pos_bias'):
return (num_max_layer - 1)
elif var_name.startswith('blocks'):
... |
class LayerDecayValueAssigner(object):
def __init__(self, values):
self.values = values
def get_scale(self, layer_id):
return self.values[layer_id]
def get_layer_id(self, var_name):
return get_num_layer_for_vit(var_name, len(self.values))
|
def add_weight_decay(model, weight_decay=1e-05, skip_list=()):
decay = []
no_decay = []
for (name, param) in model.named_parameters():
if (not param.requires_grad):
continue
if ((len(param.shape) == 1) or name.endswith('.bias') or (name in skip_list)):
no_decay.appe... |
def get_parameter_groups(model, weight_decay=1e-05, skip_list=(), get_num_layer=None, get_layer_scale=None):
parameter_group_names = {}
parameter_group_vars = {}
for (name, param) in model.named_parameters():
if (not param.requires_grad):
continue
if ((len(param.shape) == 1) or... |
def create_optimizer(args, model, get_num_layer=None, get_layer_scale=None, filter_bias_and_bn=True, skip_list=None):
opt_lower = args.opt.lower()
weight_decay = args.weight_decay
if (weight_decay and filter_bias_and_bn):
skip = {}
if (skip_list is not None):
skip = skip_list
... |
def print_options(args, model):
message = ''
num_params = sum((p.numel() for p in model.parameters() if p.requires_grad))
num_params = (num_params / 1000000)
message += ('================ FL train of %s with total model parameters: %2.1fM ================\n' % (args.model, num_params))
message +=... |
class ToNumpy():
def __call__(self, pil_img):
np_img = np.array(pil_img, dtype=np.uint8)
if (np_img.ndim < 3):
np_img = np.expand_dims(np_img, axis=(- 1))
np_img = np.rollaxis(np_img, 2)
return np_img
|
class ToTensor():
def __init__(self, dtype=torch.float32):
self.dtype = dtype
def __call__(self, pil_img):
np_img = np.array(pil_img, dtype=np.uint8)
if (np_img.ndim < 3):
np_img = np.expand_dims(np_img, axis=(- 1))
np_img = np.rollaxis(np_img, 2)
return t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.