code stringlengths 17 6.64M |
|---|
class ResBlk(nn.Module):
def __init__(self, dim_in, dim_out, actv=nn.LeakyReLU(0.2), normalize=False, downsample=False):
super().__init__()
self.actv = actv
self.normalize = normalize
self.downsample = downsample
self.learned_sc = (dim_in != dim_out)
self._build_we... |
class AdaIN(nn.Module):
def __init__(self, style_dim, num_features):
super().__init__()
self.norm = nn.InstanceNorm2d(num_features, affine=False)
self.fc = nn.Linear(style_dim, (num_features * 2))
def forward(self, x, s):
h = self.fc(s)
h = h.view(h.size(0), h.size(1)... |
class AdainResBlk(nn.Module):
def __init__(self, dim_in, dim_out, style_dim=64, w_hpf=0, actv=nn.LeakyReLU(0.2), upsample=False):
super().__init__()
self.w_hpf = w_hpf
self.actv = actv
self.upsample = upsample
self.learned_sc = (dim_in != dim_out)
self._build_weigh... |
class HighPass(nn.Module):
def __init__(self, w_hpf, device):
super(HighPass, self).__init__()
self.filter = (torch.tensor([[(- 1), (- 1), (- 1)], [(- 1), 8.0, (- 1)], [(- 1), (- 1), (- 1)]]).to(device) / w_hpf)
def forward(self, x):
filter = self.filter.unsqueeze(0).unsqueeze(1).rep... |
class Attention(nn.Module):
def __init__(self, style_dim=64):
super().__init__()
self.layers = nn.Sequential(nn.Linear(style_dim, style_dim), nn.ReLU(), nn.Linear(style_dim, style_dim))
def forward(self, s):
return self.layers(s)
|
class Generator(nn.Module):
def __init__(self, img_size=256, style_dim=64, max_conv_dim=512, w_hpf=1):
super().__init__()
dim_in = ((2 ** 14) // img_size)
self.img_size = img_size
self.from_rgb = nn.Conv2d(3, dim_in, 3, 1, 1)
self.encode = nn.ModuleList()
self.deco... |
class StyleEncoder(nn.Module):
def __init__(self, img_size=256, style_dim=64, num_domains=2, max_conv_dim=512):
super().__init__()
dim_in = ((2 ** 14) // img_size)
blocks = []
blocks += [nn.Conv2d(3, dim_in, 3, 1, 1)]
repeat_num = (int(np.log2(img_size)) - 2)
for _... |
class Discriminator(nn.Module):
def __init__(self, img_size=256, num_domains=2, max_conv_dim=512):
super().__init__()
dim_in = ((2 ** 14) // img_size)
blocks = []
blocks += [nn.Conv2d(3, dim_in, 3, 1, 1)]
repeat_num = (int(np.log2(img_size)) - 2)
for _ in range(rep... |
def build_model(args):
generator = Generator(args.img_size, args.style_dim, w_hpf=args.w_hpf)
style_encoder = StyleEncoder(args.img_size, args.style_dim, args.num_domains)
discriminator = Discriminator(args.img_size, args.num_domains)
generator_ema = copy.deepcopy(generator)
style_encoder_ema = co... |
class Solver(nn.Module):
def __init__(self, args):
super().__init__()
self.args = args
self.device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
(self.nets, self.nets_ema) = build_model(args)
for (name, module) in self.nets.items():
utils.pri... |
def save_json(json_file, filename):
with open(filename, 'w') as f:
json.dump(json_file, f, indent=4, sort_keys=False)
|
def print_network(network, name):
num_params = 0
for p in network.parameters():
num_params += p.numel()
print(('Number of parameters of %s: %i' % (name, num_params)))
|
def he_init(module):
if isinstance(module, nn.Conv2d):
nn.init.kaiming_normal_(module.weight, mode='fan_in', nonlinearity='relu')
if (module.bias is not None):
nn.init.constant_(module.bias, 0)
if isinstance(module, nn.Linear):
nn.init.kaiming_normal_(module.weight, mode='f... |
def denormalize(x):
out = ((x + 1) / 2)
return out.clamp_(0, 1)
|
def save_image(x, ncol, filename):
x = denormalize(x)
vutils.save_image(x.cpu(), filename, nrow=ncol, padding=0)
|
@torch.no_grad()
def translate_and_reconstruct(nets, args, x_src, y_src, x_ref, y_ref, filename):
(N, C, H, W) = x_src.size()
(s_ref, s_ref1, s_ref2, s_ref3) = nets.style_encoder(x_ref, y_src, y_ref)
masks = (nets.fan.get_heatmap(x_src) if (args.w_hpf > 0) else None)
x_fake = nets.generator(x_src, (s_... |
@torch.no_grad()
def translate_using_reference(nets, args, x_src, y_src, x_ref, y_ref, filename):
(N, C, H, W) = x_src.size()
wb = torch.ones(1, C, H, W).to(x_src.device)
x_src_with_wb = torch.cat([wb, x_src], dim=0)
x_ref_with_wb = torch.cat([wb, x_ref], dim=0)
masks = (nets.fan.get_heatmap(x_src... |
@torch.no_grad()
def translate_self(nets, args, x_src, y_src, filename):
(N, C, H, W) = x_src.size()
wb = torch.ones(1, C, H, W).to(x_src.device)
x_src_with_wb = torch.cat([wb, x_src], dim=0)
masks = (nets.fan.get_heatmap(x_src) if (args.w_hpf > 0) else None)
x_concat = [x_src_with_wb]
for i i... |
@torch.no_grad()
def debug_image(nets, args, inputs, step):
(x_src, y_src) = (inputs.x_src, inputs.y_src)
device = inputs.x_src.device
N = inputs.x_src.size(0)
y_ref = np.zeros(N)
for i in range(N):
while (y_ref[i] == y_src[i]):
y_ref[i] = random.randint(0, (args.num_domains - ... |
def str2bool(v):
return (v.lower() in 'true')
|
def subdirs(dname):
return [d for d in os.listdir(dname) if os.path.isdir(os.path.join(dname, d))]
|
def main(args):
print(args)
cudnn.benchmark = True
random.seed(args.seed)
np.random.seed(args.seed)
torch.cuda.manual_seed(args.seed)
torch.manual_seed(args.seed)
solver = Solver(args)
solver.evaluate()
|
@torch.no_grad()
def calculate_metrics(nets, args, step, mode):
print('Calculating evaluation metrics...')
assert (mode in ['latent', 'reference'])
device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
domains = os.listdir(args.val_img_dir)
domains.sort()
num_domains = len(do... |
def calculate_fid_for_all_tasks(args, domains, step, mode):
print('Calculating FID for all tasks...')
fid_values = OrderedDict()
for trg_domain in domains:
src_domains = [x for x in domains if (x != trg_domain)]
for src_domain in src_domains:
task = ('%s2%s' % (src_domain, trg_... |
class InceptionV3(nn.Module):
def __init__(self):
super().__init__()
inception = models.inception_v3(pretrained=True)
self.block1 = nn.Sequential(inception.Conv2d_1a_3x3, inception.Conv2d_2a_3x3, inception.Conv2d_2b_3x3, nn.MaxPool2d(kernel_size=3, stride=2))
self.block2 = nn.Sequ... |
def frechet_distance(mu, cov, mu2, cov2):
(cc, _) = linalg.sqrtm(np.dot(cov, cov2), disp=False)
dist = (np.sum(((mu - mu2) ** 2)) + np.trace(((cov + cov2) - (2 * cc))))
return np.real(dist)
|
@torch.no_grad()
def calculate_fid_given_paths(paths, img_size=256, batch_size=50):
print(('Calculating FID given paths %s and %s...' % (paths[0], paths[1])))
device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
inception = InceptionV3().eval().to(device)
loaders = [get_eval_loader(... |
def normalize(x):
return (x / torch.sqrt(x.pow(2).sum((- 1), keepdim=True)))
|
def slerp(a, b, t):
a = normalize(a)
b = normalize(b)
d = (a * b).sum((- 1), keepdim=True)
p = (t * torch.acos(d))
c = normalize((b - (d * a)))
d = ((a * torch.cos(p)) + (c * torch.sin(p)))
return normalize(d)
|
def lerp(a, b, t):
return (a + ((b - a) * t))
|
class Dataset(torch.utils.data.Dataset):
def __init__(self, args: dict, split='train'):
self.args = args
self.split = split
self.sample_length = args['sample_length']
self.size = (self.w, self.h) = (args['w'], args['h'])
if (args['name'] == 'YouTubeVOS'):
vid_l... |
def get_ref_index(length, sample_length):
if (random.uniform(0, 1) > 0.5):
ref_index = random.sample(range(length), sample_length)
ref_index.sort()
else:
pivot = random.randint(0, (length - sample_length))
ref_index = [(pivot + i) for i in range(sample_length)]
return ref_i... |
def get_world_size():
'Find OMPI world size without calling mpi functions\n :rtype: int\n '
if (os.environ.get('PMI_SIZE') is not None):
return int((os.environ.get('PMI_SIZE') or 1))
elif (os.environ.get('OMPI_COMM_WORLD_SIZE') is not None):
return int((os.environ.get('OMPI_COMM_WORL... |
def get_global_rank():
'Find OMPI world rank without calling mpi functions\n :rtype: int\n '
if (os.environ.get('PMI_RANK') is not None):
return int((os.environ.get('PMI_RANK') or 0))
elif (os.environ.get('OMPI_COMM_WORLD_RANK') is not None):
return int((os.environ.get('OMPI_COMM_WOR... |
def get_local_rank():
'Find OMPI local rank without calling mpi functions\n :rtype: int\n '
if (os.environ.get('MPI_LOCALRANKID') is not None):
return int((os.environ.get('MPI_LOCALRANKID') or 0))
elif (os.environ.get('OMPI_COMM_WORLD_LOCAL_RANK') is not None):
return int((os.environ... |
def get_master_ip():
if (os.environ.get('AZ_BATCH_MASTER_NODE') is not None):
return os.environ.get('AZ_BATCH_MASTER_NODE').split(':')[0]
elif (os.environ.get('AZ_BATCHAI_MPI_MASTER_NODE') is not None):
return os.environ.get('AZ_BATCHAI_MPI_MASTER_NODE')
else:
return '127.0.0.1'
|
class AdversarialLoss(nn.Module):
'\n Adversarial loss\n https://arxiv.org/abs/1711.10337\n '
def __init__(self, type='nsgan', target_real_label=1.0, target_fake_label=0.0):
'\n type = nsgan | lsgan | hinge\n '
super(AdversarialLoss, self).__init__()
self.type =... |
class SpectralNorm(object):
_version = 1
def __init__(self, name='weight', n_power_iterations=1, dim=0, eps=1e-12):
self.name = name
self.dim = dim
if (n_power_iterations <= 0):
raise ValueError('Expected n_power_iterations to be positive, but got n_power_iterations={}'.fo... |
class SpectralNormLoadStateDictPreHook(object):
def __init__(self, fn):
self.fn = fn
def __call__(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
fn = self.fn
version = local_metadata.get('spectral_norm', {}).get((fn.name + '.version'), N... |
class SpectralNormStateDictHook(object):
def __init__(self, fn):
self.fn = fn
def __call__(self, module, state_dict, prefix, local_metadata):
if ('spectral_norm' not in local_metadata):
local_metadata['spectral_norm'] = {}
key = (self.fn.name + '.version')
if (key... |
def spectral_norm(module, name='weight', n_power_iterations=1, eps=1e-12, dim=None):
'Applies spectral normalization to a parameter in the given module.\n\n .. math::\n \\mathbf{W}_{SN} = \\dfrac{\\mathbf{W}}{\\sigma(\\mathbf{W})},\n \\sigma(\\mathbf{W}) = \\max_{\\mathbf{h}: \\mathbf{h} \\ne 0} ... |
def remove_spectral_norm(module, name='weight'):
'Removes the spectral normalization reparameterization from a module.\n\n Args:\n module (Module): containing module\n name (str, optional): name of weight parameter\n\n Example:\n >>> m = spectral_norm(nn.Linear(40, 10))\n >>> rem... |
def use_spectral_norm(module, use_sn=False):
if use_sn:
return spectral_norm(module)
return module
|
class Trainer():
def __init__(self, config):
self.config = config
self.epoch = 0
self.iteration = 0
self.train_dataset = Dataset(config['data_loader'], split='train')
self.train_sampler = None
self.train_args = config['trainer']
if config['distributed']:
... |
class BaseNetwork(nn.Module):
def __init__(self):
super(BaseNetwork, self).__init__()
def print_network(self):
if isinstance(self, list):
self = self[0]
num_params = 0
for param in self.parameters():
num_params += param.numel()
print(('Network ... |
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
self.group = [1, 2, 4, 8, 1]
self.layers = nn.ModuleList([nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1), nn.LeakyReL... |
class InpaintGenerator(BaseNetwork):
def __init__(self, init_weights=True):
super(InpaintGenerator, self).__init__()
channel = 256
hidden = 512
stack_num = 8
num_head = 4
kernel_size = (7, 7)
padding = (3, 3)
stride = (3, 3)
output_size = (6... |
class deconv(nn.Module):
def __init__(self, input_channel, output_channel, kernel_size=3, padding=0):
super().__init__()
self.conv = nn.Conv2d(input_channel, output_channel, kernel_size=kernel_size, stride=1, padding=padding)
def forward(self, x):
x = F.interpolate(x, scale_factor=2,... |
class Attention(nn.Module):
"\n Compute 'Scaled Dot Product Attention\n "
def __init__(self, p=0.1):
super(Attention, self).__init__()
self.dropout = nn.Dropout(p=p)
def forward(self, query, key, value, m=None):
scores = (torch.matmul(query, key.transpose((- 2), (- 1))) / m... |
class AddPosEmb(nn.Module):
def __init__(self, n, c):
super(AddPosEmb, self).__init__()
self.pos_emb = nn.Parameter(torch.zeros(1, 1, n, c).float().normal_(mean=0, std=0.02), requires_grad=True)
self.num_vecs = n
def forward(self, x):
(b, n, c) = x.size()
x = x.view(b... |
class SoftSplit(nn.Module):
def __init__(self, channel, hidden, kernel_size, stride, padding, dropout=0.1):
super(SoftSplit, self).__init__()
self.kernel_size = kernel_size
self.t2t = nn.Unfold(kernel_size=kernel_size, stride=stride, padding=padding)
c_in = (reduce((lambda x, y: (... |
class SoftComp(nn.Module):
def __init__(self, channel, hidden, output_size, kernel_size, stride, padding):
super(SoftComp, self).__init__()
self.relu = nn.LeakyReLU(0.2, inplace=True)
c_out = (reduce((lambda x, y: (x * y)), kernel_size) * channel)
self.embedding = nn.Linear(hidden... |
class MultiHeadedAttention(nn.Module):
'\n Take in model size and number of heads.\n '
def __init__(self, d_model, head, p=0.1):
super().__init__()
self.query_embedding = nn.Linear(d_model, d_model)
self.value_embedding = nn.Linear(d_model, d_model)
self.key_embedding = ... |
class FeedForward(nn.Module):
def __init__(self, d_model, p=0.1):
super(FeedForward, self).__init__()
self.conv = nn.Sequential(nn.Linear(d_model, (d_model * 4)), nn.ReLU(inplace=True), nn.Dropout(p=p), nn.Linear((d_model * 4), d_model), nn.Dropout(p=p))
def forward(self, x):
x = sel... |
class FusionFeedForward(nn.Module):
def __init__(self, d_model, p=0.1, n_vecs=None, t2t_params=None):
super(FusionFeedForward, self).__init__()
hd = 1960
self.conv1 = nn.Sequential(nn.Linear(d_model, hd))
self.conv2 = nn.Sequential(nn.ReLU(inplace=True), nn.Dropout(p=p), nn.Linear... |
class TransformerBlock(nn.Module):
'\n Transformer = MultiHead_Attention + Feed_Forward with sublayer connection\n '
def __init__(self, hidden=128, num_head=4, dropout=0.1, n_vecs=None, t2t_params=None):
super().__init__()
self.attention = MultiHeadedAttention(d_model=hidden, head=num_h... |
class Discriminator(BaseNetwork):
def __init__(self, in_channels=3, use_sigmoid=False, use_spectral_norm=True, init_weights=True):
super(Discriminator, self).__init__()
self.use_sigmoid = use_sigmoid
nf = 32
self.conv = nn.Sequential(spectral_norm(nn.Conv3d(in_channels=in_channels... |
def spectral_norm(module, mode=True):
if mode:
return _spectral_norm(module)
return module
|
class MaxPool3dSamePadding(nn.MaxPool3d):
def compute_pad(self, dim, s):
if ((s % self.stride[dim]) == 0):
return max((self.kernel_size[dim] - self.stride[dim]), 0)
else:
return max((self.kernel_size[dim] - (s % self.stride[dim])), 0)
def forward(self, x):
(ba... |
class Unit3D(nn.Module):
def __init__(self, in_channels, output_channels, kernel_shape=(1, 1, 1), stride=(1, 1, 1), padding=0, activation_fn=F.relu, use_batch_norm=True, use_bias=False, name='unit_3d'):
'Initializes Unit3D module.'
super(Unit3D, self).__init__()
self._output_channels = ou... |
class InceptionModule(nn.Module):
def __init__(self, in_channels, out_channels, name):
super(InceptionModule, self).__init__()
self.b0 = Unit3D(in_channels=in_channels, output_channels=out_channels[0], kernel_shape=[1, 1, 1], padding=0, name=(name + '/Branch_0/Conv3d_0a_1x1'))
self.b1a = ... |
class InceptionI3d(nn.Module):
'Inception-v1 I3D architecture.\n The model is introduced in:\n Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset\n Joao Carreira, Andrew Zisserman\n https://arxiv.org/pdf/1705.07750v1.pdf.\n See also the Inception architecture, introduce... |
def main_worker(rank, config):
if ('local_rank' not in config):
config['local_rank'] = config['global_rank'] = rank
if config['distributed']:
torch.cuda.set_device(int(config['local_rank']))
torch.distributed.init_process_group(backend='nccl', init_method=config['init_method'], world_s... |
def train(model, dataset_paths, save_every, steps, save_path, bsize):
data_dicts = []
for d_path in dataset_paths:
data_dicts.extend(pkl.load(open(d_path, 'rb')))
print(('%d datapoints' % len(data_dicts)))
random.shuffle(data_dicts)
no_decay = ['bias', 'LayerNorm.weight']
optimizer_gro... |
def normalize(t):
return re.sub("'(.+)'", '\\1', t.lower())
|
def qc2input(d):
return normalize(((d['q'] + '\\n') + d['c']))
|
class BERTZeroShotClfQA(torch.nn.Module):
def __init__(self, model_name, max_seq_length=128):
super(BERTZeroShotClfQA, self).__init__()
if (max_seq_length > 128):
raise Exception('We only trained our model for context length 128. Feel free to remove this if you are training your own m... |
def get_id_from_path_name(p: str):
bname = os.path.basename(p)
return int(bname.split('_')[0].replace('group', ''))
|
def get_name_from_path_name(p):
bname = os.path.basename(p)
return bname.split('_')[1].split('.')[0]
|
def split(ids, train, val, test):
assert (((train + val) + test) == 1)
IDs = np.unique(ids)
num_ids = len(IDs)
test_split = math.ceil((test * num_ids))
val_split = math.ceil((val * num_ids))
train_split = ((num_ids - val_split) - test_split)
train = np.where(np.isin(ids, IDs[:train_split])... |
class EEGViT_raw(nn.Module):
def __init__(self, ViTLayers):
super().__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=256, kernel_size=(1, 36), stride=(1, 36), padding=(0, 2), bias=False)
self.batchnorm1 = nn.BatchNorm2d(256, False)
config = transformers.ViTConfig(hidd... |
class EEGViT_pretrained(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=256, kernel_size=(1, 36), stride=(1, 36), padding=(0, 2), bias=False)
self.batchnorm1 = nn.BatchNorm2d(256, False)
model_name = 'google/vit-base-patch16-22... |
class ViTBase(nn.Module):
def __init__(self):
super().__init__()
config = transformers.ViTConfig(hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, initializer_range=0.02, num_channels=1, image_size=(12... |
class ViTBase_pretrained(nn.Module):
def __init__(self):
super().__init__()
model_name = 'google/vit-base-patch16-224'
config = transformers.ViTConfig.from_pretrained(model_name)
config.update({'num_channels': 1})
config.update({'image_size': (129, 500)})
config.up... |
def scot(X, y, k, e, rho=1, mode='connectivity', metric='correlation', XontoY=True, returnCoupling=False, balanced=True):
'\n\tGiven two datasets (X and y) and \n\tthe hyperparameters (k: number of neighbors to be used in kNN graph construction; and e: eplison value in entropic regularization),\n\treturns the res... |
def search_scot(X, y, ks, es, plot_values=False):
X_sampleNo = X.shape[0]
y_sampleNo = y.shape[0]
p = ot.unif(X_sampleNo)
q = ot.unif(y_sampleNo)
k_plot = []
e_plot = []
g_plot = []
total = (len(es) * len(ks))
counter = 0
for k in ks:
Cx = ut.get_graph_distance_matrix(X... |
def unsupervised_scot(X, y, XontoY=True):
n = min(X.shape[0], y.shape[0])
k_best = min((n // 5), 50)
es = np.logspace((- 2), (- 3), 6)
(g1, k1, e1) = search_scot(X, y, [k_best], es, plot_values=True)
gmin = np.min(g1)
gminI = np.argmin(g1)
e_best = e1[gminI]
if (n > 250):
ks = ... |
def unit_normalize(data, norm='l2', bySample=True):
'\n\tDefault norm used is l2-norm. Other options: "l1", and "max"\n\tIf bySample==True, then we independently normalize each sample. If bySample==False, then we independently normalize each feature\n\t'
assert (norm in ['l1', 'l2', 'max']), "Norm argument ha... |
def zscore_standardize(data):
scaler = StandardScaler()
scaledData = scaler.fit_transform(data)
return scaledData
|
def get_spatial_distance_matrix(data, metric='eucledian'):
Cdata = sp.spatial.distance.cdist(data, data, metric=metric)
return (Cdata / Cdata.max())
|
def get_graph_distance_matrix(data, num_neighbors, mode='distance', metric='minkowski'):
'\n\tThe default distance metric used with sklearn kneighbors_graph is ‘euclidean’ (‘minkowski’ metric with the p param equal to 2.). \n\tThat\'s why metric is set to "minkowski". If set to something else, it\'s possible we m... |
def transport_data(source, target, couplingMatrix, transposeCoupling=False):
'\n\tGiven: data in the target space, data in the source space, a coupling matrix learned via Gromow-Wasserstein OT\n\tReturns: \n\n\ttransposeCoupling would need to be True only when the coupling matrix is of the form \n\t'
if (tran... |
class BaseFuzzer():
def __init__(self, elements: List, p: float, max_l0: float=float('inf')):
self.elements = [e for e in elements if (e is not None)]
self.p = (p if (len(self.elements) != 0) else 1)
self.max_l0 = max_l0
self.rand_elements = []
def one_sample(self):
r... |
class BoolFuzzer(BaseFuzzer):
def __init__(self, elements, p):
super(BoolFuzzer, self).__init__(elements, p)
def one_sample(self):
if ((random.random() < self.p) or (len(self.elements) == 0)):
return (random.random() < 0.5)
else:
return random.choice(self.elem... |
class BitFuzzer(BaseFuzzer):
def __init__(self, elements, p):
super(BitFuzzer, self).__init__(elements, p)
def one_sample(self):
if ((random.random() < self.p) or (len(self.elements) == 0)):
return (1 if (random.random() < 0.5) else 0)
else:
return random.choi... |
def random_date(start, end):
delta = (end - start)
int_delta = ((((delta.days * 24) * 60) * 60) + delta.seconds)
random_second = random.randrange(int_delta)
return (start + timedelta(seconds=random_second))
|
class DateFuzzer(BaseFuzzer):
def __init__(self, elements, p=0.5, max_l0=float('inf')):
super(DateFuzzer, self).__init__(elements, p, max_l0)
self.template = '%Y-%m-%d %H:%M:%S'
template_found = False
self.orig_type = str
element_dates = []
for element in elements:... |
def random_choices(l: List[E], k: int) -> List[E]:
if (len(l) == 0):
return [None for _ in range(k)]
idxes = [random.randint(0, (len(l) - 1)) for _ in range(k)]
return [l[idx] for idx in idxes]
|
def get_fuzzer_from_type_str(dtype_str: str, elements: List, p=0.5, max_l0=float('inf')) -> BaseFuzzer:
elements = [e for e in elements if (random.random() > ELEMENT_DROPOUT)]
dtype_str = dtype_str.lower()
if (dtype_str == 'time'):
return TimeFuzzer(elements, p=p, max_l0=max_l0)
if ((dtype_str... |
def filter_by_primary(column2elements: Dict[(str, List)], primary_keys: List[str]) -> Dict[(str, List)]:
if (len(primary_keys) == 0):
return column2elements
num_elements = len(column2elements[primary_keys[0]])
(filtered_idx, existing_keys) = (set(), set())
for idx in range(num_elements):
... |
def filter_by_unique_keys(column2elements: Dict[(str, List)], unique_keys: Set[str]) -> Dict[(str, List)]:
for k in unique_keys:
column2elements = filter_by_primary(column2elements, [k])
return column2elements
|
def restore_order(column2elements: Dict[(str, List)], column_order: List[str]) -> Dict[(str, List)]:
result = OrderedDict()
for column in column_order:
result[column] = column2elements[column]
return result
|
def rand_lin(x: int, min_c: int=MIN_C) -> int:
return (min_c + int(((random.random() * ADDITIVE_C) + (x * (random.random() * MULTIPLICATIVE_C)))))
|
class DBFuzzer():
def __init__(self, sqlite_path: str, tab_col2values: Dict[(Tuple[(str, str)], List[str])], p: float=0.2):
self.sqlite_path = sqlite_path
self.values = tab_col2values
(self.table_column_properties, self.child2parent, self.table_column2elements) = get_all_db_info_path(sqli... |
def fuzz_db_wrapper(args: Tuple[(str, str, Dict[(Tuple[(str, str)], List[str])])]):
(orig_path, target_path, tab_col2values) = args
print(('now fuzzing based on database %s, target path %s.' % (orig_path, target_path)))
dbfuzzer = DBFuzzer(orig_path, tab_col2values)
tables = dbfuzzer.get_fuzz()
wr... |
def generate_random_db_with_queries_wrapper(args: Tuple[(str, str, List[str], Dict[(str, str)])]):
(orig_path, target_path, queries, _) = args
typed_values = list(chain(*[extract_typed_value_in_comparison_from_query(query) for query in queries]))
tab_col2values = type_values_w_db(orig_path, typed_values, ... |
def count_table_occurences(query_toks: List[str], table_names: List[str]) -> int:
counter = 0
for t in query_toks:
if (t.lower() in table_names):
counter += 1
return counter
|
def _other_toks_same_family(tok: Token, family: Set[str]) -> List[Token]:
(t, v) = (tok.ttype, tok.value)
result = []
if ((v.lower() in family) or (v.upper() in family)):
for s in family:
if ((v.lower() != s) and (v.upper() != s)):
result.append(Token(t, s))
return ... |
def _get_int_replacement(tok: Token) -> List[Token]:
result = []
if (tok.ttype == tokens.Token.Literal.Number.Integer):
v = int(tok.value)
random_ints = np.random.randint(((- np.abs(v)) - 1), (np.abs(v) + 1), NUM_ALTERNATIVES)
for r in random_ints:
if (r != v):
... |
def _get_float_replacement(tok: Token) -> List[Token]:
result = []
if (tok.ttype == tokens.Token.Literal.Number.Float):
v = float(tok.value)
random_vals = [(((np.random.random() * 2) * v) - v) for _ in range(NUM_ALTERNATIVES)]
for r in random_vals:
if (r != v):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.