id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
157,503 | import torch
import torchvision
from torchvision import datasets
from torch.utils.data import sampler, DataLoader
from torch.utils.data.sampler import BatchSampler
import torch.distributed as dist
import numpy as np
import json
import os
from datasets.DistributedProxySampler import DistributedProxySampler
def sample_labeled_data(args, data, target,
num_labels, num_classes,
index=None, name=None):
'''
samples for labeled data
(sampling with balanced ratio over classes)
'''
assert num_labels % num_classes == 0
if not index is None:
index = np.array(index, dtype=np.int32)
return data[index], target[index], index
dump_path = os.path.join(args.save_dir, args.save_name, 'sampled_label_idx.npy')
if os.path.exists(dump_path):
lb_idx = np.load(dump_path)
lb_data = data[lb_idx]
lbs = target[lb_idx]
return lb_data, lbs, lb_idx
samples_per_class = int(num_labels / num_classes)
lb_data = []
lbs = []
lb_idx = []
for c in range(num_classes):
idx = np.where(target == c)[0]
idx = np.random.choice(idx, samples_per_class, False)
lb_idx.extend(idx)
lb_data.extend(data[idx])
lbs.extend(target[idx])
np.save(dump_path, np.array(lb_idx))
return np.array(lb_data), np.array(lbs), np.array(lb_idx)
The provided code snippet includes necessary dependencies for implementing the `split_ssl_data` function. Write a Python function `def split_ssl_data(args, data, target, num_labels, num_classes, index=None, include_lb_to_ulb=True)` to solve the following problem:
data & target is splitted into labeled and unlabeld data. Args index: If np.array of index is given, select the data[index], target[index] as labeled samples. include_lb_to_ulb: If True, labeled data is also included in unlabeld data
Here is the function:
def split_ssl_data(args, data, target, num_labels, num_classes, index=None, include_lb_to_ulb=True):
"""
data & target is splitted into labeled and unlabeld data.
Args
index: If np.array of index is given, select the data[index], target[index] as labeled samples.
include_lb_to_ulb: If True, labeled data is also included in unlabeld data
"""
data, target = np.array(data), np.array(target)
lb_data, lbs, lb_idx, = sample_labeled_data(args, data, target, num_labels, num_classes, index)
ulb_idx = np.array(sorted(list(set(range(len(data))) - set(lb_idx)))) # unlabeled_data index of data
if include_lb_to_ulb:
return lb_data, lbs, data, target
else:
return lb_data, lbs, data[ulb_idx], target[ulb_idx] | data & target is splitted into labeled and unlabeld data. Args index: If np.array of index is given, select the data[index], target[index] as labeled samples. include_lb_to_ulb: If True, labeled data is also included in unlabeld data |
157,504 | import torch
import torchvision
from torchvision import datasets
from torch.utils.data import sampler, DataLoader
from torch.utils.data.sampler import BatchSampler
import torch.distributed as dist
import numpy as np
import json
import os
from datasets.DistributedProxySampler import DistributedProxySampler
def get_onehot(num_classes, idx):
onehot = np.zeros([num_classes], dtype=np.float32)
onehot[idx] += 1.0
return onehot | null |
157,510 | import torch
from .data_utils import split_ssl_data, sample_labeled_data
from .dataset import BasicDataset
from collections import Counter
import torchvision
import numpy as np
from torchvision import transforms
import json
import os
import random
from .augmentation.randaugment import RandAugment
from torch.utils.data import sampler, DataLoader
from torch.utils.data.sampler import BatchSampler
import torch.distributed as dist
from datasets.DistributedProxySampler import DistributedProxySampler
import gc
import sys
import copy
from PIL import Image
def accimage_loader(path):
import accimage
try:
return accimage.Image(path)
except IOError:
# Potentially a decoding problem, fall back to PIL.Image
return pil_loader(path)
def pil_loader(path):
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
with open(path, 'rb') as f:
img = Image.open(f)
return img.convert('RGB')
def default_loader(path):
from torchvision import get_image_backend
if get_image_backend() == 'accimage':
return accimage_loader(path)
else:
return pil_loader(path) | null |
157,511 | import torch
from .data_utils import split_ssl_data, sample_labeled_data
from .dataset import BasicDataset
from collections import Counter
import torchvision
import numpy as np
from torchvision import transforms
import json
import os
import random
from .augmentation.randaugment import RandAugment
from torch.utils.data import sampler, DataLoader
from torch.utils.data.sampler import BatchSampler
import torch.distributed as dist
from datasets.DistributedProxySampler import DistributedProxySampler
import gc
import sys
import copy
from PIL import Image
def get_transform(mean, std, crop_size, train=True):
if train:
return transforms.Compose([transforms.RandomHorizontalFlip(),
transforms.RandomCrop(crop_size, padding=4, padding_mode='reflect'),
transforms.ToTensor(),
transforms.Normalize(mean, std)])
else:
return transforms.Compose([transforms.ToTensor(),
transforms.Normalize(mean, std)]) | null |
157,512 | import os
def create_configuration(cfg, cfg_file):
cfg['save_name'] = "{alg}_{dataset}_{num_lb}_{seed}".format(
alg=cfg['alg'],
dataset=cfg['dataset'],
num_lb=cfg['num_labels'],
seed=cfg['seed'],
)
alg_file = cfg_file + cfg['alg'] + '/'
if not os.path.exists(alg_file):
os.mkdir(alg_file)
print(alg_file + cfg['save_name'] + '.yaml')
with open(alg_file + cfg['save_name'] + '.yaml', 'w', encoding='utf-8') as w:
lines = []
for k, v in cfg.items():
line = str(k) + ': ' + str(v)
lines.append(line)
for line in lines:
w.writelines(line)
w.write('\n')
def create_base_config(alg, seed,
dataset, net, num_classes, num_labels,
port,
weight_decay,
depth, widen_factor,
):
cfg = {}
# save config
cfg['save_dir'] = './saved_models'
cfg['save_name'] = None
cfg['resume'] = False
cfg['load_path'] = None
cfg['overwrite'] = True
cfg['use_tensorboard'] = True
# algorithm config
cfg['epoch'] = 1
cfg['num_train_iter'] = 2 ** 20
cfg['num_eval_iter'] = 5000
cfg['num_labels'] = num_labels
cfg['batch_size'] = 64
cfg['eval_batch_size'] = 1024
if alg == 'fixmatch':
cfg['hard_label'] = True
cfg['T'] = 0.5
cfg['p_cutoff'] = 0.95
cfg['ulb_loss_ratio'] = 1.0
cfg['uratio'] = 7
elif alg == 'flexmatch':
cfg['hard_label'] = True
cfg['T'] = 0.5
cfg['p_cutoff'] = 0.95
cfg['ulb_loss_ratio'] = 1.0
cfg['uratio'] = 7
elif alg == 'uda':
cfg['TSA_schedule'] = 'none'
cfg['T'] = 0.4
cfg['p_cutoff'] = 0.8
cfg['ulb_loss_ratio'] = 1.0
cfg['uratio'] = 7
elif alg == 'pseudolabel':
cfg['ulb_loss_ratio'] = 1.0
cfg['uratio'] = 1
elif alg == 'mixmatch':
cfg['uratio'] = 1
cfg['alpha'] = 0.5
cfg['T'] = 0.5
cfg['ulb_loss_ratio'] = 100
cfg['ramp_up'] = 0.4
elif alg == 'remixmatch':
cfg['alpha'] = 0.75
cfg['T'] = 0.5
cfg['ulb_loss_ratio'] = 1.0
cfg['w_kl'] = 0.5
cfg['w_match'] = 1.5
cfg['w_rot'] = 0.5
cfg['use_dm'] = True
cfg['use_xe'] = True
cfg['warm_up'] = 1 / 64
cfg['uratio'] = 1
elif alg == 'meanteacher':
cfg['uratio'] = 1
cfg['ulb_loss_ratio'] = 50
cfg['unsup_warm_up'] = 0.4
elif alg == 'pimodel':
cfg['ulb_loss_ratio'] = 10
cfg['uratio'] = 1
elif alg == 'freematch':
cfg['hard_label'] = True
cfg['T'] = 0.5
cfg['ulb_loss_ratio'] = 1.0
cfg['ent_loss_ratio'] = 0.0
cfg['uratio'] = 7
elif alg == 'freematch_entropy':
cfg['hard_label'] = True
cfg['T'] = 0.5
cfg['ulb_loss_ratio'] = 1.0
cfg['ent_loss_ratio'] = 0.01
cfg['uratio'] = 7
elif alg == 'softmatch':
cfg['hard_label'] = True
cfg['T'] = 0.5
cfg['ulb_loss_ratio'] = 1.0
cfg['uratio'] = 7
cfg['dist_align'] = True
cfg['ema_m'] = 0.999
# optim config
cfg['optim'] = 'SGD'
cfg['lr'] = 0.03
cfg['momentum'] = 0.9
cfg['weight_decay'] = weight_decay
cfg['amp'] = False
# net config
cfg['net'] = net
cfg['net_from_name'] = False
cfg['depth'] = depth
cfg['widen_factor'] = widen_factor
cfg['leaky_slope'] = 0.1
cfg['dropout'] = 0.0
# data config
cfg['data_dir'] = './data'
cfg['dataset'] = dataset
cfg['train_sampler'] = 'RandomSampler'
cfg['num_classes'] = num_classes
cfg['num_workers'] = 1
# basic config
cfg['alg'] = alg
cfg['seed'] = seed
# distributed config
cfg['world_size'] = 1
cfg['rank'] = 0
cfg['multiprocessing_distributed'] = True
cfg['dist_url'] = 'tcp://127.0.0.1:' + str(port)
cfg['dist_backend'] = 'nccl'
cfg['gpu'] = None
# other config
cfg['overwrite'] = True
cfg['amp'] = False
# # to follow fixmatch settings
# if dataset == "imagenet":
# cfg['batch_size'] = 1024
# cfg['uratio'] = 5
# cfg['ulb_loss_ratio'] = 10
# cfg['p_cutoff'] = 0.7
# cfg['lr'] = 0.1
# cfg['num_train_iter'] = 12000000
if dataset == "imagenet":
cfg['batch_size'] = 32
cfg['eval_batch_size'] = 256
cfg['lr'] = 0.03
cfg['num_train_iter'] = 2000000
cfg['num_eval_iter'] = 10000
return cfg
def exp_baseline(label_amount):
config_file = r'./config/'
save_path = r'./saved_models/'
if not os.path.exists(config_file):
os.mkdir(config_file)
if not os.path.exists(save_path):
os.mkdir(save_path)
algs = ['flexmatch', 'fixmatch', 'uda', 'pseudolabel', 'fullysupervised', 'remixmatch', 'mixmatch', 'meanteacher',
'pimodel', 'vat', 'freematch', 'freematch_entropy', 'softmatch']
datasets = ['cifar10', 'cifar100', 'svhn', 'stl10', 'imagenet']
# datasets = ['imagenet']
# seeds = [1, 11, 111]
seeds = [0] # 1, 22, 333
dist_port = range(10001, 11120, 1)
count = 0
for alg in algs:
for dataset in datasets:
for seed in seeds:
# change the configuration of each dataset
if dataset == 'cifar10':
net = 'WideResNet'
num_classes = 10
num_labels = label_amount[0]
weight_decay = 5e-4
depth = 28
widen_factor = 2
elif dataset == 'cifar100':
net = 'WideResNet'
num_classes = 100
num_labels = label_amount[1]
weight_decay = 1e-3
depth = 28
widen_factor = 8
elif dataset == 'svhn':
net = 'WideResNet'
num_classes = 10
num_labels = label_amount[2]
weight_decay = 5e-4
depth = 28
widen_factor = 2
elif dataset == 'stl10':
net = 'WideResNetVar'
num_classes = 10
num_labels = label_amount[3]
weight_decay = 5e-4
depth = 28
widen_factor = 2
elif dataset == 'imagenet':
if alg not in ['fixmatch', 'flexmatch']:
continue
net = 'ResNet50'
num_classes = 1000
num_labels = 100000 # 128000
weight_decay = 3e-4
depth = 0 # depth and widen_factor not used in ResNet-50.
widen_factor = 0
port = dist_port[count]
# prepare the configuration file
cfg = create_base_config(alg, seed,
dataset, net, num_classes, num_labels,
port,
weight_decay, depth, widen_factor
)
count += 1
create_configuration(cfg, config_file) | null |
157,513 | import os
def create_configuration(cfg, cfg_file):
cfg['save_name'] = "{alg}_{dataset}_{num_lb}_{seed}".format(
alg=cfg['alg'],
dataset=cfg['dataset'],
num_lb=cfg['num_labels'],
seed=cfg['seed'],
)
alg_file = cfg_file + cfg['alg'] + '/'
if not os.path.exists(alg_file):
os.mkdir(alg_file)
print(alg_file + cfg['save_name'] + '.yaml')
with open(alg_file + cfg['save_name'] + '.yaml', 'w', encoding='utf-8') as w:
lines = []
for k, v in cfg.items():
line = str(k) + ': ' + str(v)
lines.append(line)
for line in lines:
w.writelines(line)
w.write('\n')
def create_base_config(alg, seed,
dataset, net, num_classes, num_labels,
port,
weight_decay,
depth, widen_factor,
):
cfg = {}
# save config
cfg['save_dir'] = './saved_models'
cfg['save_name'] = None
cfg['resume'] = False
cfg['load_path'] = None
cfg['overwrite'] = True
cfg['use_tensorboard'] = True
# algorithm config
cfg['epoch'] = 1
cfg['num_train_iter'] = 2 ** 20
cfg['num_eval_iter'] = 5000
cfg['num_labels'] = num_labels
cfg['batch_size'] = 64
cfg['eval_batch_size'] = 1024
if alg == 'fixmatch':
cfg['hard_label'] = True
cfg['T'] = 0.5
cfg['p_cutoff'] = 0.95
cfg['ulb_loss_ratio'] = 1.0
cfg['uratio'] = 7
elif alg == 'flexmatch':
cfg['hard_label'] = True
cfg['T'] = 0.5
cfg['p_cutoff'] = 0.95
cfg['ulb_loss_ratio'] = 1.0
cfg['uratio'] = 7
elif alg == 'uda':
cfg['TSA_schedule'] = 'none'
cfg['T'] = 0.4
cfg['p_cutoff'] = 0.8
cfg['ulb_loss_ratio'] = 1.0
cfg['uratio'] = 7
elif alg == 'pseudolabel':
cfg['ulb_loss_ratio'] = 1.0
cfg['uratio'] = 1
elif alg == 'mixmatch':
cfg['uratio'] = 1
cfg['alpha'] = 0.5
cfg['T'] = 0.5
cfg['ulb_loss_ratio'] = 100
cfg['ramp_up'] = 0.4
elif alg == 'remixmatch':
cfg['alpha'] = 0.75
cfg['T'] = 0.5
cfg['ulb_loss_ratio'] = 1.0
cfg['w_kl'] = 0.5
cfg['w_match'] = 1.5
cfg['w_rot'] = 0.5
cfg['use_dm'] = True
cfg['use_xe'] = True
cfg['warm_up'] = 1 / 64
cfg['uratio'] = 1
elif alg == 'meanteacher':
cfg['uratio'] = 1
cfg['ulb_loss_ratio'] = 50
cfg['unsup_warm_up'] = 0.4
elif alg == 'pimodel':
cfg['ulb_loss_ratio'] = 10
cfg['uratio'] = 1
elif alg == 'freematch':
cfg['hard_label'] = True
cfg['T'] = 0.5
cfg['ulb_loss_ratio'] = 1.0
cfg['ent_loss_ratio'] = 0.0
cfg['uratio'] = 7
elif alg == 'freematch_entropy':
cfg['hard_label'] = True
cfg['T'] = 0.5
cfg['ulb_loss_ratio'] = 1.0
cfg['ent_loss_ratio'] = 0.01
cfg['uratio'] = 7
elif alg == 'softmatch':
cfg['hard_label'] = True
cfg['T'] = 0.5
cfg['ulb_loss_ratio'] = 1.0
cfg['uratio'] = 7
cfg['dist_align'] = True
cfg['ema_m'] = 0.999
# optim config
cfg['optim'] = 'SGD'
cfg['lr'] = 0.03
cfg['momentum'] = 0.9
cfg['weight_decay'] = weight_decay
cfg['amp'] = False
# net config
cfg['net'] = net
cfg['net_from_name'] = False
cfg['depth'] = depth
cfg['widen_factor'] = widen_factor
cfg['leaky_slope'] = 0.1
cfg['dropout'] = 0.0
# data config
cfg['data_dir'] = './data'
cfg['dataset'] = dataset
cfg['train_sampler'] = 'RandomSampler'
cfg['num_classes'] = num_classes
cfg['num_workers'] = 1
# basic config
cfg['alg'] = alg
cfg['seed'] = seed
# distributed config
cfg['world_size'] = 1
cfg['rank'] = 0
cfg['multiprocessing_distributed'] = True
cfg['dist_url'] = 'tcp://127.0.0.1:' + str(port)
cfg['dist_backend'] = 'nccl'
cfg['gpu'] = None
# other config
cfg['overwrite'] = True
cfg['amp'] = False
# # to follow fixmatch settings
# if dataset == "imagenet":
# cfg['batch_size'] = 1024
# cfg['uratio'] = 5
# cfg['ulb_loss_ratio'] = 10
# cfg['p_cutoff'] = 0.7
# cfg['lr'] = 0.1
# cfg['num_train_iter'] = 12000000
if dataset == "imagenet":
cfg['batch_size'] = 32
cfg['eval_batch_size'] = 256
cfg['lr'] = 0.03
cfg['num_train_iter'] = 2000000
cfg['num_eval_iter'] = 10000
return cfg
def exp_flex_component(label_amount):
config_file = r'./config/'
save_path = r'./saved_models/'
if not os.path.exists(config_file):
os.mkdir(config_file)
if not os.path.exists(save_path):
os.mkdir(save_path)
algs = ['uda', 'pseudolabel']
datasets = ['cifar10', 'cifar100', 'svhn', 'stl10']
# seeds = [1, 11, 111]
seeds = [0]
dist_port = range(11121, 12120, 1)
count = 0
for alg in algs:
for dataset in datasets:
for seed in seeds:
# change the configuration of each dataset
if dataset == 'cifar10':
net = 'WideResNet'
num_classes = 10
num_labels = label_amount[0]
weight_decay = 5e-4
depth = 28
widen_factor = 2
elif dataset == 'cifar100':
net = 'WideResNet'
num_classes = 100
num_labels = label_amount[1]
weight_decay = 1e-3
depth = 28
widen_factor = 8
elif dataset == 'svhn':
net = 'WideResNet'
num_classes = 10
num_labels = label_amount[2]
weight_decay = 5e-4
depth = 28
widen_factor = 2
elif dataset == 'stl10':
net = 'WideResNetVar'
num_classes = 10
num_labels = label_amount[3]
weight_decay = 5e-4
depth = 28
widen_factor = 2
port = dist_port[count]
# prepare the configuration file
cfg = create_base_config(alg, seed,
dataset, net, num_classes, num_labels,
port,
weight_decay, depth, widen_factor
)
count += 1
cfg['use_flex'] = True
cfg['alg'] += str('_flex')
create_configuration(cfg, config_file) | null |
157,515 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
import numpy as np
from torch.autograd import Variable
def entropy_loss(ul_y):
p = F.softmax(ul_y, dim=1)
return -(p*F.log_softmax(ul_y, dim=1)).sum(dim=1).mean(dim=0) | null |
157,516 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
import numpy as np
from torch.autograd import Variable
def _l2_normalize(d):
d = d.numpy()
d /= (np.sqrt(np.sum(d ** 2, axis=(1, 2, 3))).reshape((-1, 1, 1, 1)) + 1e-16)
return torch.from_numpy(d)
def kl_div_with_logit(q_logit, p_logit):
q = F.softmax(q_logit, dim=1)
logq = F.log_softmax(q_logit, dim=1)
logp = F.log_softmax(p_logit, dim=1)
qlogq = ( q *logq).sum(dim=1).mean(dim=0)
qlogp = ( q *logp).sum(dim=1).mean(dim=0)
return qlogq - qlogp
def vat_loss(model, ul_x, ul_y, xi=1e-6, eps=6, num_iters=1):
# find r_adv
d = torch.Tensor(ul_x.size()).normal_()
for i in range(num_iters):
d = xi *_l2_normalize(d)
d = Variable(d.cuda(), requires_grad=True)
y_hat = model(ul_x + d)
delta_kl = kl_div_with_logit(ul_y.detach(), y_hat)
delta_kl.backward()
d = d.grad.data.clone().cpu()
model.zero_grad()
d = _l2_normalize(d)
d = Variable(d.cuda())
r_adv = eps *d
# compute lds
y_hat = model(ul_x + r_adv.detach())
delta_kl = kl_div_with_logit(ul_y.detach(), y_hat)
return delta_kl | null |
157,517 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
def replace_inf_to_zero(val):
val[val == float('inf')] = 0.0
return val
def entropy_loss(mask, logits_s, logits_w, prob_model, label_hist):
# select samples
logits_s = logits_s[mask]
prob_s = logits_s.softmax(dim=-1)
_, pred_label_s = torch.max(prob_s, dim=-1)
hist_s = torch.bincount(pred_label_s, minlength=logits_s.shape[1]).to(logits_w.dtype)
hist_s = hist_s / hist_s.sum()
# modulate prob model
prob_model = prob_model.reshape(1, -1)
label_hist = label_hist.reshape(1, -1)
# prob_model_scaler = torch.nan_to_num(1 / label_hist, nan=0.0, posinf=0.0, neginf=0.0).detach()
prob_model_scaler = replace_inf_to_zero(1 / label_hist).detach()
mod_prob_model = prob_model * prob_model_scaler
mod_prob_model = mod_prob_model / mod_prob_model.sum(dim=-1, keepdim=True)
# modulate mean prob
mean_prob_scaler_s = replace_inf_to_zero(1 / hist_s).detach()
# mean_prob_scaler_s = torch.nan_to_num(1 / hist_s, nan=0.0, posinf=0.0, neginf=0.0).detach()
mod_mean_prob_s = prob_s.mean(dim=0, keepdim=True) * mean_prob_scaler_s
mod_mean_prob_s = mod_mean_prob_s / mod_mean_prob_s.sum(dim=-1, keepdim=True)
loss = mod_prob_model * torch.log(mod_mean_prob_s + 1e-12)
loss = loss.sum(dim=1)
return loss.mean(), hist_s.mean() | null |
157,518 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
def ce_loss(logits, targets, use_hard_labels=True, reduction='none'):
"""
wrapper for cross entropy loss in pytorch.
Args
logits: logit values, shape=[Batch size, # of classes]
targets: integer or vector, shape=[Batch size] or [Batch size, # of classes]
use_hard_labels: If True, targets have [Batch size] shape with int values. If False, the target is vector (default True)
"""
if use_hard_labels:
log_pred = F.log_softmax(logits, dim=-1)
return F.nll_loss(log_pred, targets, reduction=reduction)
# return F.cross_entropy(logits, targets, reduction=reduction) this is unstable
else:
assert logits.shape == targets.shape
log_pred = F.log_softmax(logits, dim=-1)
nll_loss = torch.sum(-targets * log_pred, dim=1)
return nll_loss
def consistency_loss(dataset, logits_s, logits_w,time_p,p_model, name='ce', use_hard_labels=True):
assert name in ['ce', 'L2']
logits_w = logits_w.detach()
if name == 'L2':
assert logits_w.size() == logits_s.size()
return F.mse_loss(logits_s, logits_w, reduction='mean')
elif name == 'L2_mask':
pass
elif name == 'ce':
pseudo_label = torch.softmax(logits_w, dim=-1)
max_probs, max_idx = torch.max(pseudo_label, dim=-1)
p_cutoff = time_p
p_model_cutoff = p_model / torch.max(p_model,dim=-1)[0]
threshold = p_cutoff * p_model_cutoff[max_idx]
if dataset == 'svhn':
threshold = torch.clamp(threshold, min=0.9, max=0.95)
mask = max_probs.ge(threshold)
if use_hard_labels:
masked_loss = ce_loss(logits_s, max_idx, use_hard_labels, reduction='none') * mask.float()
else:
pseudo_label = torch.softmax(logits_w / T, dim=-1)
masked_loss = ce_loss(logits_s, pseudo_label, use_hard_labels) * mask.float()
return masked_loss.mean(), mask
else:
assert Exception('Not Implemented consistency_loss') | null |
157,519 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
import numpy as np
def one_hot(targets, nClass, gpu):
logits = torch.zeros(targets.size(0), nClass).cuda(gpu)
return logits.scatter_(1,targets.unsqueeze(1),1) | null |
157,520 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `mixup_one_target` function. Write a Python function `def mixup_one_target(x, y, gpu, alpha=1.0, is_bias=False)` to solve the following problem:
Returns mixed inputs, mixed targets, and lambda
Here is the function:
def mixup_one_target(x, y, gpu, alpha=1.0, is_bias=False):
"""Returns mixed inputs, mixed targets, and lambda
"""
if alpha > 0:
lam = np.random.beta(alpha, alpha)
else:
lam = 1
if is_bias: lam = max(lam, 1-lam)
index = torch.randperm(x.size(0)).cuda(gpu)
mixed_x = lam*x + (1-lam)*x[index, :]
mixed_y = lam*y + (1-lam)*y[index]
return mixed_x, mixed_y, lam | Returns mixed inputs, mixed targets, and lambda |
157,521 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
import numpy as np
def consistency_loss(logits_w, y):
return F.mse_loss(torch.softmax(logits_w,dim=-1), y, reduction='mean') | null |
157,522 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
def ce_loss(logits, targets, use_hard_labels=True, reduction='none'):
"""
wrapper for cross entropy loss in pytorch.
Args
logits: logit values, shape=[Batch size, # of classes]
targets: integer or vector, shape=[Batch size] or [Batch size, # of classes]
use_hard_labels: If True, targets have [Batch size] shape with int values. If False, the target is vector (default True)
"""
if use_hard_labels:
log_pred = F.log_softmax(logits, dim=-1)
return F.nll_loss(log_pred, targets, reduction=reduction)
# return F.cross_entropy(logits, targets, reduction=reduction) this is unstable
else:
assert logits.shape == targets.shape
log_pred = F.log_softmax(logits, dim=-1)
nll_loss = torch.sum(-targets * log_pred, dim=1)
return nll_loss
def consistency_loss(logits_s, logits_w, mask, name='ce', T=0.5, use_hard_labels=True):
assert name in ['ce', 'L2']
logits_w = logits_w.detach()
if name == 'L2':
assert logits_w.size() == logits_s.size()
return F.mse_loss(logits_s, logits_w, reduction='mean')
elif name == 'L2_mask':
pass
elif name == 'ce':
pseudo_label = torch.softmax(logits_w, dim=-1)
_, max_idx = torch.max(pseudo_label, dim=-1)
if use_hard_labels:
masked_loss = ce_loss(logits_s, max_idx, use_hard_labels, reduction='none') * mask.float()
else:
pseudo_label = torch.softmax(logits_w / T, dim=-1)
masked_loss = ce_loss(logits_s, pseudo_label, use_hard_labels) * mask.float()
return masked_loss.mean(), mask
else:
assert Exception('Not Implemented consistency_loss') | null |
157,523 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `mish` function. Write a Python function `def mish(x)` to solve the following problem:
Mish: A Self Regularized Non-Monotonic Neural Activation Function (https://arxiv.org/abs/1908.08681)
Here is the function:
def mish(x):
"""Mish: A Self Regularized Non-Monotonic Neural Activation Function (https://arxiv.org/abs/1908.08681)"""
return x * torch.tanh(F.softplus(x)) | Mish: A Self Regularized Non-Monotonic Neural Activation Function (https://arxiv.org/abs/1908.08681) |
157,527 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
def consistency_loss(logits_w1, logits_w2):
logits_w2 = logits_w2.detach()
assert logits_w1.size() == logits_w2.size()
return F.mse_loss(torch.softmax(logits_w1, dim=-1), torch.softmax(logits_w2, dim=-1), reduction='mean') | null |
157,528 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
def ce_loss(logits, targets, use_hard_labels=True, reduction='none'):
"""
wrapper for cross entropy loss in pytorch.
Args
logits: logit values, shape=[Batch size, # of classes]
targets: integer or vector, shape=[Batch size] or [Batch size, # of classes]
use_hard_labels: If True, targets have [Batch size] shape with int values. If False, the target is vector (default True)
"""
if use_hard_labels:
log_pred = F.log_softmax(logits, dim=-1)
return F.nll_loss(log_pred, targets, reduction=reduction)
# return F.cross_entropy(logits, targets, reduction=reduction) this is unstable
else:
assert logits.shape == targets.shape
log_pred = F.log_softmax(logits, dim=-1)
nll_loss = torch.sum(-targets * log_pred, dim=1)
return nll_loss
def consistency_loss(logits_s, logits_w, name='ce', T=1.0, p_cutoff=0.0, use_hard_labels=True):
assert name in ['ce', 'L2']
logits_w = logits_w.detach()
if name == 'L2':
assert logits_w.size() == logits_s.size()
return F.mse_loss(logits_s, logits_w, reduction='mean')
elif name == 'L2_mask':
pass
elif name == 'ce':
pseudo_label = torch.softmax(logits_w, dim=-1)
max_probs, max_idx = torch.max(pseudo_label, dim=-1)
mask = max_probs.ge(p_cutoff).float()
select = max_probs.ge(p_cutoff).long()
# strong_prob, strong_idx = torch.max(torch.softmax(logits_s, dim=-1), dim=-1)
# strong_select = strong_prob.ge(p_cutoff).long()
# select = select * strong_select * (strong_idx == max_idx)
if use_hard_labels:
masked_loss = ce_loss(logits_s, max_idx, use_hard_labels, reduction='none') * mask
else:
pseudo_label = torch.softmax(logits_w / T, dim=-1)
masked_loss = ce_loss(logits_s, pseudo_label, use_hard_labels) * mask
return masked_loss.mean(), mask.mean(), select, max_idx.long()
else:
assert Exception('Not Implemented consistency_loss') | null |
157,529 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
def consistency_loss(logits_w1, logits_w2):
logits_w2 = logits_w2.detach()
assert logits_w1.size() == logits_w2.size()
return F.mse_loss(torch.softmax(logits_w1,dim=-1), torch.softmax(logits_w2,dim=-1), reduction='mean') | null |
157,530 | import torch
import math
import torch.nn.functional as F
import numpy as np
from train_utils import ce_loss
def ce_loss(logits, targets, use_hard_labels=True, reduction='none'):
"""
wrapper for cross entropy loss in pytorch.
Args
logits: logit values, shape=[Batch size, # of classes]
targets: integer or vector, shape=[Batch size] or [Batch size, # of classes]
use_hard_labels: If True, targets have [Batch size] shape with int values. If False, the target is vector (default True)
"""
if use_hard_labels:
log_pred = F.log_softmax(logits, dim=-1)
return F.nll_loss(log_pred, targets, reduction=reduction)
# return F.cross_entropy(logits, targets, reduction=reduction) this is unstable
else:
assert logits.shape == targets.shape
log_pred = F.log_softmax(logits, dim=-1)
nll_loss = torch.sum(-targets * log_pred, dim=1)
return nll_loss
def consistency_loss(logits_s, logits_w, class_acc, p_target, p_model, name='ce',
T=1.0, p_cutoff=0.0, use_hard_labels=True, use_DA=False):
assert name in ['ce', 'L2']
logits_w = logits_w.detach()
if name == 'L2':
assert logits_w.size() == logits_s.size()
return F.mse_loss(logits_s, logits_w, reduction='mean')
elif name == 'L2_mask':
pass
elif name == 'ce':
pseudo_label = torch.softmax(logits_w, dim=-1)
if use_DA:
if p_model == None:
p_model = torch.mean(pseudo_label.detach(), dim=0)
else:
p_model = p_model * 0.999 + torch.mean(pseudo_label.detach(), dim=0) * 0.001
pseudo_label = pseudo_label * p_target / p_model
pseudo_label = (pseudo_label / pseudo_label.sum(dim=-1, keepdim=True))
max_probs, max_idx = torch.max(pseudo_label, dim=-1)
# mask = max_probs.ge(p_cutoff * (class_acc[max_idx] + 1.) / 2).float() # linear
# mask = max_probs.ge(p_cutoff * (1 / (2. - class_acc[max_idx]))).float() # low_limit
mask = max_probs.ge(p_cutoff * (class_acc[max_idx] / (2. - class_acc[max_idx]))).float() # convex
# mask = max_probs.ge(p_cutoff * (torch.log(class_acc[max_idx] + 1.) + 0.5)/(math.log(2) + 0.5)).float() # concave
select = max_probs.ge(p_cutoff).long()
if use_hard_labels:
masked_loss = ce_loss(logits_s, max_idx, use_hard_labels, reduction='none') * mask
else:
pseudo_label = torch.softmax(logits_w / T, dim=-1)
masked_loss = ce_loss(logits_s, pseudo_label, use_hard_labels) * mask
return masked_loss.mean(), mask.mean(), select, max_idx.long(), p_model
else:
assert Exception('Not Implemented consistency_loss') | null |
157,531 | import torch
import math
import torch.nn.functional as F
from train_utils import ce_loss
import numpy as np
def TSA(schedule, cur_iter, total_iter, num_classes):
training_progress = cur_iter / total_iter
if schedule == 'linear':
threshold = training_progress
elif schedule == 'exp':
scale = 5
threshold = math.exp((training_progress - 1) * scale)
elif schedule == 'log':
scale = 5
threshold = 1 - math.exp((-training_progress) * scale)
elif schedule == 'none':
return 1
tsa = threshold * (1 - 1 / num_classes) + 1 / num_classes
return tsa | null |
157,532 | import torch
import math
import torch.nn.functional as F
from train_utils import ce_loss
import numpy as np
def ce_loss(logits, targets, use_hard_labels=True, reduction='none'):
"""
wrapper for cross entropy loss in pytorch.
Args
logits: logit values, shape=[Batch size, # of classes]
targets: integer or vector, shape=[Batch size] or [Batch size, # of classes]
use_hard_labels: If True, targets have [Batch size] shape with int values. If False, the target is vector (default True)
"""
if use_hard_labels:
log_pred = F.log_softmax(logits, dim=-1)
return F.nll_loss(log_pred, targets, reduction=reduction)
# return F.cross_entropy(logits, targets, reduction=reduction) this is unstable
else:
assert logits.shape == targets.shape
log_pred = F.log_softmax(logits, dim=-1)
nll_loss = torch.sum(-targets * log_pred, dim=1)
return nll_loss
def consistency_loss(logits_s, logits_w, class_acc, it, ds, name='ce', T=1.0, p_cutoff=0.0, use_flex=False):
logits_w = logits_w.detach()
if name == 'ce':
pseudo_label = torch.softmax(logits_w, dim=-1)
max_probs, max_idx = torch.max(pseudo_label, dim=-1)
if use_flex:
mask = max_probs.ge(p_cutoff * (class_acc[max_idx] / (2. - class_acc[max_idx]))).float()
else:
mask = max_probs.ge(p_cutoff).float()
select = max_probs.ge(p_cutoff).long()
pseudo_label = torch.softmax(logits_w / T, dim=-1)
masked_loss = ce_loss(logits_s, pseudo_label, use_hard_labels=False) * mask
return masked_loss.mean(), mask.mean(), select, max_idx.long()
if name == 'kld_tf':
# The implementation of loss_unsup for Google's TF
# logits_tgt by sharpening
logits_tgt = (logits_w / T).detach()
# pseudo_labels_mask by confidence masking
pseudo_labels = torch.softmax(logits_w, dim=-1).detach()
p_class_max = torch.max(pseudo_labels, dim=-1, keepdim=False)[0]
loss_mask = p_class_max.ge(p_cutoff).float().detach()
kld = F.kl_div(torch.log_softmax(logits_s, dim=-1), torch.softmax(logits_tgt, dim=-1), reduction='none')
masked_loss = kld * loss_mask.unsqueeze(dim=-1).repeat(1, pseudo_labels.shape[1])
masked_loss = torch.sum(masked_loss, dim=1)
return masked_loss.mean(), loss_mask.mean()
else:
assert Exception('Not Implemented consistency_loss') | null |
157,533 | import torch
import math
import torch.nn.functional as F
from train_utils import ce_loss
import numpy as np
def torch_device_one():
return torch.tensor(1.) | null |
157,534 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
import numpy as np
def one_hot(targets, nClass, gpu):
logits = torch.zeros(targets.size(0), nClass).cuda(gpu)
return logits.scatter_(1, targets.unsqueeze(1), 1) | null |
157,535 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `mixup_one_target` function. Write a Python function `def mixup_one_target(x, y, gpu, alpha=1.0, is_bias=False)` to solve the following problem:
Returns mixed inputs, mixed targets, and lambda
Here is the function:
def mixup_one_target(x, y, gpu, alpha=1.0, is_bias=False):
"""Returns mixed inputs, mixed targets, and lambda
"""
if alpha > 0:
lam = np.random.beta(alpha, alpha)
else:
lam = 1
if is_bias:
lam = max(lam, 1 - lam)
index = torch.randperm(x.size(0)).cuda(gpu)
mixed_x = lam * x + (1 - lam) * x[index]
mixed_y = lam * y + (1 - lam) * y[index]
return mixed_x, mixed_y, lam | Returns mixed inputs, mixed targets, and lambda |
157,536 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
import numpy as np
def consistency_loss(logits_w, y):
return F.mse_loss(torch.softmax(logits_w, dim=-1), y, reduction='mean') | null |
157,537 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
def ce_loss(logits, targets, use_hard_labels=True, reduction='none'):
"""
wrapper for cross entropy loss in pytorch.
Args
logits: logit values, shape=[Batch size, # of classes]
targets: integer or vector, shape=[Batch size] or [Batch size, # of classes]
use_hard_labels: If True, targets have [Batch size] shape with int values. If False, the target is vector (default True)
"""
if use_hard_labels:
log_pred = F.log_softmax(logits, dim=-1)
return F.nll_loss(log_pred, targets, reduction=reduction)
# return F.cross_entropy(logits, targets, reduction=reduction) this is unstable
else:
assert logits.shape == targets.shape
log_pred = F.log_softmax(logits, dim=-1)
nll_loss = torch.sum(-targets * log_pred, dim=1)
return nll_loss
def consistency_loss(dataset,logits_s, logits_w,time_p,p_model, name='ce', use_hard_labels=True):
assert name in ['ce', 'L2']
logits_w = logits_w.detach()
if name == 'L2':
assert logits_w.size() == logits_s.size()
return F.mse_loss(logits_s, logits_w, reduction='mean')
elif name == 'L2_mask':
pass
elif name == 'ce':
pseudo_label = torch.softmax(logits_w, dim=-1)
max_probs, max_idx = torch.max(pseudo_label, dim=-1)
p_cutoff = time_p
p_model_cutoff = p_model / torch.max(p_model,dim=-1)[0]
threshold = p_cutoff * p_model_cutoff[max_idx]
if dataset == 'svhn':
threshold = torch.clamp(threshold, min=0.9, max=0.95)
mask = max_probs.ge(threshold)
if use_hard_labels:
masked_loss = ce_loss(logits_s, max_idx, use_hard_labels, reduction='none') * mask.float()
else:
pseudo_label = torch.softmax(logits_w / T, dim=-1)
masked_loss = ce_loss(logits_s, pseudo_label, use_hard_labels) * mask.float()
return masked_loss.mean(), mask
else:
assert Exception('Not Implemented consistency_loss') | null |
157,538 | import torch
import torch.nn.functional as F
from train_utils import ce_loss
import numpy as np
def ce_loss(logits, targets, use_hard_labels=True, reduction='none'):
"""
wrapper for cross entropy loss in pytorch.
Args
logits: logit values, shape=[Batch size, # of classes]
targets: integer or vector, shape=[Batch size] or [Batch size, # of classes]
use_hard_labels: If True, targets have [Batch size] shape with int values. If False, the target is vector (default True)
"""
if use_hard_labels:
log_pred = F.log_softmax(logits, dim=-1)
return F.nll_loss(log_pred, targets, reduction=reduction)
# return F.cross_entropy(logits, targets, reduction=reduction) this is unstable
else:
assert logits.shape == targets.shape
log_pred = F.log_softmax(logits, dim=-1)
nll_loss = torch.sum(-targets * log_pred, dim=1)
return nll_loss
def consistency_loss(logits_w, class_acc, it, ds, p_cutoff, use_flex=False):
pseudo_label = torch.softmax(logits_w, dim=-1)
max_probs, max_idx = torch.max(pseudo_label, dim=-1)
if use_flex:
mask = max_probs.ge(p_cutoff * (class_acc[max_idx] / (2. - class_acc[max_idx]))).float()
else:
mask = max_probs.ge(p_cutoff).float()
select = max_probs.ge(p_cutoff).long()
return (ce_loss(logits_w, max_idx.detach(), use_hard_labels=True,
reduction='none') * mask).mean(), select, max_idx.long() | null |
157,539 | import os
import logging
import random
import warnings
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.multiprocessing as mp
from utils import net_builder, get_logger, count_parameters, over_write_args_from_file
from train_utils import TBLog, get_optimizer, get_cosine_schedule_with_warmup
from models.remixmatch.remixmatch import ReMixMatch
from datasets.ssl_dataset import SSL_Dataset
from datasets.data_utils import get_data_loader
def net_builder(net_name, from_name: bool, net_conf=None, is_remix=False):
"""
return **class** of backbone network (not instance).
Args
net_name: 'WideResNet' or network names in torchvision.models
from_name: If True, net_buidler takes models in torch.vision models. Then, net_conf is ignored.
net_conf: When from_name is False, net_conf is the configuration of backbone network (now, only WRN is supported).
"""
if from_name:
import torchvision.models as models
model_name_list = sorted(name for name in models.__dict__
if name.islower() and not name.startswith("__")
and callable(models.__dict__[name]))
if net_name not in model_name_list:
assert Exception(f"[!] Networks\' Name is wrong, check net config, \
expected: {model_name_list} \
received: {net_name}")
else:
return models.__dict__[net_name]
else:
if net_name == 'WideResNet':
import models.nets.wrn as net
builder = getattr(net, 'build_WideResNet')()
elif net_name == 'WideResNetVar':
import models.nets.wrn_var as net
builder = getattr(net, 'build_WideResNetVar')()
elif net_name == 'ResNet50':
import models.nets.resnet50 as net
builder = getattr(net, 'build_ResNet50')(is_remix)
else:
assert Exception("Not Implemented Error")
if net_name != 'ResNet50':
setattr_cls_from_kwargs(builder, net_conf)
return builder.build
def get_logger(name, save_path=None, level='INFO'):
logger = logging.getLogger(name)
logger.setLevel(getattr(logging, level))
log_format = logging.Formatter('[%(asctime)s %(levelname)s] %(message)s')
streamHandler = logging.StreamHandler()
streamHandler.setFormatter(log_format)
logger.addHandler(streamHandler)
if not save_path is None:
os.makedirs(save_path, exist_ok=True)
fileHandler = logging.FileHandler(os.path.join(save_path, 'log.txt'))
fileHandler.setFormatter(log_format)
logger.addHandler(fileHandler)
return logger
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
class TBLog:
"""
Construc tensorboard writer (self.writer).
The tensorboard is saved at os.path.join(tb_dir, file_name).
"""
def __init__(self, tb_dir, file_name, use_tensorboard=False):
self.tb_dir = tb_dir
self.use_tensorboard = use_tensorboard
if self.use_tensorboard:
self.writer = SummaryWriter(os.path.join(self.tb_dir, file_name))
else:
self.writer = CustomWriter(os.path.join(self.tb_dir, file_name))
def update(self, tb_dict, it, suffix=None, mode="train"):
"""
Args
tb_dict: contains scalar values for updating tensorboard
it: contains information of iteration (int).
suffix: If not None, the update key has the suffix.
"""
if suffix is None:
suffix = ''
if self.use_tensorboard:
for key, value in tb_dict.items():
self.writer.add_scalar(suffix + key, value, it)
else:
self.writer.set_epoch(it, mode)
for key, value in tb_dict.items():
self.writer.add_scalar(suffix + key, value)
self.writer.plot_stats()
self.writer.dump_stats()
def get_optimizer(net, optim_name='SGD', lr=0.1, momentum=0.9, weight_decay=0, nesterov=True, bn_wd_skip=True):
'''
return optimizer (name) in torch.optim.
If bn_wd_skip, the optimizer does not apply
weight decay regularization on parameters in batch normalization.
'''
decay = []
no_decay = []
for name, param in net.named_parameters():
if ('bn' in name or 'bias' in name) and bn_wd_skip:
no_decay.append(param)
else:
decay.append(param)
per_param_args = [{'params': decay},
{'params': no_decay, 'weight_decay': 0.0}]
if optim_name == 'SGD':
optimizer = torch.optim.SGD(per_param_args, lr=lr, momentum=momentum, weight_decay=weight_decay,
nesterov=nesterov)
elif optim_name == 'AdamW':
optimizer = torch.optim.AdamW(per_param_args, lr=lr, weight_decay=weight_decay)
return optimizer
def get_cosine_schedule_with_warmup(optimizer,
num_training_steps,
num_cycles=7. / 16.,
num_warmup_steps=0,
last_epoch=-1):
'''
Get cosine scheduler (LambdaLR).
if warmup is needed, set num_warmup_steps (int) > 0.
'''
def _lr_lambda(current_step):
'''
_lr_lambda returns a multiplicative factor given an interger parameter epochs.
Decaying criteria: last_epoch
'''
if current_step < num_warmup_steps:
_lr = float(current_step) / float(max(1, num_warmup_steps))
else:
num_cos_steps = float(current_step - num_warmup_steps)
num_cos_steps = num_cos_steps / float(max(1, num_training_steps - num_warmup_steps))
_lr = max(0.0, math.cos(math.pi * num_cycles * num_cos_steps))
return _lr
return LambdaLR(optimizer, _lr_lambda, last_epoch)
class ReMixMatch:
def __init__(self, net_builder, num_classes, ema_m, T, lambda_u, \
w_match,
t_fn=None, it=0, num_eval_iter=1000, tb_log=None, logger=None):
"""
class Fixmatch contains setter of data_loader, optimizer, and model update methods.
Args:
net_builder: backbone network class (see net_builder in utils.py)
num_classes: # of label classes
ema_m: momentum of exponential moving average for eval_model
T: Temperature scaling parameter for output sharpening (only when hard_label = False)
p_cutoff: confidence cutoff parameters for loss masking
lambda_u: ratio of unsupervised loss to supervised loss
hard_label: If True, consistency regularization use a hard pseudo label.
it: initial iteration count
num_eval_iter: freqeuncy of iteration (after 500,000 iters)
tb_log: tensorboard writer (see train_utils.py)
logger: logger (see utils.py)
"""
super(ReMixMatch, self).__init__()
# momentum update param
self.loader = {}
self.num_classes = num_classes
self.ema_m = ema_m
# create the encoders
# network is builded only by num_classes,
# other configs are covered in main.py
self.model = net_builder(num_classes=num_classes)
self.ema_model = deepcopy(self.model)
self.num_eval_iter = num_eval_iter
self.t_fn = Get_Scalar(T) # temperature params function
self.w_match = w_match # weight of distribution matching
self.lambda_u = lambda_u
self.tb_log = tb_log
self.optimizer = None
self.scheduler = None
self.it = 0
self.logger = logger
self.print_fn = print if logger is None else logger.info
self.bn_controller = Bn_Controller()
def set_data_loader(self, loader_dict):
self.loader_dict = loader_dict
self.print_fn(f'[!] data loader keys: {self.loader_dict.keys()}')
def set_optimizer(self, optimizer, scheduler=None):
self.optimizer = optimizer
self.scheduler = scheduler
def train(self, args, logger=None):
ngpus_per_node = torch.cuda.device_count()
# EMA Init
self.model.train()
self.ema = EMA(self.model, self.ema_m)
self.ema.register()
if args.resume == True:
self.ema.load(self.ema_model)
# for gpu profiling
start_batch = torch.cuda.Event(enable_timing=True)
end_batch = torch.cuda.Event(enable_timing=True)
start_run = torch.cuda.Event(enable_timing=True)
end_run = torch.cuda.Event(enable_timing=True)
start_batch.record()
best_eval_acc, best_it = 0.0, 0
scaler = GradScaler()
amp_cm = autocast if args.amp else contextlib.nullcontext
# p(y) based on the labeled examples seen during training
dist_file_name = r"./data_statistics/" + args.dataset + '_' + str(args.num_labels) + '.json'
with open(dist_file_name, 'r') as f:
p_target = json.loads(f.read())
p_target = torch.tensor(p_target['distribution'])
p_target = p_target.cuda(args.gpu)
print('p_target:', p_target)
p_model = None
# eval for once to verify if the checkpoint is loaded correctly
if args.resume == True:
eval_dict = self.evaluate(args=args)
print(eval_dict)
# x_ulb_s1_rot: rotated data, rot_v: rot angles
for (_, x_lb, y_lb), (_, x_ulb_w, x_ulb_s1, x_ulb_s2, x_ulb_s1_rot, rot_v) in zip(self.loader_dict['train_lb'],
self.loader_dict[
'train_ulb']):
# prevent the training iterations exceed args.num_train_iter
if self.it > args.num_train_iter:
break
end_batch.record()
torch.cuda.synchronize()
start_run.record()
num_lb = x_lb.shape[0]
num_ulb = x_ulb_w.shape[0]
num_rot = x_ulb_s1_rot.shape[0]
assert num_ulb == x_ulb_s1.shape[0]
x_lb, x_ulb_w, x_ulb_s1, x_ulb_s2 = x_lb.cuda(args.gpu), x_ulb_w.cuda(args.gpu), x_ulb_s1.cuda(
args.gpu), x_ulb_s2.cuda(args.gpu)
x_ulb_s1_rot = x_ulb_s1_rot.cuda(args.gpu) # rot_image
rot_v = rot_v.cuda(args.gpu) # rot_label
y_lb = y_lb.cuda(args.gpu)
# inference and calculate sup/unsup losses
with amp_cm():
with torch.no_grad():
self.bn_controller.freeze_bn(self.model)
# logits_x_lb = self.model(x_lb)[0]
logits_x_ulb_w = self.model(x_ulb_w)[0]
# logits_x_ulb_s1 = self.model(x_ulb_s1)[0]
# logits_x_ulb_s2 = self.model(x_ulb_s2)[0]
self.bn_controller.unfreeze_bn(self.model)
# hyper-params for update
T = self.t_fn(self.it)
prob_x_ulb = torch.softmax(logits_x_ulb_w, dim=1)
# p^~_(y): moving average of p(y)
if p_model == None:
p_model = torch.mean(prob_x_ulb.detach(), dim=0)
else:
p_model = p_model * 0.999 + torch.mean(prob_x_ulb.detach(), dim=0) * 0.001
prob_x_ulb = prob_x_ulb * p_target / p_model
prob_x_ulb = (prob_x_ulb / prob_x_ulb.sum(dim=-1, keepdim=True))
sharpen_prob_x_ulb = prob_x_ulb ** (1 / T)
sharpen_prob_x_ulb = (sharpen_prob_x_ulb / sharpen_prob_x_ulb.sum(dim=-1, keepdim=True)).detach()
# mix up
mixed_inputs = torch.cat((x_lb, x_ulb_s1, x_ulb_s2, x_ulb_w))
input_labels = torch.cat(
[one_hot(y_lb, args.num_classes, args.gpu), sharpen_prob_x_ulb, sharpen_prob_x_ulb,
sharpen_prob_x_ulb], dim=0)
mixed_x, mixed_y, _ = mixup_one_target(mixed_inputs, input_labels,
args.gpu,
args.alpha,
is_bias=True)
# Interleave labeled and unlabeled samples between batches to get correct batch norm calculation
mixed_x = list(torch.split(mixed_x, num_lb))
mixed_x = self.interleave(mixed_x, num_lb)
# inter_inputs = torch.cat([mixed_x, x_ulb_s1], dim=0)
# inter_inputs = list(torch.split(inter_inputs, num_lb))
# inter_inputs = self.interleave(inter_inputs, num_lb)
# calculate BN only for the first batch
logits = [self.model(mixed_x[0])[0]]
self.bn_controller.freeze_bn(self.model)
for ipt in mixed_x[1:]:
logits.append(self.model(ipt)[0])
u1_logits = self.model(x_ulb_s1)[0]
logits_rot = self.model(x_ulb_s1_rot)[1]
logits = self.interleave(logits, num_lb)
self.bn_controller.unfreeze_bn(self.model)
logits_x = logits[0]
logits_u = torch.cat(logits[1:])
# calculate rot loss with w_rot
rot_loss = ce_loss(logits_rot, rot_v, reduction='mean')
rot_loss = rot_loss.mean()
# sup loss
sup_loss = ce_loss(logits_x, mixed_y[:num_lb], use_hard_labels=False)
sup_loss = sup_loss.mean()
# unsup_loss
unsup_loss = ce_loss(logits_u, mixed_y[num_lb:], use_hard_labels=False)
unsup_loss = unsup_loss.mean()
# loss U1
u1_loss = ce_loss(u1_logits, sharpen_prob_x_ulb, use_hard_labels=False)
u1_loss = u1_loss.mean()
# ramp for w_match
w_match = args.w_match * float(np.clip(self.it / (args.warm_up * args.num_train_iter), 0.0, 1.0))
w_kl = args.w_kl * float(np.clip(self.it / (args.warm_up * args.num_train_iter), 0.0, 1.0))
total_loss = sup_loss + args.w_rot * rot_loss + w_kl * u1_loss + w_match * unsup_loss
# parameter updates
if args.amp:
scaler.scale(total_loss).backward()
if (args.clip > 0):
scaler.unscale_(self.optimizer)
torch.nn.utils.clip_grad_norm_(self.model.parameters(), args.clip)
scaler.step(self.optimizer)
scaler.update()
else:
total_loss.backward()
if (args.clip > 0):
torch.nn.utils.clip_grad_norm_(self.model.parameters(), args.clip)
self.optimizer.step()
self.scheduler.step()
self.ema.update()
self.model.zero_grad()
end_run.record()
torch.cuda.synchronize()
# tensorboard_dict update
tb_dict = {}
tb_dict['train/sup_loss'] = sup_loss.detach()
tb_dict['train/unsup_loss'] = unsup_loss.detach()
tb_dict['train/total_loss'] = total_loss.detach()
tb_dict['lr'] = self.optimizer.param_groups[0]['lr']
tb_dict['train/prefecth_time'] = start_batch.elapsed_time(end_batch) / 1000.
tb_dict['train/run_time'] = start_run.elapsed_time(end_run) / 1000.
# Save model for each 10K steps and best model for each 1K steps
if self.it % 10000 == 0:
save_path = os.path.join(args.save_dir, args.save_name)
if not args.multiprocessing_distributed or \
(args.multiprocessing_distributed and args.rank % ngpus_per_node == 0):
self.save_model('latest_model.pth', save_path)
if self.it % self.num_eval_iter == 0:
eval_dict = self.evaluate(args=args)
tb_dict.update(eval_dict)
save_path = os.path.join(args.save_dir, args.save_name)
if tb_dict['eval/top-1-acc'] > best_eval_acc:
best_eval_acc = tb_dict['eval/top-1-acc']
best_it = self.it
self.print_fn(
f"{self.it} iteration, USE_EMA: {self.ema_m != 0}, {tb_dict}, BEST_EVAL_ACC: {best_eval_acc}, at {best_it} iters")
total_time = 0
if not args.multiprocessing_distributed or \
(args.multiprocessing_distributed and args.rank % ngpus_per_node == 0):
if self.it == best_it:
self.save_model('model_best.pth', save_path)
if not self.tb_log is None:
self.tb_log.update(tb_dict, self.it)
self.it += 1
del tb_dict
start_batch.record()
if self.it > 0.8 * args.num_train_iter:
self.num_eval_iter = 1000
eval_dict = self.evaluate(args=args)
eval_dict.update({'eval/best_acc': best_eval_acc, 'eval/best_it': best_it})
return eval_dict
def evaluate(self, eval_loader=None, args=None):
self.model.eval()
self.ema.apply_shadow()
if eval_loader is None:
eval_loader = self.loader_dict['eval']
total_loss = 0.0
total_num = 0.0
y_true = []
y_pred = []
y_logits = []
for _, x, y in eval_loader:
x, y = x.cuda(args.gpu), y.cuda(args.gpu)
num_batch = x.shape[0]
total_num += num_batch
logits, _ = self.model(x)
loss = F.cross_entropy(logits, y, reduction='mean')
y_true.extend(y.cpu().tolist())
y_pred.extend(torch.max(logits, dim=-1)[1].cpu().tolist())
y_logits.extend(torch.softmax(logits, dim=-1).cpu().tolist())
total_loss += loss.detach() * num_batch
top1 = accuracy_score(y_true, y_pred)
top5 = top_k_accuracy_score(y_true, y_logits, k=5)
cf_mat = confusion_matrix(y_true, y_pred, normalize='true')
self.print_fn('confusion matrix:\n' + np.array_str(cf_mat))
self.ema.restore()
self.model.train()
return {'eval/loss': total_loss / total_num, 'eval/top-1-acc': top1, 'eval/top-5-acc': top5}
def save_model(self, save_name, save_path):
if self.it < 1000000:
return
save_filename = os.path.join(save_path, save_name)
# copy EMA parameters to ema_model for saving with model as temp
self.model.eval()
self.ema.apply_shadow()
ema_model = deepcopy(self.model)
self.ema.restore()
self.model.train()
torch.save({'model': self.model.state_dict(),
'optimizer': self.optimizer.state_dict(),
'scheduler': self.scheduler.state_dict(),
'it': self.it + 1,
'ema_model': ema_model.state_dict()},
save_filename)
self.print_fn(f"model saved: {save_filename}")
def load_model(self, load_path):
checkpoint = torch.load(load_path)
self.model.load_state_dict(checkpoint['model'])
self.optimizer.load_state_dict(checkpoint['optimizer'])
self.scheduler.load_state_dict(checkpoint['scheduler'])
self.it = checkpoint['it']
self.ema_model.load_state_dict(checkpoint['ema_model'])
self.print_fn('model loaded')
def interleave_offsets(self, batch, nu):
groups = [batch // (nu + 1)] * (nu + 1)
for x in range(batch - sum(groups)):
groups[-x - 1] += 1
offsets = [0]
for g in groups:
offsets.append(offsets[-1] + g)
assert offsets[-1] == batch
return offsets
def interleave(self, xy, batch):
nu = len(xy) - 1
offsets = self.interleave_offsets(batch, nu)
xy = [[v[offsets[p]:offsets[p + 1]] for p in range(nu + 1)] for v in xy]
for i in range(1, nu + 1):
xy[0][i], xy[i][i] = xy[i][i], xy[0][i]
return [torch.cat(v, dim=0) for v in xy]
class SSL_Dataset:
"""
SSL_Dataset class gets dataset from torchvision.datasets,
separates labeled and unlabeled data,
and return BasicDataset: torch.utils.data.Dataset (see datasets.dataset.py)
"""
def __init__(self,
args,
alg='fixmatch',
name='cifar10',
train=True,
num_classes=10,
data_dir='./data'):
"""
Args
alg: SSL algorithms
name: name of dataset in torchvision.datasets (cifar10, cifar100, svhn, stl10)
train: True means the dataset is training dataset (default=True)
num_classes: number of label classes
data_dir: path of directory, where data is downloaed or stored.
"""
self.args = args
self.alg = alg
self.name = name
self.train = train
self.num_classes = num_classes
self.data_dir = data_dir
crop_size = 96 if self.name.upper() == 'STL10' else 224 if self.name.upper() == 'IMAGENET' else 32
self.transform = get_transform(mean[name], std[name], crop_size, train)
def get_data(self, svhn_extra=True):
"""
get_data returns data (images) and targets (labels)
shape of data: B, H, W, C
shape of labels: B,
"""
dset = getattr(torchvision.datasets, self.name.upper())
if 'CIFAR' in self.name.upper():
dset = dset(self.data_dir, train=self.train, download=True)
data, targets = dset.data, dset.targets
return data, targets
elif self.name.upper() == 'SVHN':
if self.train:
if svhn_extra: # train+extra
dset_base = dset(self.data_dir, split='train', download=True)
data_b, targets_b = dset_base.data.transpose([0, 2, 3, 1]), dset_base.labels
dset_extra = dset(self.data_dir, split='extra', download=True)
data_e, targets_e = dset_extra.data.transpose([0, 2, 3, 1]), dset_extra.labels
data = np.concatenate([data_b, data_e])
targets = np.concatenate([targets_b, targets_e])
del data_b, data_e
del targets_b, targets_e
else: # train_only
dset = dset(self.data_dir, split='train', download=True)
data, targets = dset.data.transpose([0, 2, 3, 1]), dset.labels
else: # test
dset = dset(self.data_dir, split='test', download=True)
data, targets = dset.data.transpose([0, 2, 3, 1]), dset.labels
return data, targets
elif self.name.upper() == 'STL10':
split = 'train' if self.train else 'test'
dset_lb = dset(self.data_dir, split=split, download=True)
dset_ulb = dset(self.data_dir, split='unlabeled', download=True)
data, targets = dset_lb.data.transpose([0, 2, 3, 1]), dset_lb.labels.astype(np.int64)
ulb_data = dset_ulb.data.transpose([0, 2, 3, 1])
return data, targets, ulb_data
def get_dset(self, is_ulb=False,
strong_transform=None, onehot=False):
"""
get_dset returns class BasicDataset, containing the returns of get_data.
Args
is_ulb: If True, returned dataset generates a pair of weak and strong augmented images.
strong_transform: list of strong_transform (augmentation) if use_strong_transform is True。
onehot: If True, the label is not integer, but one-hot vector.
"""
if self.name.upper() == 'STL10':
data, targets, _ = self.get_data()
else:
data, targets = self.get_data()
num_classes = self.num_classes
transform = self.transform
return BasicDataset(self.alg, data, targets, num_classes, transform,
is_ulb, strong_transform, onehot)
def get_ssl_dset(self, num_labels, index=None, include_lb_to_ulb=True,
strong_transform=None, onehot=False):
"""
get_ssl_dset split training samples into labeled and unlabeled samples.
The labeled data is balanced samples over classes.
Args:
num_labels: number of labeled data.
index: If index of np.array is given, labeled data is not randomly sampled, but use index for sampling.
include_lb_to_ulb: If True, consistency regularization is also computed for the labeled data.
strong_transform: list of strong transform (RandAugment in FixMatch)
onehot: If True, the target is converted into onehot vector.
Returns:
BasicDataset (for labeled data), BasicDataset (for unlabeld data)
"""
# Supervised top line using all data as labeled data.
if self.alg == 'fullysupervised':
lb_data, lb_targets = self.get_data()
lb_dset = BasicDataset(self.alg, lb_data, lb_targets, self.num_classes,
self.transform, False, None, onehot)
return lb_dset, None
if self.name.upper() == 'STL10':
lb_data, lb_targets, ulb_data = self.get_data()
if include_lb_to_ulb:
ulb_data = np.concatenate([ulb_data, lb_data], axis=0)
lb_data, lb_targets, _ = sample_labeled_data(self.args, lb_data, lb_targets, num_labels, self.num_classes)
ulb_targets = None
else:
data, targets = self.get_data()
lb_data, lb_targets, ulb_data, ulb_targets = split_ssl_data(self.args, data, targets,
num_labels, self.num_classes,
index, include_lb_to_ulb)
# output the distribution of labeled data for remixmatch
count = [0 for _ in range(self.num_classes)]
for c in lb_targets:
count[c] += 1
dist = np.array(count, dtype=float)
dist = dist / dist.sum()
dist = dist.tolist()
out = {"distribution": dist}
output_file = r"./data_statistics/"
output_path = output_file + str(self.name) + '_' + str(num_labels) + '.json'
if not os.path.exists(output_file):
os.makedirs(output_file, exist_ok=True)
with open(output_path, 'w') as w:
json.dump(out, w)
# print(Counter(ulb_targets.tolist()))
lb_dset = BasicDataset(self.alg, lb_data, lb_targets, self.num_classes,
self.transform, False, None, onehot)
ulb_dset = BasicDataset(self.alg, ulb_data, ulb_targets, self.num_classes,
self.transform, True, strong_transform, onehot)
# print(lb_data.shape)
# print(ulb_data.shape)
return lb_dset, ulb_dset
def get_data_loader(dset,
batch_size=None,
shuffle=False,
num_workers=4,
pin_memory=False,
data_sampler=None,
replacement=True,
num_epochs=None,
num_iters=None,
generator=None,
drop_last=True,
distributed=False):
"""
get_data_loader returns torch.utils.data.DataLoader for a Dataset.
All arguments are comparable with those of pytorch DataLoader.
However, if distributed, DistributedProxySampler, which is a wrapper of data_sampler, is used.
Args
num_epochs: total batch -> (# of batches in dset) * num_epochs
num_iters: total batch -> num_iters
"""
assert batch_size is not None
if data_sampler is None:
return DataLoader(dset, batch_size=batch_size, shuffle=shuffle,
num_workers=num_workers, pin_memory=pin_memory)
else:
if isinstance(data_sampler, str):
data_sampler = get_sampler_by_name(data_sampler)
if distributed:
assert dist.is_available()
num_replicas = dist.get_world_size()
else:
num_replicas = 1
if (num_epochs is not None) and (num_iters is None):
num_samples = len(dset) * num_epochs
elif (num_epochs is None) and (num_iters is not None):
num_samples = batch_size * num_iters * num_replicas
else:
num_samples = len(dset)
if data_sampler.__name__ == 'RandomSampler':
data_sampler = data_sampler(dset, replacement, num_samples, generator)
else:
raise RuntimeError(f"{data_sampler.__name__} is not implemented.")
if distributed:
'''
Different with DistributedSampler,
the DistribuedProxySampler does not shuffle the data (just wrapper for dist).
'''
data_sampler = DistributedProxySampler(data_sampler)
batch_sampler = BatchSampler(data_sampler, batch_size, drop_last)
return DataLoader(dset, batch_sampler=batch_sampler,
num_workers=num_workers, pin_memory=pin_memory)
The provided code snippet includes necessary dependencies for implementing the `main_worker` function. Write a Python function `def main_worker(gpu, ngpus_per_node, args)` to solve the following problem:
main_worker is conducted on each GPU.
Here is the function:
def main_worker(gpu, ngpus_per_node, args):
'''
main_worker is conducted on each GPU.
'''
global best_acc1
args.gpu = gpu
# random seed has to be set for the syncronization of labeled data sampling in each process.
assert args.seed is not None
random.seed(args.seed)
torch.manual_seed(args.seed)
np.random.seed(args.seed)
cudnn.deterministic = True
# SET UP FOR DISTRIBUTED TRAINING
if args.distributed:
if args.dist_url == "env://" and args.rank == -1:
args.rank = int(os.environ["RANK"])
if args.multiprocessing_distributed:
args.rank = args.rank * ngpus_per_node + gpu # compute global rank
# set distributed group:
dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
world_size=args.world_size, rank=args.rank)
# SET save_path and logger
save_path = os.path.join(args.save_dir, args.save_name)
logger_level = "WARNING"
tb_log = None
if args.rank % ngpus_per_node == 0:
tb_log = TBLog(save_path, 'tensorboard', use_tensorboard=args.use_tensorboard)
logger_level = "INFO"
logger = get_logger(args.save_name, save_path, logger_level)
logger.warning(f"USE GPU: {args.gpu} for training")
# SET RemixMatch: class RemixMatch in models.remixmatch
args.bn_momentum = 1.0 - 0.999
if 'imagenet' in args.dataset.lower():
_net_builder = net_builder('ResNet50', False, None, is_remix=True)
else:
_net_builder = net_builder(args.net,
args.net_from_name,
{'first_stride': 2 if 'stl' in args.dataset else 1,
'depth': args.depth,
'widen_factor': args.widen_factor,
'leaky_slope': args.leaky_slope,
'bn_momentum': args.bn_momentum,
'dropRate': args.dropout,
'use_embed': False,
'is_remix': True},
)
model = ReMixMatch(_net_builder,
args.num_classes,
args.ema_m,
args.T,
args.ulb_loss_ratio,
num_eval_iter=args.num_eval_iter,
tb_log=tb_log,
logger=logger,
w_match=args.w_match,
)
logger.info(f'Number of Trainable Params: {count_parameters(model.model)}')
# SET Optimizer & LR Scheduler
## construct SGD and cosine lr scheduler
optimizer = get_optimizer(model.model, args.optim, args.lr, args.momentum, args.weight_decay)
scheduler = get_cosine_schedule_with_warmup(optimizer,
args.num_train_iter,
num_warmup_steps=args.num_train_iter * 0)
## set SGD and cosine lr on RemixMatch
model.set_optimizer(optimizer, scheduler)
# SET Devices for (Distributed) DataParallel
if not torch.cuda.is_available():
raise Exception('ONLY GPU TRAINING IS SUPPORTED')
elif args.distributed:
if args.gpu is not None:
torch.cuda.set_device(args.gpu)
'''
batch_size: batch_size per node -> batch_size per gpu
workers: workers per node -> workers per gpu
'''
args.batch_size = int(args.batch_size / ngpus_per_node)
model.model.cuda(args.gpu)
model.model = torch.nn.parallel.DistributedDataParallel(model.model,
device_ids=[args.gpu],
broadcast_buffers=False,
find_unused_parameters=True)
else:
# if arg.gpu is None, DDP will divide and allocate batch_size
# to all available GPUs if device_ids are not set.
model.cuda()
model = torch.nn.parallel.DistributedDataParallel(model)
elif args.gpu is not None:
torch.cuda.set_device(args.gpu)
model.model = model.model.cuda(args.gpu)
else:
model.model = torch.nn.DataParallel(model.model).cuda()
import copy
model.ema_model = copy.deepcopy(model.model)
logger.info(f"model_arch: {model}")
logger.info(f"Arguments: {args}")
cudnn.benchmark = True
if args.rank != 0 and args.distributed:
torch.distributed.barrier()
# Construct Dataset & DataLoader
if args.dataset != "imagenet":
if args.num_labels == 10 and args.dataset == 'cifar10':
fixmatch_index = [
[7408, 8148, 9850, 10361, 33949, 36506, 37018, 45044, 46443, 47447],
[5022, 8193, 8902, 9601, 25226, 26223, 34089, 35186, 40595, 48024],
[7510, 13186, 14043, 21305, 22805, 31288, 34508, 40470, 41493, 45506],
[9915, 9978, 16631, 19915, 28008, 35314, 35801, 36149, 39215, 42557],
[6695, 14891, 19726, 22715, 23999, 34230, 46511, 47457, 49181, 49397],
[12830, 20293, 26835, 30517, 30898, 31061, 43693, 46501, 47310, 48517],
[1156, 11501, 19974, 21963, 32103, 42189, 46789, 47690, 48229, 48675],
[4255, 6446, 8580, 11759, 12598, 29349, 29433, 33759, 35345, 38639]]
index = fixmatch_index[-args.seed - 1]
print("10 labels for cifar10")
else:
index = None
train_dset = SSL_Dataset(args, alg='remixmatch', name=args.dataset, train=True,
num_classes=args.num_classes, data_dir=args.data_dir)
lb_dset, ulb_dset = train_dset.get_ssl_dset(args.num_labels,index=index)
_eval_dset = SSL_Dataset(args, alg='remixmatch', name=args.dataset, train=False,
num_classes=args.num_classes, data_dir=args.data_dir)
eval_dset = _eval_dset.get_dset()
if args.rank == 0 and args.distributed:
torch.distributed.barrier()
loader_dict = {}
dset_dict = {'train_lb': lb_dset, 'train_ulb': ulb_dset, 'eval': eval_dset}
loader_dict['train_lb'] = get_data_loader(dset_dict['train_lb'],
args.batch_size,
data_sampler=args.train_sampler,
num_iters=args.num_train_iter,
num_workers=args.num_workers,
distributed=args.distributed)
loader_dict['train_ulb'] = get_data_loader(dset_dict['train_ulb'],
args.batch_size * args.uratio,
data_sampler=args.train_sampler,
num_iters=args.num_train_iter,
num_workers=4 * args.num_workers,
distributed=args.distributed)
loader_dict['eval'] = get_data_loader(dset_dict['eval'],
args.eval_batch_size,
num_workers=args.num_workers,
drop_last=False)
## set DataLoader on RemixMatch
model.set_data_loader(loader_dict)
# If args.resume, load checkpoints from args.load_path
if args.resume:
model.load_model(args.load_path)
# START TRAINING of RemixMatch
trainer = model.train
for epoch in range(args.epoch):
trainer(args, logger=logger)
if not args.multiprocessing_distributed or \
(args.multiprocessing_distributed and args.rank % ngpus_per_node == 0):
model.save_model('latest_model.pth', save_path)
logging.warning(f"GPU {args.rank} training is FINISHED") | main_worker is conducted on each GPU. |
157,540 | import os
import logging
import random
import warnings
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.multiprocessing as mp
from utils import net_builder, get_logger, count_parameters, over_write_args_from_file
from train_utils import TBLog, get_optimizer, get_cosine_schedule_with_warmup
from models.remixmatch.remixmatch import ReMixMatch
from datasets.ssl_dataset import SSL_Dataset
from datasets.data_utils import get_data_loader
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.') | null |
157,541 | import random
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
def to_float(x):
return x.cpu().detach().numpy().flatten()[0].astype(float) | null |
157,542 | import random
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda:
torch.cuda.manual_seed_all(seed) | null |
157,543 | import json, math
import random
import numpy as np
import torch
from torch.nn import functional as F
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed) | null |
157,544 | import numpy as np
import types
import os
import torch
import array
from torch.nn import functional as F
import torch.nn as nn
def to_float(x):
return x.cpu().detach().squeeze().numpy() | null |
157,545 | print('\nAI人工智障写作 https://github.com/BlinkDL/AI-Writer')
print('如果觉得好用,欢迎选购我们的护眼灯 https://withablink.taobao.com')
print('我的知乎是 https://zhuanlan.zhihu.com/p/423646620')
print('\n声明:模型的训练数据来自网文,缺乏生活常识。生成的文字仅供娱乐。请遵守法律法规。')
import sys, os, time, datetime
import numpy as np
import time
import numpy as np
import torch
from src.model import RWKV_RNN, RWKV_CFG
from src.utils import CHN_TOKENIZER
np.set_printoptions(precision=4, suppress=True, linewidth=200)
cfg = RWKV_CFG('L24_CHN', 'all-44704')
cfg.RUN_DEVICE = 'cuda'\n正在使用 {cfg.RUN_DEVICE} 模式\n')
NUM_OF_RUNS = 33
LENGTH_OF_EACH = 333
TEMPERATURE = 1.0
top_p_newline = 0.9
top_p = 0.7
allow_p = 0.01len(context) + LENGTH_OF_EACH >= cfg.ctx_len:
print('总长度过长,请缩短续写长度和原文长度。')
exit(0)
tokenizer = CHN_TOKENIZER(WORD_NAME='word-2022-02-16', UNKNOWN_CHAR='\ue083')
cfg.vocab_size = tokenizer.vocab_size
model = RWKV_RNN(cfg)
model.tokenizer = tokenizer
def ai_print(str):
print('\n')
def run(context):
context = '\n' + tokenizer.refine_context(context).strip()
print(f'开头有 {str(len(context))} 字,写 {NUM_OF_RUNS} 次,每次 {LENGTH_OF_EACH} 字。\n')
for run in range(NUM_OF_RUNS):
print('-' * 20 + '\x1B[93m' + context.replace('\n', '\n '), end = '\x1B[37m')
t_begin = time.time_ns()
x = np.array([tokenizer.stoi.get(s, tokenizer.UNKNOWN_CHAR) for s in context], dtype=np.int64)
real_len = len(x)
print_begin = 0
for i in range(LENGTH_OF_EACH):
if i == 0:
print_begin = real_len
with torch.no_grad():
xin = x[-cfg.ctx_len-1:]
out = model.run(xin)
char = tokenizer.sample_logits(out, xin.tolist(), cfg.ctx_len, temperature=TEMPERATURE, top_p_usual=top_p, top_p_newline=top_p_newline, allow_p=allow_p)
x = np.append(x, char)
real_len += 1
if i % 2 == 0 or i == LENGTH_OF_EACH-1 or i < 10:
completion = ''.join([tokenizer.itos[int(i)] for i in x[print_begin:real_len]])
ai_print(completion.replace('\n', '\n '))
print_begin = real_len
print()
t_end = time.time_ns()
print(f"---------- {round((t_end - t_begin) / (10 ** 9), 2)} s, 第 {run+1}/{NUM_OF_RUNS} 次", end='') | null |
157,546 | import math
import json
import random
import time
_DEBUG_LEVEL_ = 2
PORT_NUM = 8266
def SocketWorker(queueX, queueZ):
import asyncio
import websockets
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
USERS = set()
async def producer():
hasData = False
try:
K, out = queueX.get(timeout=0.05)
hasData = True
except:
pass
if hasData:
return (K, out)
else:
await asyncio.sleep(0.001)
if random.random() < -0.003:
return '[PING]'
else:
return ''
async def producer_handler(websocket, path):
while True:
msg = await producer()
if isinstance(msg, tuple):
K, msg = msg
for x in USERS:
if x.client_id == K:
# if _DEBUG_LEVEL_ > 0:
# print('sent X', K)
await x.send(msg)
break
elif msg != '':
await websocket.send(msg)
async def consumer(websocket, msg):
if msg == '[PONG]':
return
try:
msg = json.loads(msg)
if msg['op'].lower() == 'get':
# if _DEBUG_LEVEL_ > 0:
# print('get', websocket.client_id, msg['txt'])
queueZ.put((websocket.client_id, msg['txt']))
except Exception as e:
print(e)
pass
async def consumer_handler(websocket, path):
while True:
msg = await websocket.recv()
await consumer(websocket, msg)
async def server(websocket, path):
websocket.client_id = '%020x' % random.randrange(16**20)
USERS.add(websocket)
print("[ws connect]", len(USERS), 'users @',
time.strftime("%Y %b %d %H:%M:%S", time.localtime(time.time())))
try:
await websocket.send('id_' + websocket.client_id)
consumer_task = asyncio.ensure_future(
consumer_handler(websocket, path))
producer_task = asyncio.ensure_future(
producer_handler(websocket, path))
done, pending = await asyncio.wait(
[consumer_task, producer_task],
return_when=asyncio.FIRST_COMPLETED)
for task in pending:
task.cancel()
finally:
USERS.remove(websocket)
print("[ws disconnect]", len(USERS))
def srv_exception(loop, context):
if _DEBUG_LEVEL_ > 1:
print('exception', loop, context)
pass
try:
start_server = websockets.serve(server, "127.0.0.1", PORT_NUM)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().set_exception_handler(srv_exception)
asyncio.get_event_loop().run_forever()
except Exception as e:
print('[srv error]', e) | null |
157,547 | import math
import json
import random
import time
_DEBUG_LEVEL_ = 2
n_layer = 12
n_head = 12
n_embd = n_head * 64
n_attn = n_embd
n_ffn = n_embd
class GPTConfig:
def __init__(self, vocab_size, ctx_len, **kwargs):
self.vocab_size = vocab_size
self.ctx_len = ctx_len
for k, v in kwargs.items():
setattr(self, k, v)
class GPT(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.tok_emb = nn.Embedding(config.vocab_size, config.n_embd)
self.blocks = nn.Sequential(*[Block(config, i)
for i in range(config.n_layer)])
self.ln_f = nn.LayerNorm(config.n_embd)
self.time_out = nn.Parameter(torch.ones(1, config.ctx_len, 1))
self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
self.head_q = nn.Linear(config.n_embd, 256)
self.head_k = nn.Linear(config.n_embd, 256)
self.register_buffer("copy_mask", torch.tril(torch.ones(config.ctx_len, config.ctx_len)))
self.ctx_len = config.ctx_len
logger.info("number of parameters: %e", sum(p.numel()
for p in self.parameters()))
def get_ctx_len(self):
return self.ctx_len
def forward(self, idx, targets=None):
B, T = idx.size()
assert T <= self.ctx_len, "Cannot forward, because len(input) > model ctx_len."
x = self.tok_emb(idx)
x = self.blocks(x)
x = self.ln_f(x)
q = self.head_q(x)[:,:T,:]
k = self.head_k(x)[:,:T,:]
c = (q @ k.transpose(-2, -1)) * (1.0 / 256)
c = c.masked_fill(self.copy_mask[:T,:T] == 0, 0)
c = c @ F.one_hot(idx, num_classes = self.config.vocab_size).float()
x = x * self.time_out[:, :T, :]
x = self.head(x) + c
loss = None
if targets is not None:
loss = F.cross_entropy(x.view(-1, x.size(-1)), targets.view(-1))
return x, loss
def NeuralWorker(queueZ, queueX):
from multiprocessing import Process, RawArray, freeze_support, Queue, Lock
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
import src.utils
from src.model import GPT, GPTConfig
# src.utils.set_seed(42) # 是否固定随机数(固定后每次运行的生成结果都一样)
print('\nAI人工智障写作 https://github.com/BlinkDL/AI-Writer')
print('请关注我的知乎 https://zhuanlan.zhihu.com/p/423646620')
print('\n声明:模型的训练数据全部来自网文,缺乏生活常识。生成的文字仅供娱乐。请遵守法律法规。')
print(f'\nLoading model for {RUN_DEVICE}...', end=' ')
with open(WORD_NAME + '.json', "r", encoding="utf-16") as result_file:
word_table = json.load(result_file)
vocab_size = len(word_table)
def train_dataset(): return None
train_dataset.stoi = {v: int(k) for k, v in word_table.items()}
train_dataset.itos = {int(k): v for k, v in word_table.items()}
UNKNOWN_CHAR = train_dataset.stoi['\ue083']
if RUN_DEVICE == 'dml':
import onnxruntime as rt
sess_options = rt.SessionOptions()
sess_options.graph_optimization_level = rt.GraphOptimizationLevel.ORT_ENABLE_ALL
sess_options.execution_mode = rt.ExecutionMode.ORT_SEQUENTIAL
sess_options.enable_mem_pattern = False
rt_session = rt.InferenceSession(MODEL_NAME + '.onnx', sess_options=sess_options, providers=['DmlExecutionProvider'])
rt_session.set_providers(['DmlExecutionProvider'])
else:
model = GPT(GPTConfig(vocab_size, ctx_len, n_layer=n_layer, n_head=n_head, n_embd=n_embd, n_attn=n_attn, n_ffn=n_ffn))
m2 = torch.load(MODEL_NAME + '.pth', map_location='cpu').state_dict()
for i in range(n_layer):
prefix = f'blocks.{i}.attn.'
time_w = m2[prefix + 'time_w']
time_alpha = m2[prefix + 'time_alpha']
time_beta = m2[prefix + 'time_beta']
TT = ctx_len
T = ctx_len
w = F.pad(time_w, (0, TT))
w = torch.tile(w, [TT])
w = w[:, :-TT].reshape(-1, TT, 2 * TT - 1)
w = w[:, :, TT-1:]
w = w[:, :T, :T] * time_alpha[:, :, :T] * time_beta[:, :T, :]
m2[prefix + 'time_ww'] = w
del m2[prefix + 'time_w']
del m2[prefix + 'time_alpha']
del m2[prefix + 'time_beta']
if RUN_DEVICE == 'gpu':
model = model.cuda()
model.load_state_dict(m2)
print('done:', MODEL_NAME, '&', WORD_NAME)
while True:
K, Z = queueZ.get()
# print('neural task', K, Z)
ttt = time.time()
context = Z
context = context.strip().split('\n')
for c in range(len(context)):
context[c] = context[c].strip().strip('\u3000').strip('\r')
context = list(filter(lambda c: c != '', context))
context = '\n' + ('\n'.join(context)).strip()
# print('您输入的开头有 ' + str(len(context)) +
# ' 个字。注意,模型只会看最后 ' + str(ctx_len) + ' 个字。')
NUM_OF_RUNS = 1
for run in range(NUM_OF_RUNS):
x = np.array([train_dataset.stoi.get(s, UNKNOWN_CHAR)
for s in context], dtype=np.int64)
real_len = len(x)
print_begin = 0
out_txt = ''
for i in range(LENGTH_OF_EACH):
if i == 0:
print_begin = real_len
with torch.no_grad():
if RUN_DEVICE == 'dml':
if real_len < ctx_len:
xxx = np.pad(x, (0, ctx_len - real_len))
else:
xxx = x
out = rt_session.run(None, {rt_session.get_inputs()[0].name: [xxx[-ctx_len:]]})
out = torch.tensor(out[0])
else:
xxx = torch.tensor(x[-ctx_len:], dtype=torch.long)[None,...]
if RUN_DEVICE == 'gpu':
xxx = xxx.cuda()
out, _ = model(xxx)
out[:, :, UNKNOWN_CHAR] = -float('Inf')
pos = -1 if real_len >= ctx_len else real_len - 1
if train_dataset.itos[int(x[real_len-1])] == '\n':
char = src.utils.sample_logits(out, pos, temperature=1.0, top_p=top_p_newline)
else:
char = src.utils.sample_logits(out, pos, temperature=1.0, top_p=top_p)
x = np.append(x, char)
real_len += 1
completion = ''.join([train_dataset.itos[int(i)]
for i in x[print_begin:real_len]])
out_txt += completion
print_begin = real_len
outmsg = {}
outmsg['op'] = 'TXT'
outmsg['txt'] = out_txt
queueX.put((K, json.dumps(outmsg, separators=(',', ':'))))
# if _DEBUG_LEVEL_ > 1:
# print(time.time() - ttt, end=' ')
ttt = time.time()
if _DEBUG_LEVEL_ > 1:
print(context, end = '')
print(out_txt + '\n' + ('=' * 20)) | null |
157,548 | import re
from distutils.command.build import build
from glob import glob
from itertools import chain
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import Command
from setuptools import find_packages
from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.easy_install import easy_install
from setuptools.command.install_lib import install_lib
def read(*names, **kwargs):
with open(
join(dirname(__file__), *names),
encoding=kwargs.get('encoding', 'utf8')
) as fh:
return fh.read() | null |
157,549 | import os
import subprocess
import sys
from collections import defaultdict
from os.path import abspath
from os.path import dirname
from os.path import exists
from os.path import join
base_path = dirname(dirname(abspath(__file__)))
def check_call(args):
print("+", *args)
subprocess.check_call(args)
def exec_in_env():
env_path = join(base_path, ".tox", "bootstrap")
if sys.platform == "win32":
bin_path = join(env_path, "Scripts")
else:
bin_path = join(env_path, "bin")
if not exists(env_path):
import subprocess
print(f"Making bootstrap env in: {env_path} ...")
try:
check_call([sys.executable, "-m", "venv", env_path])
except subprocess.CalledProcessError:
try:
check_call([sys.executable, "-m", "virtualenv", env_path])
except subprocess.CalledProcessError:
check_call(["virtualenv", env_path])
print("Installing `jinja2` into bootstrap environment...")
check_call([join(bin_path, "pip"), "install", "jinja2", "tox"])
python_executable = join(bin_path, "python")
if not os.path.exists(python_executable):
python_executable += '.exe'
print(f"Re-executing with: {python_executable}")
print("+ exec", python_executable, __file__, "--no-env")
os.execv(python_executable, [python_executable, __file__, "--no-env"]) | null |
157,550 | import os
def find_user_home_path():
with open(os.path.expanduser("~/.yagmail")) as f:
return f.read().strip() | null |
157,551 | from yagmail.sender import SMTP
import sys
try:
import keyring
except (ImportError, NameError, RuntimeError):
pass
The provided code snippet includes necessary dependencies for implementing the `register` function. Write a Python function `def register(username, password)` to solve the following problem:
Use this to add a new gmail account to your OS' keyring so it can be used in yagmail
Here is the function:
def register(username, password):
""" Use this to add a new gmail account to your OS' keyring so it can be used in yagmail """
keyring.set_password("yagmail", username, password) | Use this to add a new gmail account to your OS' keyring so it can be used in yagmail |
157,552 | import re
VALID_ADDRESS_REGEXP = '^' + ADDR_SPEC + '$'
class YagInvalidEmailAddress(Exception):
"""
Note that this will only filter out syntax mistakes in emailaddresses.
If a human would think it is probably a valid email, it will most likely pass.
However, it could still very well be that the actual emailaddress has simply
not be claimed by anyone (so then this function fails to devalidate).
"""
pass
The provided code snippet includes necessary dependencies for implementing the `validate_email_with_regex` function. Write a Python function `def validate_email_with_regex(email_address)` to solve the following problem:
Note that this will only filter out syntax mistakes in emailaddresses. If a human would think it is probably a valid email, it will most likely pass. However, it could still very well be that the actual emailaddress has simply not be claimed by anyone (so then this function fails to devalidate).
Here is the function:
def validate_email_with_regex(email_address):
"""
Note that this will only filter out syntax mistakes in emailaddresses.
If a human would think it is probably a valid email, it will most likely pass.
However, it could still very well be that the actual emailaddress has simply
not be claimed by anyone (so then this function fails to devalidate).
"""
if not re.match(VALID_ADDRESS_REGEXP, email_address):
emsg = 'Emailaddress "{}" is not valid according to RFC 2822 standards'.format(
email_address)
raise YagInvalidEmailAddress(emsg)
# apart from the standard, I personally do not trust email addresses without dot.
if "." not in email_address and "localhost" not in email_address.lower():
raise YagInvalidEmailAddress("Missing dot in emailaddress") | Note that this will only filter out syntax mistakes in emailaddresses. If a human would think it is probably a valid email, it will most likely pass. However, it could still very well be that the actual emailaddress has simply not be claimed by anyone (so then this function fails to devalidate). |
157,553 | import time
import random
import hashlib
from yagmail.compat import text_type
from yagmail.error import YagAddressError
def make_addr_alias_target(x, addresses, which):
if isinstance(x, text_type):
addresses["recipients"].append(x)
addresses[which] = x
elif isinstance(x, list) or isinstance(x, tuple):
if not all([isinstance(k, text_type) for k in x]):
raise YagAddressError
addresses["recipients"].extend(x)
addresses[which] = ",".join(x)
elif isinstance(x, dict):
addresses["recipients"].extend(x.keys())
addresses[which] = ",".join(x.values())
else:
raise YagAddressError
The provided code snippet includes necessary dependencies for implementing the `resolve_addresses` function. Write a Python function `def resolve_addresses(user, useralias, to, cc, bcc)` to solve the following problem:
Handle the targets addresses, adding aliases when defined
Here is the function:
def resolve_addresses(user, useralias, to, cc, bcc):
""" Handle the targets addresses, adding aliases when defined """
addresses = {"recipients": []}
if to is not None:
make_addr_alias_target(to, addresses, "To")
elif cc is not None and bcc is not None:
make_addr_alias_target([user, useralias], addresses, "To")
else:
addresses["recipients"].append(user)
if cc is not None:
make_addr_alias_target(cc, addresses, "Cc")
if bcc is not None:
make_addr_alias_target(bcc, addresses, "Bcc")
return addresses | Handle the targets addresses, adding aliases when defined |
157,554 | import time
import random
import hashlib
from yagmail.compat import text_type
from yagmail.error import YagAddressError
text_type = (str,) if PY3 else (str, unicode)
class YagAddressError(Exception):
"""
This means that the address was given in an invalid format.
Note that From can either be a string, or a dictionary where the key is an email,
and the value is an alias {'sample@gmail.com', 'Sam'}. In the case of 'to',
it can either be a string (email), a list of emails (email addresses without aliases)
or a dictionary where keys are the email addresses and the values indicate the aliases.
Furthermore, it does not do any validation of whether an email exists.
"""
pass
def make_addr_alias_user(email_addr):
if isinstance(email_addr, text_type):
if "@" not in email_addr:
email_addr += "@gmail.com"
return (email_addr, email_addr)
if isinstance(email_addr, dict):
if len(email_addr) == 1:
return (list(email_addr.keys())[0], list(email_addr.values())[0])
raise YagAddressError | null |
157,555 | import datetime
import email.encoders
import io
import json
import mimetypes
import os
import sys
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
from yagmail.headers import add_message_id
from yagmail.headers import add_recipients_headers
from yagmail.headers import add_subject
from yagmail.utils import raw, inline
PY3 = sys.version_info[0] > 2
def serialize_object(content):
is_marked_up = False
if isinstance(content, (dict, list, tuple, set)):
content = "<pre>" + json.dumps(content, indent=4, default=dt_converter) + "</pre>"
is_marked_up = True
elif "DataFrame" in content.__class__.__name__:
try:
content = content.render()
except AttributeError:
content = content.to_html()
is_marked_up = True
return is_marked_up, content
def prepare_contents(contents, encoding):
mime_objects = []
has_included_images = False
if contents is not None:
unnamed_attachment_id = 1
for is_marked_up, content in contents:
if isinstance(content, io.IOBase):
if not hasattr(content, 'name'):
# If the IO object has no name attribute, give it one.
content.name = f'attachment_{unnamed_attachment_id}'
content_object = get_mime_object(is_marked_up, content, encoding)
if content_object["main_type"] == "image":
has_included_images = True
mime_objects.append(content_object)
return has_included_images, mime_objects
def add_subject(msg, subject):
if not subject:
return
if isinstance(subject, list):
subject = " ".join(subject)
msg["Subject"] = subject
def add_recipients_headers(user, useralias, msg, addresses):
# Quoting the useralias so it should match display-name from https://tools.ietf.org/html/rfc5322 ,
# even if it's an email address.
msg["From"] = '"{0}" <{1}>'.format(useralias.replace("\\", "\\\\").replace('"', '\\"'), user)
if "To" in addresses:
msg["To"] = addresses["To"]
else:
msg["To"] = useralias
if "Cc" in addresses:
msg["Cc"] = addresses["Cc"]
def add_message_id(msg, message_id=None, group_messages=True):
if message_id is None:
if group_messages:
addr = " ".join(sorted([msg["From"], msg["To"]])) + msg.get("Subject", "None")
else:
addr = str(time.time() + random.random())
message_id = "<" + hashlib.md5(addr.encode()).hexdigest() + "@yagmail>"
msg["Message-ID"] = message_id
class inline(str):
""" Only needed when wanting to inline an image rather than attach it """
pass
The provided code snippet includes necessary dependencies for implementing the `prepare_message` function. Write a Python function `def prepare_message( user, useralias, addresses, subject, contents, attachments, headers, encoding, prettify_html=True, message_id=None, group_messages=True, )` to solve the following problem:
Prepare a MIME message
Here is the function:
def prepare_message(
user,
useralias,
addresses,
subject,
contents,
attachments,
headers,
encoding,
prettify_html=True,
message_id=None,
group_messages=True,
):
# check if closed!!!!!! XXX
""" Prepare a MIME message """
if not isinstance(contents, (list, tuple)):
if contents is not None:
contents = [contents]
if not isinstance(attachments, (list, tuple)):
if attachments is not None:
attachments = [attachments]
# merge contents and attachments for now.
if attachments is not None:
for a in attachments:
if not isinstance(a, io.IOBase) and not os.path.isfile(a):
raise TypeError(f'{a} must be a valid filepath or file handle (instance of io.IOBase). {a} is of type {type(a)}')
contents = attachments if contents is None else contents + attachments
if contents is not None:
contents = [serialize_object(x) for x in contents]
has_included_images, content_objects = prepare_contents(contents, encoding)
if contents is not None:
contents = [x[1] for x in contents]
msg = MIMEMultipart()
if headers is not None:
# Strangely, msg does not have an update method, so then manually.
for k, v in headers.items():
msg[k] = v
if headers is None or "Date" not in headers:
msg["Date"] = formatdate()
msg_alternative = MIMEMultipart("alternative")
msg_related = MIMEMultipart("related")
msg_related.attach("-- HTML goes here --")
msg.attach(msg_alternative)
add_subject(msg, subject)
add_recipients_headers(user, useralias, msg, addresses)
add_message_id(msg, message_id, group_messages)
htmlstr = ""
altstr = []
if has_included_images:
msg.preamble = "This message is best displayed using a MIME capable email reader."
if contents is not None:
for content_object, content_string in zip(content_objects, contents):
if content_object["main_type"] == "image":
# all image objects need base64 encoding, so do it now
email.encoders.encode_base64(content_object["mime_object"])
# aliased image {'path' : 'alias'}
if isinstance(content_string, dict) and len(content_string) == 1:
for key in content_string:
hashed_ref = str(abs(hash(key)))
alias = content_string[key]
# pylint: disable=undefined-loop-variable
content_string = key
else:
alias = os.path.basename(str(content_string))
hashed_ref = str(abs(hash(alias)))
# TODO: I should probably remove inline now that there is "attachments"
# if string is `inline`, inline, else, attach
# pylint: disable=unidiomatic-typecheck
if type(content_string) == inline:
htmlstr += '<img src="cid:{0}" title="{1}"/>'.format(hashed_ref, alias)
content_object["mime_object"].add_header(
"Content-ID", "<{0}>".format(hashed_ref)
)
altstr.append("-- img {0} should be here -- ".format(alias))
# inline images should be in related MIME block
msg_related.attach(content_object["mime_object"])
else:
# non-inline images get attached like any other attachment
msg.attach(content_object["mime_object"])
else:
if content_object["encoding"] == "base64":
email.encoders.encode_base64(content_object["mime_object"])
msg.attach(content_object["mime_object"])
elif content_object["sub_type"] not in ["html", "plain"]:
msg.attach(content_object["mime_object"])
else:
if not content_object["is_marked_up"]:
content_string = content_string.replace("\n", "<br>")
try:
htmlstr += "<div>{0}</div>".format(content_string)
if PY3 and prettify_html:
import premailer
htmlstr = premailer.transform(htmlstr)
except UnicodeEncodeError:
htmlstr += u"<div>{0}</div>".format(content_string)
altstr.append(content_string)
msg_related.get_payload()[0] = MIMEText(htmlstr, "html", _charset=encoding)
msg_alternative.attach(MIMEText("\n".join(altstr), _charset=encoding))
msg_alternative.attach(msg_related)
return msg | Prepare a MIME message |
157,556 | import logging
def get_logger(log_level=logging.DEBUG, file_path_name=None):
# create logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
# create console handler and set level to debug
if file_path_name:
ch = logging.FileHandler(file_path_name)
elif log_level is None:
logger.handlers = [logging.NullHandler()]
return logger
else:
ch = logging.StreamHandler()
ch.setLevel(log_level)
# create formatter
formatter = logging.Formatter(
"%(asctime)s [yagmail] [%(levelname)s] : %(message)s", "%Y-%m-%d %H:%M:%S"
)
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.handlers = [ch]
return logger | null |
157,557 | try:
import keyring
except (ImportError, NameError, RuntimeError):
pass
def register(username, password):
""" Use this to add a new gmail account to your OS' keyring so it can be used in yagmail """
keyring.set_password("yagmail", username, password)
The provided code snippet includes necessary dependencies for implementing the `handle_password` function. Write a Python function `def handle_password(user, password)` to solve the following problem:
Handles getting the password
Here is the function:
def handle_password(user, password): # pragma: no cover
""" Handles getting the password"""
if password is None:
try:
password = keyring.get_password("yagmail", user)
except NameError as e:
print(
"'keyring' cannot be loaded. Try 'pip install keyring' or continue without. See https://github.com/kootenpv/yagmail"
)
raise e
if password is None:
import getpass
password = getpass.getpass("Password for <{0}>: ".format(user))
answer = ""
# Python 2 fix
while answer != "y" and answer != "n":
prompt_string = "Save username and password in keyring? [y/n]: "
# pylint: disable=undefined-variable
try:
answer = raw_input(prompt_string).strip()
except NameError:
answer = input(prompt_string).strip()
if answer == "y":
register(user, password)
return password | Handles getting the password |
157,558 | import os
import base64
import json
import getpass
def generate_oauth2_string(username, access_token, as_base64=False):
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (username, access_token)
if as_base64:
auth_string = base64.b64encode(auth_string.encode('ascii')).decode('ascii')
return auth_string
def refresh_authorization(google_client_id, google_client_secret, google_refresh_token):
response = call_refresh_token(google_client_id, google_client_secret, google_refresh_token)
return response['access_token'], response['expires_in']
def get_oauth_string(user, oauth2_info):
access_token, expires_in = refresh_authorization(**oauth2_info)
auth_string = generate_oauth2_string(user, access_token, as_base64=True)
return auth_string | null |
157,559 | import os
import base64
import json
import getpass
try:
input = raw_input
except NameError:
pass
def get_authorization(google_client_id, google_client_secret):
permission_url = generate_permission_url(google_client_id)
print('Navigate to the following URL to auth:\n' + permission_url)
authorization_code = input('Enter verification code: ')
response = call_authorize_tokens(google_client_id, google_client_secret, authorization_code)
return response['refresh_token'], response['access_token'], response['expires_in']
def get_oauth2_info(oauth2_file):
oauth2_file = os.path.expanduser(oauth2_file)
if os.path.isfile(oauth2_file):
with open(oauth2_file) as f:
oauth2_info = json.load(f)
try:
oauth2_info = oauth2_info["installed"]
except KeyError:
return oauth2_info
email_addr = input("Your 'email address': ")
google_client_id = oauth2_info["client_id"]
google_client_secret = oauth2_info["client_secret"]
google_refresh_token, _, _ = get_authorization(google_client_id, google_client_secret)
oauth2_info = {
"email_address": email_addr,
"google_client_id": google_client_id.strip(),
"google_client_secret": google_client_secret.strip(),
"google_refresh_token": google_refresh_token.strip(),
}
with open(oauth2_file, "w") as f:
json.dump(oauth2_info, f)
else:
print("If you do not have an app registered for your email sending purposes, visit:")
print("https://console.developers.google.com")
print("and create a new project.\n")
email_addr = input("Your 'email address': ")
google_client_id = input("Your 'google_client_id': ")
google_client_secret = getpass.getpass("Your 'google_client_secret': ")
google_refresh_token, _, _ = get_authorization(google_client_id, google_client_secret)
oauth2_info = {
"email_address": email_addr,
"google_client_id": google_client_id.strip(),
"google_client_secret": google_client_secret.strip(),
"google_refresh_token": google_refresh_token.strip(),
}
with open(oauth2_file, "w") as f:
json.dump(oauth2_info, f)
return oauth2_info | null |
157,560 | import codecs
import os
import re
import sys
from distutils.util import strtobool
from setuptools import find_packages, setup
from setuptools.command.test import test as TestCommand
def open_local(paths, mode="r", encoding="utf8"):
path = os.path.join(os.path.abspath(os.path.dirname(__file__)), *paths)
return codecs.open(path, mode, encoding) | null |
157,561 | import asyncio
from sanic import Sanic
async def notify_server_started_after_five_seconds():
await asyncio.sleep(5)
print('Server successfully started!') | null |
157,562 | from os import getenv
from sentry_sdk import init as sentry_init
from sentry_sdk.integrations.sanic import SanicIntegration
from sanic import Sanic
from sanic.response import json
def json(
body: Any,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "application/json",
dumps: Optional[Callable[..., str]] = None,
**kwargs,
) -> HTTPResponse:
"""
Returns response object with body in json format.
:param body: Response data to be serialized.
:param status: Response code.
:param headers: Custom Headers.
:param kwargs: Remaining arguments that are passed to the json encoder.
"""
if not dumps:
dumps = BaseHTTPResponse._dumps
return HTTPResponse(
dumps(body, **kwargs),
headers=headers,
status=status,
content_type=content_type,
)
async def working_path(request):
return json({
"response": "Working API Response"
}) | null |
157,563 | from os import getenv
from sentry_sdk import init as sentry_init
from sentry_sdk.integrations.sanic import SanicIntegration
from sanic import Sanic
from sanic.response import json
async def raise_error(request):
raise Exception("Testing Sentry Integration") | null |
157,564 | from sanic import Blueprint, Sanic
from sanic.response import file, json
def json(
body: Any,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "application/json",
dumps: Optional[Callable[..., str]] = None,
**kwargs,
) -> HTTPResponse:
"""
Returns response object with body in json format.
:param body: Response data to be serialized.
:param status: Response code.
:param headers: Custom Headers.
:param kwargs: Remaining arguments that are passed to the json encoder.
"""
if not dumps:
dumps = BaseHTTPResponse._dumps
return HTTPResponse(
dumps(body, **kwargs),
headers=headers,
status=status,
content_type=content_type,
)
async def foo(request):
return json({"msg": "hi from blueprint"}) | null |
157,565 | from sanic import Blueprint, Sanic
from sanic.response import file, json
def json(
body: Any,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "application/json",
dumps: Optional[Callable[..., str]] = None,
**kwargs,
) -> HTTPResponse:
"""
Returns response object with body in json format.
:param body: Response data to be serialized.
:param status: Response code.
:param headers: Custom Headers.
:param kwargs: Remaining arguments that are passed to the json encoder.
"""
if not dumps:
dumps = BaseHTTPResponse._dumps
return HTTPResponse(
dumps(body, **kwargs),
headers=headers,
status=status,
content_type=content_type,
)
async def foo2(request):
return json({"msg": "hi from blueprint2"}) | null |
157,566 | from sanic import Blueprint, Sanic
from sanic.response import file, json
async def file(
location: Union[str, PurePath],
status: int = 200,
mime_type: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
filename: Optional[str] = None,
_range: Optional[Range] = None,
) -> HTTPResponse:
"""Return a response object with file data.
:param location: Location of file on system.
:param mime_type: Specific mime_type.
:param headers: Custom Headers.
:param filename: Override filename.
:param _range:
"""
headers = headers or {}
if filename:
headers.setdefault(
"Content-Disposition", f'attachment; filename="{filename}"'
)
filename = filename or path.split(location)[-1]
async with await open_async(location, mode="rb") as f:
if _range:
await f.seek(_range.start)
out_stream = await f.read(_range.size)
headers[
"Content-Range"
] = f"bytes {_range.start}-{_range.end}/{_range.total}"
status = 206
else:
out_stream = await f.read()
mime_type = mime_type or guess_type(filename)[0] or "text/plain"
return HTTPResponse(
body=out_stream,
status=status,
headers=headers,
content_type=mime_type,
)
async def index(request):
return await file("websocket.html") | null |
157,567 | from sanic import Blueprint, Sanic
from sanic.response import file, json
async def foo3(request, ws):
while True:
data = "hello!"
print("Sending: " + data)
await ws.send(data)
data = await ws.recv()
print("Received: " + data) | null |
157,568 | from sanic import Sanic, response, text
def foo(request):
return text("foo") | null |
157,569 | from sanic import Sanic, response, text
def bar(request):
return text("bar") | null |
157,570 | from sanic import Sanic, response, text
https = Sanic("https")
https.config.SERVER_NAME = f"localhost:{HTTPS_PORT}"
https.run(port=HTTPS_PORT, debug=True)
def proxy(request, path):
url = request.app.url_for(
"proxy",
path=path,
_server=https.config.SERVER_NAME,
_external=True,
_scheme="http",
)
return response.redirect(url) | null |
157,571 | from sanic import Sanic, response, text
HTTP_PORT = 9999
http = Sanic("http")
http.config.SERVER_NAME = f"localhost:{HTTP_PORT}"
async def start(app, _):
global http
app.http_server = await http.create_server(
port=HTTP_PORT, return_asyncio_server=True
)
app.http_server.after_start() | null |
157,572 | from sanic import Sanic, response, text
async def stop(app, _):
app.http_server.before_stop()
await app.http_server.close()
app.http_server.after_stop() | null |
157,573 | from sanic import Sanic
from sanic import response
app = Sanic(__name__)
async def index(request):
# generate a URL for the endpoint `post_handler`
url = app.url_for('post_handler', post_id=5)
# the URL is `/posts/5`, redirect to it
return response.redirect(url) | null |
157,574 | from sanic import Sanic
from sanic import response
async def post_handler(request, post_id):
return response.text('Post - {}'.format(post_id)) | null |
157,575 | from asyncio import sleep
from sanic import Sanic, response
async def handler(request):
return response.redirect("/sleep/3") | null |
157,576 | from asyncio import sleep
from sanic import Sanic, response
async def handler2(request, t=0.3):
await sleep(t)
return response.text(f"Slept {t:.1f} seconds.\n") | null |
157,577 | import logging
import aiotask_context as context
from sanic import Sanic, response
log = logging.getLogger(__name__)
async def set_request_id(request):
request_id = request.id
context.set("X-Request-ID", request_id)
log.info(f"Setting {request.id=}") | null |
157,578 | import logging
import aiotask_context as context
from sanic import Sanic, response
async def set_request_header(request, response):
response.headers["X-Request-ID"] = request.id | null |
157,579 | import logging
import aiotask_context as context
from sanic import Sanic, response
def setup(app, loop):
loop.set_task_factory(context.task_factory) | null |
157,580 | from sanic import Sanic
from sanic.response import text
from random import randint
def append_request(request):
# Add new key with random value
request['num'] = randint(0, 100) | null |
157,581 | from sanic import Sanic
from sanic.response import text
from random import randint
def text(
body: str,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "text/plain; charset=utf-8",
) -> HTTPResponse:
"""
Returns response object with body in text format.
:param body: Response data to be encoded.
:param status: Response code.
:param headers: Custom Headers.
:param content_type: the content type (string) of the response
"""
if not isinstance(body, str):
raise TypeError(
f"Bad body type. Expected str, got {type(body).__name__})"
)
return HTTPResponse(
body, status=status, headers=headers, content_type=content_type
)
def pop_handler(request):
# Pop key from request object
num = request.pop('num')
return text(num) | null |
157,582 | from sanic import Sanic
from sanic.response import text
from random import randint
def text(
body: str,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "text/plain; charset=utf-8",
) -> HTTPResponse:
"""
Returns response object with body in text format.
:param body: Response data to be encoded.
:param status: Response code.
:param headers: Custom Headers.
:param content_type: the content type (string) of the response
"""
if not isinstance(body, str):
raise TypeError(
f"Bad body type. Expected str, got {type(body).__name__})"
)
return HTTPResponse(
body, status=status, headers=headers, content_type=content_type
)
def key_exist_handler(request):
# Check the key is exist or not
if 'num' in request:
return text('num exist in request')
return text('num does not exist in reqeust') | null |
157,583 | import asyncio
from signal import SIGINT, signal
import uvloop
from sanic import Sanic, response
from sanic.server import AsyncioServer
async def after_start_test(app, loop):
print("Async Server Started!") | null |
157,584 | from sanic import Sanic
from sanic.views import CompositionView
from sanic.views import HTTPMethodView
from sanic.views import stream as stream_decorator
from sanic.blueprints import Blueprint
from sanic.response import stream, text
def stream(func):
func.is_stream = True
return func
def stream(
streaming_fn: StreamingFunction,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "text/plain; charset=utf-8",
):
"""Accepts an coroutine `streaming_fn` which can be used to
write chunks to a streaming response. Returns a `StreamingHTTPResponse`.
Example usage::
async def index(request):
async def streaming_fn(response):
await response.write('foo')
await response.write('bar')
return stream(streaming_fn, content_type='text/plain')
:param streaming_fn: A coroutine accepts a response and
writes content to that response.
:param mime_type: Specific mime_type.
:param headers: Custom Headers.
:param chunked: Deprecated
"""
return StreamingHTTPResponse(
streaming_fn,
headers=headers,
content_type=content_type,
status=status,
ignore_deprecation_notice=True,
)
async def handler(request):
async def streaming(response):
while True:
body = await request.stream.get()
if body is None:
break
body = body.decode('utf-8').replace('1', 'A')
await response.write(body)
return stream(streaming) | null |
157,585 | from sanic import Sanic
from sanic.views import CompositionView
from sanic.views import HTTPMethodView
from sanic.views import stream as stream_decorator
from sanic.blueprints import Blueprint
from sanic.response import stream, text
def stream(func):
func.is_stream = True
return func
def text(
body: str,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "text/plain; charset=utf-8",
) -> HTTPResponse:
"""
Returns response object with body in text format.
:param body: Response data to be encoded.
:param status: Response code.
:param headers: Custom Headers.
:param content_type: the content type (string) of the response
"""
if not isinstance(body, str):
raise TypeError(
f"Bad body type. Expected str, got {type(body).__name__})"
)
return HTTPResponse(
body, status=status, headers=headers, content_type=content_type
)
def stream(
streaming_fn: StreamingFunction,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "text/plain; charset=utf-8",
):
"""Accepts an coroutine `streaming_fn` which can be used to
write chunks to a streaming response. Returns a `StreamingHTTPResponse`.
Example usage::
async def index(request):
async def streaming_fn(response):
await response.write('foo')
await response.write('bar')
return stream(streaming_fn, content_type='text/plain')
:param streaming_fn: A coroutine accepts a response and
writes content to that response.
:param mime_type: Specific mime_type.
:param headers: Custom Headers.
:param chunked: Deprecated
"""
return StreamingHTTPResponse(
streaming_fn,
headers=headers,
content_type=content_type,
status=status,
ignore_deprecation_notice=True,
)
async def bp_handler(request):
result = ''
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode('utf-8').replace('1', 'A')
return text(result) | null |
157,586 | from sanic import Sanic
from sanic.views import CompositionView
from sanic.views import HTTPMethodView
from sanic.views import stream as stream_decorator
from sanic.blueprints import Blueprint
from sanic.response import stream, text
def stream(func):
func.is_stream = True
return func
def text(
body: str,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "text/plain; charset=utf-8",
) -> HTTPResponse:
"""
Returns response object with body in text format.
:param body: Response data to be encoded.
:param status: Response code.
:param headers: Custom Headers.
:param content_type: the content type (string) of the response
"""
if not isinstance(body, str):
raise TypeError(
f"Bad body type. Expected str, got {type(body).__name__})"
)
return HTTPResponse(
body, status=status, headers=headers, content_type=content_type
)
def stream(
streaming_fn: StreamingFunction,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "text/plain; charset=utf-8",
):
"""Accepts an coroutine `streaming_fn` which can be used to
write chunks to a streaming response. Returns a `StreamingHTTPResponse`.
Example usage::
async def index(request):
async def streaming_fn(response):
await response.write('foo')
await response.write('bar')
return stream(streaming_fn, content_type='text/plain')
:param streaming_fn: A coroutine accepts a response and
writes content to that response.
:param mime_type: Specific mime_type.
:param headers: Custom Headers.
:param chunked: Deprecated
"""
return StreamingHTTPResponse(
streaming_fn,
headers=headers,
content_type=content_type,
status=status,
ignore_deprecation_notice=True,
)
async def post_handler(request):
result = ''
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode('utf-8')
return text(result) | null |
157,587 | import logging
import socket
from os import getenv
from platform import node
from uuid import getnode as get_mac
from logdna import LogDNAHandler
from sanic import Sanic
from sanic.response import json
from sanic.request import Request
def get_my_ip_address(remote_server="google.com"):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect((remote_server, 80))
return s.getsockname()[0] | null |
157,588 | import logging
import socket
from os import getenv
from platform import node
from uuid import getnode as get_mac
from logdna import LogDNAHandler
from sanic import Sanic
from sanic.response import json
from sanic.request import Request
def get_mac_address():
h = iter(hex(get_mac())[2:].zfill(12))
return ":".join(i + next(h) for i in h) | null |
157,589 | import logging
import socket
from os import getenv
from platform import node
from uuid import getnode as get_mac
from logdna import LogDNAHandler
from sanic import Sanic
from sanic.response import json
from sanic.request import Request
logdna = logging.getLogger(__name__)
logdna.setLevel(logging.INFO)
logdna.addHandler(logdna_handler)
class Request:
"""
Properties of an HTTP request such as URL, headers, etc.
"""
__slots__ = (
"__weakref__",
"_cookies",
"_id",
"_ip",
"_parsed_url",
"_port",
"_protocol",
"_remote_addr",
"_socket",
"_match_info",
"_name",
"app",
"body",
"conn_info",
"ctx",
"head",
"headers",
"method",
"parsed_accept",
"parsed_args",
"parsed_not_grouped_args",
"parsed_files",
"parsed_form",
"parsed_json",
"parsed_forwarded",
"raw_url",
"request_middleware_started",
"route",
"stream",
"transport",
"version",
)
def __init__(
self,
url_bytes: bytes,
headers: Header,
version: str,
method: str,
transport: TransportProtocol,
app: Sanic,
head: bytes = b"",
):
self.raw_url = url_bytes
# TODO: Content-Encoding detection
self._parsed_url = parse_url(url_bytes)
self._id: Optional[Union[uuid.UUID, str, int]] = None
self._name: Optional[str] = None
self.app = app
self.headers = Header(headers)
self.version = version
self.method = method
self.transport = transport
self.head = head
# Init but do not inhale
self.body = b""
self.conn_info: Optional[ConnInfo] = None
self.ctx = SimpleNamespace()
self.parsed_forwarded: Optional[Options] = None
self.parsed_accept: Optional[AcceptContainer] = None
self.parsed_json = None
self.parsed_form = None
self.parsed_files = None
self.parsed_args: DefaultDict[
Tuple[bool, bool, str, str], RequestParameters
] = defaultdict(RequestParameters)
self.parsed_not_grouped_args: DefaultDict[
Tuple[bool, bool, str, str], List[Tuple[str, str]]
] = defaultdict(list)
self.request_middleware_started = False
self._cookies: Optional[Dict[str, str]] = None
self._match_info: Dict[str, Any] = {}
self.stream: Optional[Http] = None
self.route: Optional[Route] = None
self._protocol = None
def __repr__(self):
class_name = self.__class__.__name__
return f"<{class_name}: {self.method} {self.path}>"
def generate_id(*_):
return uuid.uuid4()
async def respond(
self,
response: Optional[BaseHTTPResponse] = None,
*,
status: int = 200,
headers: Optional[Union[Header, Dict[str, str]]] = None,
content_type: Optional[str] = None,
):
# This logic of determining which response to use is subject to change
if response is None:
response = (self.stream and self.stream.response) or HTTPResponse(
status=status,
headers=headers,
content_type=content_type,
)
# Connect the response
if isinstance(response, BaseHTTPResponse) and self.stream:
response = self.stream.respond(response)
# Run response middleware
try:
response = await self.app._run_response_middleware(
self, response, request_name=self.name
)
except CancelledErrors:
raise
except Exception:
error_logger.exception(
"Exception occurred in one of response middleware handlers"
)
return response
async def receive_body(self):
"""Receive request.body, if not already received.
Streaming handlers may call this to receive the full body. Sanic calls
this function before running any handlers of non-streaming routes.
Custom request classes can override this for custom handling of both
streaming and non-streaming routes.
"""
if not self.body:
self.body = b"".join([data async for data in self.stream])
def name(self):
if self._name:
return self._name
elif self.route:
return self.route.name
return None
def endpoint(self):
return self.name
def uri_template(self):
return f"/{self.route.path}"
def protocol(self):
if not self._protocol:
self._protocol = self.transport.get_protocol()
return self._protocol
def raw_headers(self):
_, headers = self.head.split(b"\r\n", 1)
return bytes(headers)
def request_line(self):
reqline, _ = self.head.split(b"\r\n", 1)
return bytes(reqline)
def id(self) -> Optional[Union[uuid.UUID, str, int]]:
"""
A request ID passed from the client, or generated from the backend.
By default, this will look in a request header defined at:
``self.app.config.REQUEST_ID_HEADER``. It defaults to
``X-Request-ID``. Sanic will try to cast the ID into a ``UUID`` or an
``int``. If there is not a UUID from the client, then Sanic will try
to generate an ID by calling ``Request.generate_id()``. The default
behavior is to generate a ``UUID``. You can customize this behavior
by subclassing ``Request``.
.. code-block:: python
from sanic import Request, Sanic
from itertools import count
class IntRequest(Request):
counter = count()
def generate_id(self):
return next(self.counter)
app = Sanic("MyApp", request_class=IntRequest)
"""
if not self._id:
self._id = self.headers.getone(
self.app.config.REQUEST_ID_HEADER,
self.__class__.generate_id(self), # type: ignore
)
# Try casting to a UUID or an integer
if isinstance(self._id, str):
try:
self._id = uuid.UUID(self._id)
except ValueError:
try:
self._id = int(self._id) # type: ignore
except ValueError:
...
return self._id # type: ignore
def json(self):
if self.parsed_json is None:
self.load_json()
return self.parsed_json
def load_json(self, loads=json_loads):
try:
self.parsed_json = loads(self.body)
except Exception:
if not self.body:
return None
raise InvalidUsage("Failed when parsing body as json")
return self.parsed_json
def accept(self) -> AcceptContainer:
if self.parsed_accept is None:
accept_header = self.headers.getone("accept", "")
self.parsed_accept = parse_accept(accept_header)
return self.parsed_accept
def token(self):
"""Attempt to return the auth header token.
:return: token related to request
"""
prefixes = ("Bearer", "Token")
auth_header = self.headers.getone("authorization", None)
if auth_header is not None:
for prefix in prefixes:
if prefix in auth_header:
return auth_header.partition(prefix)[-1].strip()
return auth_header
def form(self):
if self.parsed_form is None:
self.parsed_form = RequestParameters()
self.parsed_files = RequestParameters()
content_type = self.headers.getone(
"content-type", DEFAULT_HTTP_CONTENT_TYPE
)
content_type, parameters = parse_content_header(content_type)
try:
if content_type == "application/x-www-form-urlencoded":
self.parsed_form = RequestParameters(
parse_qs(self.body.decode("utf-8"))
)
elif content_type == "multipart/form-data":
# TODO: Stream this instead of reading to/from memory
boundary = parameters["boundary"].encode("utf-8")
self.parsed_form, self.parsed_files = parse_multipart_form(
self.body, boundary
)
except Exception:
error_logger.exception("Failed when parsing form")
return self.parsed_form
def files(self):
if self.parsed_files is None:
self.form # compute form to get files
return self.parsed_files
def get_args(
self,
keep_blank_values: bool = False,
strict_parsing: bool = False,
encoding: str = "utf-8",
errors: str = "replace",
) -> RequestParameters:
"""
Method to parse `query_string` using `urllib.parse.parse_qs`.
This methods is used by `args` property.
Can be used directly if you need to change default parameters.
:param keep_blank_values:
flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.
A true value indicates that blanks should be retained as blank
strings. The default false value indicates that blank values
are to be ignored and treated as if they were not included.
:type keep_blank_values: bool
:param strict_parsing:
flag indicating what to do with parsing errors.
If false (the default), errors are silently ignored. If true,
errors raise a ValueError exception.
:type strict_parsing: bool
:param encoding:
specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
:type encoding: str
:param errors:
specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
:type errors: str
:return: RequestParameters
"""
if (
keep_blank_values,
strict_parsing,
encoding,
errors,
) not in self.parsed_args:
if self.query_string:
self.parsed_args[
(keep_blank_values, strict_parsing, encoding, errors)
] = RequestParameters(
parse_qs(
qs=self.query_string,
keep_blank_values=keep_blank_values,
strict_parsing=strict_parsing,
encoding=encoding,
errors=errors,
)
)
return self.parsed_args[
(keep_blank_values, strict_parsing, encoding, errors)
]
args = property(get_args)
def get_query_args(
self,
keep_blank_values: bool = False,
strict_parsing: bool = False,
encoding: str = "utf-8",
errors: str = "replace",
) -> list:
"""
Method to parse `query_string` using `urllib.parse.parse_qsl`.
This methods is used by `query_args` property.
Can be used directly if you need to change default parameters.
:param keep_blank_values:
flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.
A true value indicates that blanks should be retained as blank
strings. The default false value indicates that blank values
are to be ignored and treated as if they were not included.
:type keep_blank_values: bool
:param strict_parsing:
flag indicating what to do with parsing errors.
If false (the default), errors are silently ignored. If true,
errors raise a ValueError exception.
:type strict_parsing: bool
:param encoding:
specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
:type encoding: str
:param errors:
specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
:type errors: str
:return: list
"""
if (
keep_blank_values,
strict_parsing,
encoding,
errors,
) not in self.parsed_not_grouped_args:
if self.query_string:
self.parsed_not_grouped_args[
(keep_blank_values, strict_parsing, encoding, errors)
] = parse_qsl(
qs=self.query_string,
keep_blank_values=keep_blank_values,
strict_parsing=strict_parsing,
encoding=encoding,
errors=errors,
)
return self.parsed_not_grouped_args[
(keep_blank_values, strict_parsing, encoding, errors)
]
query_args = property(get_query_args)
"""
Convenience property to access :meth:`Request.get_query_args` with
default values.
"""
def cookies(self) -> Dict[str, str]:
"""
:return: Incoming cookies on the request
:rtype: Dict[str, str]
"""
if self._cookies is None:
cookie = self.headers.getone("cookie", None)
if cookie is not None:
cookies: SimpleCookie = SimpleCookie()
cookies.load(cookie)
self._cookies = {
name: cookie.value for name, cookie in cookies.items()
}
else:
self._cookies = {}
return self._cookies
def content_type(self) -> str:
"""
:return: Content-Type header form the request
:rtype: str
"""
return self.headers.getone("content-type", DEFAULT_HTTP_CONTENT_TYPE)
def match_info(self):
"""
:return: matched info after resolving route
"""
return self._match_info
def match_info(self, value):
self._match_info = value
# Transport properties (obtained from local interface only)
def ip(self) -> str:
"""
:return: peer ip of the socket
:rtype: str
"""
return self.conn_info.client_ip if self.conn_info else ""
def port(self) -> int:
"""
:return: peer port of the socket
:rtype: int
"""
return self.conn_info.client_port if self.conn_info else 0
def socket(self):
return self.conn_info.peername if self.conn_info else (None, None)
def path(self) -> str:
"""
:return: path of the local HTTP request
:rtype: str
"""
return self._parsed_url.path.decode("utf-8")
# Proxy properties (using SERVER_NAME/forwarded/request/transport info)
def forwarded(self) -> Options:
"""
Active proxy information obtained from request headers, as specified in
Sanic configuration.
Field names by, for, proto, host, port and path are normalized.
- for and by IPv6 addresses are bracketed
- port (int) is only set by port headers, not from host.
- path is url-unencoded
Additional values may be available from new style Forwarded headers.
:return: forwarded address info
:rtype: Dict[str, str]
"""
if self.parsed_forwarded is None:
self.parsed_forwarded = (
parse_forwarded(self.headers, self.app.config)
or parse_xforwarded(self.headers, self.app.config)
or {}
)
return self.parsed_forwarded
def remote_addr(self) -> str:
"""
Client IP address, if available.
1. proxied remote address `self.forwarded['for']`
2. local remote address `self.ip`
:return: IPv4, bracketed IPv6, UNIX socket name or arbitrary string
:rtype: str
"""
if not hasattr(self, "_remote_addr"):
self._remote_addr = str(
self.forwarded.get("for", "")
) # or self.ip
return self._remote_addr
def scheme(self) -> str:
"""
Determine request scheme.
1. `config.SERVER_NAME` if in full URL format
2. proxied proto/scheme
3. local connection protocol
:return: http|https|ws|wss or arbitrary value given by the headers.
:rtype: str
"""
if "//" in self.app.config.get("SERVER_NAME", ""):
return self.app.config.SERVER_NAME.split("//")[0]
if "proto" in self.forwarded:
return str(self.forwarded["proto"])
if (
self.app.websocket_enabled
and self.headers.getone("upgrade", "").lower() == "websocket"
):
scheme = "ws"
else:
scheme = "http"
if self.transport.get_extra_info("sslcontext"):
scheme += "s"
return scheme
def host(self) -> str:
"""
The currently effective server 'host' (hostname or hostname:port).
1. `config.SERVER_NAME` overrides any client headers
2. proxied host of original request
3. request host header
hostname and port may be separated by
`sanic.headers.parse_host(request.host)`.
:return: the first matching host found, or empty string
:rtype: str
"""
server_name = self.app.config.get("SERVER_NAME")
if server_name:
return server_name.split("//", 1)[-1].split("/", 1)[0]
return str(
self.forwarded.get("host") or self.headers.getone("host", "")
)
def server_name(self) -> str:
"""
:return: hostname the client connected to, by ``request.host``
:rtype: str
"""
return parse_host(self.host)[0] or ""
def server_port(self) -> int:
"""
The port the client connected to, by forwarded ``port`` or
``request.host``.
Default port is returned as 80 and 443 based on ``request.scheme``.
:return: port number
:rtype: int
"""
port = self.forwarded.get("port") or parse_host(self.host)[1]
return int(port or (80 if self.scheme in ("http", "ws") else 443))
def server_path(self) -> str:
"""
:return: full path of current URL; uses proxied or local path
:rtype: str
"""
return str(self.forwarded.get("path") or self.path)
def query_string(self) -> str:
"""
:return: representation of the requested query
:rtype: str
"""
if self._parsed_url.query:
return self._parsed_url.query.decode("utf-8")
else:
return ""
def url(self) -> str:
"""
:return: the URL
:rtype: str
"""
return urlunparse(
(self.scheme, self.host, self.path, None, self.query_string, None)
)
def url_for(self, view_name: str, **kwargs) -> str:
"""
Same as :func:`sanic.Sanic.url_for`, but automatically determine
`scheme` and `netloc` base on the request. Since this method is aiming
to generate correct schema & netloc, `_external` is implied.
:param kwargs: takes same parameters as in :func:`sanic.Sanic.url_for`
:return: an absolute url to the given view
:rtype: str
"""
# Full URL SERVER_NAME can only be handled in app.url_for
try:
if "//" in self.app.config.SERVER_NAME:
return self.app.url_for(view_name, _external=True, **kwargs)
except AttributeError:
pass
scheme = self.scheme
host = self.server_name
port = self.server_port
if (scheme.lower() in ("http", "ws") and port == 80) or (
scheme.lower() in ("https", "wss") and port == 443
):
netloc = host
else:
netloc = f"{host}:{port}"
return self.app.url_for(
view_name, _external=True, _scheme=scheme, _server=netloc, **kwargs
)
def log_request(request: Request):
logdna.info("I was Here with a new Request to URL: {}".format(request.url)) | null |
157,590 | import logging
import socket
from os import getenv
from platform import node
from uuid import getnode as get_mac
from logdna import LogDNAHandler
from sanic import Sanic
from sanic.response import json
from sanic.request import Request
def json(
body: Any,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "application/json",
dumps: Optional[Callable[..., str]] = None,
**kwargs,
) -> HTTPResponse:
def default(request):
return json({
"response": "I was here"
}) | null |
157,591 | from sanic import Sanic
from sanic.blueprints import Blueprint
from sanic.response import json
def json(
body: Any,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "application/json",
dumps: Optional[Callable[..., str]] = None,
**kwargs,
) -> HTTPResponse:
"""
Returns response object with body in json format.
:param body: Response data to be serialized.
:param status: Response code.
:param headers: Custom Headers.
:param kwargs: Remaining arguments that are passed to the json encoder.
"""
if not dumps:
dumps = BaseHTTPResponse._dumps
return HTTPResponse(
dumps(body, **kwargs),
headers=headers,
status=status,
content_type=content_type,
)
The provided code snippet includes necessary dependencies for implementing the `bp1_name` function. Write a Python function `async def bp1_name(request)` to solve the following problem:
This will expose an Endpoint GET /v1/sentient/robot/ultron/name
Here is the function:
async def bp1_name(request):
"""This will expose an Endpoint GET /v1/sentient/robot/ultron/name"""
return json({"name": "Ultron"}) | This will expose an Endpoint GET /v1/sentient/robot/ultron/name |
157,592 | from sanic import Sanic
from sanic.blueprints import Blueprint
from sanic.response import json
def json(
body: Any,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "application/json",
dumps: Optional[Callable[..., str]] = None,
**kwargs,
) -> HTTPResponse:
"""
Returns response object with body in json format.
:param body: Response data to be serialized.
:param status: Response code.
:param headers: Custom Headers.
:param kwargs: Remaining arguments that are passed to the json encoder.
"""
if not dumps:
dumps = BaseHTTPResponse._dumps
return HTTPResponse(
dumps(body, **kwargs),
headers=headers,
status=status,
content_type=content_type,
)
The provided code snippet includes necessary dependencies for implementing the `bp2_name` function. Write a Python function `async def bp2_name(request)` to solve the following problem:
This will expose an Endpoint GET /v1/sentient/robot/vision/name
Here is the function:
async def bp2_name(request):
"""This will expose an Endpoint GET /v1/sentient/robot/vision/name"""
return json({"name": "vision"}) | This will expose an Endpoint GET /v1/sentient/robot/vision/name |
157,593 | from sanic import Sanic
from sanic.blueprints import Blueprint
from sanic.response import json
def json(
body: Any,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "application/json",
dumps: Optional[Callable[..., str]] = None,
**kwargs,
) -> HTTPResponse:
"""
Returns response object with body in json format.
:param body: Response data to be serialized.
:param status: Response code.
:param headers: Custom Headers.
:param kwargs: Remaining arguments that are passed to the json encoder.
"""
if not dumps:
dumps = BaseHTTPResponse._dumps
return HTTPResponse(
dumps(body, **kwargs),
headers=headers,
status=status,
content_type=content_type,
)
The provided code snippet includes necessary dependencies for implementing the `bp2_revised_name` function. Write a Python function `async def bp2_revised_name(request)` to solve the following problem:
This will expose an Endpoint GET /v2/sentient/robot/vision/name
Here is the function:
async def bp2_revised_name(request):
"""This will expose an Endpoint GET /v2/sentient/robot/vision/name"""
return json({"name": "new vision"}) | This will expose an Endpoint GET /v2/sentient/robot/vision/name |
157,594 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
async def test_async(request):
return response.json({"test": True}) | null |
157,595 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
def test_sync(request):
return response.json({"test": True}) | null |
157,596 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
def test_params(request, name, i):
return response.text("yeehaww {} {}".format(name, i)) | null |
157,597 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
class ServerError(SanicException):
def exception(request):
raise ServerError("It's dead jim") | null |
157,598 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
async def test_await(request):
import asyncio
await asyncio.sleep(5)
return response.text("I'm feeling sleepy") | null |
157,599 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
async def test_file(request):
return await response.file(os.path.abspath("setup.py")) | null |
157,600 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
async def test_file_stream(request):
return await response.file_stream(os.path.abspath("setup.py"),
chunk_size=1024) | null |
157,601 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
def post_json(request):
return response.json({"received": True, "message": request.json}) | null |
157,602 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
def post_form_json(request):
return response.json({"received": True, "form_data": request.form, "test": request.form.get('test')}) | null |
157,603 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
def query_string(request):
return response.json({"parsed": True, "args": request.args, "url": request.url,
"query_string": request.query_string}) | null |
157,604 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
def before_start(app, loop):
log.info("SERVER STARTING") | null |
157,605 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
def after_start(app, loop):
log.info("OH OH OH OH OHHHHHHHH") | null |
157,606 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
def before_stop(app, loop):
log.info("SERVER STOPPING") | null |
157,607 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
def after_stop(app, loop):
log.info("TRIED EVERYTHING") | null |
157,608 | import asyncio
from sanic import Sanic
from sanic import response
from sanic.config import Config
from sanic.exceptions import RequestTimeout
def timeout(request, exception):
return response.text('RequestTimeout from error_handler.', 408) | null |
157,609 | from sanic import Sanic
from sanic import response
def handle_request(request):
return response.json(
{'message': 'Hello world!'},
headers={'X-Served-By': 'sanic'},
status=200
) | null |
157,610 | from sanic import Sanic
from sanic import response
def handle_request(request):
return response.json(
{'message': 'You are not authorized'},
headers={'X-Served-By': 'sanic'},
status=404
) | null |
157,611 | import rollbar
from sanic.handlers import ErrorHandler
from sanic import Sanic
from sanic.exceptions import SanicException
from os import getenv
class SanicException(Exception):
message: str = ""
def __init__(
self,
message: Optional[Union[str, bytes]] = None,
status_code: Optional[int] = None,
quiet: Optional[bool] = None,
context: Optional[Dict[str, Any]] = None,
extra: Optional[Dict[str, Any]] = None,
) -> None:
self.context = context
self.extra = extra
if message is None:
if self.message:
message = self.message
elif status_code is not None:
msg: bytes = STATUS_CODES.get(status_code, b"")
message = msg.decode("utf8")
super().__init__(message)
if status_code is not None:
self.status_code = status_code
# quiet=None/False/True with None meaning choose by status
if quiet or quiet is None and status_code not in (None, 500):
self.quiet = True
def create_error(request):
raise SanicException("I was here and I don't like where I am") | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.