code stringlengths 17 6.64M |
|---|
def main():
parser = argparse.ArgumentParser(description='Export the Napolab benchmark datasets as CSV')
parser.add_argument('--output_path', type=str, default=os.getcwd(), help='The path where datasets will be saved. Default is the current directory.')
parser.add_argument('--include_translations', type=b... |
class DatasetLoader():
'\n A class responsible for loading the datasets of the Napolab benchmark and performing various preprocessing operations.\n\n Attributes:\n DATASET_NAMES (list): List of supported dataset names.\n SELECTED_COLUMNS (dict): Columns to select from datasets.\n RENAME... |
def load_napolab_benchmark(include_translations=True):
" \n Load the Napolab benchmark datasets, and optionally their translations.\n\n Args:\n include_translations (bool): Determines if translated versions of the datasets should be \n loaded. Defaults to True.\n\n Returns:\n dict: A... |
def export_napolab_benchmark(output_path, include_translations=True):
'\n Load the Napolab benchmark datasets using load_napolab_benchmark and save each split of \n each dataset as CSV in a structured hierarchy of folders and subfolders.\n \n Args:\n output_path (str): The path where datasets w... |
def test_validate_parameters_invalid_dataset_name():
with pytest.raises(ValueError):
loader.validate_parameters('invalid_dataset_name', 'portuguese', 'full')
|
def test_validate_parameters_invalid_language():
with pytest.raises(ValueError):
loader.validate_parameters('assin', 'invalid_language', 'full')
|
def test_validate_parameters_invalid_variant():
with pytest.raises(ValueError):
loader.validate_parameters('assin', 'portuguese', 'invalid_variant')
|
def test_get_dataset_name_non_assin():
assert (loader.get_dataset_name('rerelem', 'english') == 'ruanchaves/rerelem_por_Latn_to_eng_Latn')
|
def test_get_dataset_name_assin():
assert (loader.get_dataset_name('assin', 'portuguese') == 'assin')
|
def test_get_dataset_name_assin_other_language():
assert (loader.get_dataset_name('assin', 'english') == 'ruanchaves/assin_por_Latn_to_eng_Latn')
|
def load_config():
return yaml.load(open((Path(__file__).parent / 'config.yml'), 'r'), Loader=yaml.FullLoader)
|
def check_os_environ(key, use):
if (key not in os.environ):
raise ValueError(f'{key} is not defined in the os variables, it is required for {use}.')
|
def dataset_dir():
check_os_environ('DATASET', 'data loading')
return os.environ['DATASET']
|
class ADE20KSegmentation(BaseMMSeg):
def __init__(self, image_size, crop_size, split, **kwargs):
super().__init__(image_size, crop_size, split, ADE20K_CONFIG_PATH, **kwargs)
(self.names, self.colors) = utils.dataset_cat_description(ADE20K_CATS_PATH)
self.n_cls = 150
self.ignore_la... |
class BaseMMSeg(Dataset):
def __init__(self, image_size, crop_size, split, config_path, normalization, **kwargs):
super().__init__()
self.image_size = image_size
self.crop_size = crop_size
self.split = split
self.normalization = STATS[normalization].copy()
self.ign... |
class CityscapesDataset(BaseMMSeg):
def __init__(self, image_size, crop_size, split, **kwargs):
super().__init__(image_size, crop_size, split, CITYSCAPES_CONFIG_PATH, **kwargs)
(self.names, self.colors) = utils.dataset_cat_description(CITYSCAPES_CATS_PATH)
self.n_cls = 19
self.ign... |
def create_dataset(dataset_kwargs):
dataset_kwargs = dataset_kwargs.copy()
dataset_name = dataset_kwargs.pop('dataset')
batch_size = dataset_kwargs.pop('batch_size')
num_workers = dataset_kwargs.pop('num_workers')
split = dataset_kwargs.pop('split')
if (dataset_name == 'imagenet'):
dat... |
class ImagenetDataset(Dataset):
def __init__(self, root_dir, image_size=224, crop_size=224, split='train', normalization='vit'):
super().__init__()
assert (image_size[0] == image_size[1])
self.path = (Path(root_dir) / split)
self.crop_size = crop_size
self.image_size = ima... |
class Loader(DataLoader):
def __init__(self, dataset, batch_size, num_workers, distributed, split):
if distributed:
sampler = DistributedSampler(dataset, shuffle=True)
super().__init__(dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers, pin_memory=True, sampler... |
class PascalContextDataset(BaseMMSeg):
def __init__(self, image_size, crop_size, split, **kwargs):
super().__init__(image_size, crop_size, split, PASCAL_CONTEXT_CONFIG_PATH, **kwargs)
(self.names, self.colors) = utils.dataset_cat_description(PASCAL_CONTEXT_CATS_PATH)
self.n_cls = 60
... |
def train_one_epoch(model, data_loader, optimizer, lr_scheduler, epoch, amp_autocast, loss_scaler):
criterion = torch.nn.CrossEntropyLoss(ignore_index=IGNORE_LABEL)
logger = MetricLogger(delimiter=' ')
header = f'Epoch: [{epoch}]'
print_freq = 100
model.train()
data_loader.set_epoch(epoch)
... |
@torch.no_grad()
def evaluate(model, data_loader, val_seg_gt, window_size, window_stride, amp_autocast):
model_without_ddp = model
if hasattr(model, 'module'):
model_without_ddp = model.module
logger = MetricLogger(delimiter=' ')
header = 'Eval:'
print_freq = 50
val_seg_pred = {}
... |
def compute_labels(model, batch):
im = batch['im']
target = batch['target']
with torch.no_grad():
with torch.cuda.amp.autocast():
output = model.forward(im)
(acc1, acc5) = accuracy(output, target, topk=(1, 5))
return (acc1.item(), acc5.item())
|
def eval_dataset(model, dataset_kwargs):
db = create_dataset(dataset_kwargs)
print_freq = 20
header = ''
logger = MetricLogger(delimiter=' ')
for batch in logger.log_every(db, print_freq, header):
for (k, v) in batch.items():
batch[k] = v.to(ptu.device)
(acc1, acc5) = ... |
@click.command()
@click.argument('backbone', type=str)
@click.option('--imagenet-dir', type=str)
@click.option('-bs', '--batch-size', default=32, type=int)
@click.option('-nw', '--num-workers', default=10, type=int)
@click.option('-gpu', '--gpu/--no-gpu', default=True, is_flag=True)
def main(backbone, imagenet_dir, b... |
def blend_im(im, seg, alpha=0.5):
pil_im = Image.fromarray(im)
pil_seg = Image.fromarray(seg)
im_blend = Image.blend(pil_im, pil_seg, alpha).convert('RGB')
return np.asarray(im_blend)
|
def save_im(save_dir, save_name, im, seg_pred, seg_gt, colors, blend, normalization):
seg_rgb = seg_to_rgb(seg_gt[None], colors)
pred_rgb = seg_to_rgb(seg_pred[None], colors)
im_unnorm = rgb_denormalize(im, normalization)
save_dir = Path(save_dir)
im_uint = im_unnorm.permute(0, 2, 3, 1).cpu().nump... |
def process_batch(model, batch, window_size, window_stride, window_batch_size):
ims = batch['im']
ims_metas = batch['im_metas']
ori_shape = ims_metas[0]['ori_shape']
ori_shape = (ori_shape[0].item(), ori_shape[1].item())
filename = batch['im_metas'][0]['ori_filename'][0]
model_without_ddp = mo... |
def eval_dataset(model, multiscale, model_dir, blend, window_size, window_stride, window_batch_size, save_images, frac_dataset, dataset_kwargs):
db = create_dataset(dataset_kwargs)
normalization = db.dataset.normalization
dataset_name = dataset_kwargs['dataset']
im_size = dataset_kwargs['image_size']
... |
@click.command()
@click.argument('model_path', type=str)
@click.argument('dataset_name', type=str)
@click.option('--im-size', default=None, type=int)
@click.option('--multiscale/--singlescale', default=False, is_flag=True)
@click.option('--blend/--no-blend', default=True, is_flag=True)
@click.option('--window-size', ... |
@click.command()
@click.option('--model-path', type=str)
@click.option('--input-dir', '-i', type=str, help='folder with input images')
@click.option('--output-dir', '-o', type=str, help='folder with output images')
@click.option('--gpu/--cpu', default=True, is_flag=True)
def main(model_path, input_dir, output_dir, gp... |
def accuracy(output, target, topk=(1,)):
'\n https://github.com/pytorch/examples/blob/master/imagenet/main.py\n Computes the accuracy over the k top predictions for the specified values of k\n '
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
(_, pred) = out... |
def gather_data(seg_pred, tmp_dir=None):
'\n distributed data gathering\n prediction and ground truth are stored in a common tmp directory\n and loaded on the master node to compute metrics\n '
if (tmp_dir is None):
tmpprefix = os.path.expandvars('$DATASET/temp')
else:
tmpprefi... |
def compute_metrics(seg_pred, seg_gt, n_cls, ignore_index=None, ret_cat_iou=False, tmp_dir=None, distributed=False):
ret_metrics_mean = torch.zeros(3, dtype=float, device=ptu.device)
if (ptu.dist_rank == 0):
list_seg_pred = []
list_seg_gt = []
keys = sorted(seg_pred.keys())
for... |
class FeedForward(nn.Module):
def __init__(self, dim, hidden_dim, dropout, out_dim=None):
super().__init__()
self.fc1 = nn.Linear(dim, hidden_dim)
self.act = nn.GELU()
if (out_dim is None):
out_dim = dim
self.fc2 = nn.Linear(hidden_dim, out_dim)
self.dr... |
class Attention(nn.Module):
def __init__(self, dim, heads, dropout):
super().__init__()
self.heads = heads
head_dim = (dim // heads)
self.scale = (head_dim ** (- 0.5))
self.attn = None
self.qkv = nn.Linear(dim, (dim * 3))
self.attn_drop = nn.Dropout(dropout... |
class Block(nn.Module):
def __init__(self, dim, heads, mlp_dim, dropout, drop_path):
super().__init__()
self.norm1 = nn.LayerNorm(dim)
self.norm2 = nn.LayerNorm(dim)
self.attn = Attention(dim, heads, dropout)
self.mlp = FeedForward(dim, mlp_dim, dropout)
self.drop_... |
@register_model
def vit_base_patch8_384(pretrained=False, **kwargs):
'ViT-Base model (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929).\n ImageNet-1k weights fine-tuned from in21k @ 384x384, source https://github.com/google-research/vision_transformer.\n '
model_kwargs = dict(patch_size=... |
def create_vit(model_cfg):
model_cfg = model_cfg.copy()
backbone = model_cfg.pop('backbone')
normalization = model_cfg.pop('normalization')
model_cfg['n_cls'] = 1000
mlp_expansion_ratio = 4
model_cfg['d_ff'] = (mlp_expansion_ratio * model_cfg['d_model'])
if (backbone in default_cfgs):
... |
def create_decoder(encoder, decoder_cfg):
decoder_cfg = decoder_cfg.copy()
name = decoder_cfg.pop('name')
decoder_cfg['d_encoder'] = encoder.d_model
decoder_cfg['patch_size'] = encoder.patch_size
if ('linear' in name):
decoder = DecoderLinear(**decoder_cfg)
elif (name == 'mask_transfor... |
def create_segmenter(model_cfg):
model_cfg = model_cfg.copy()
decoder_cfg = model_cfg.pop('decoder')
decoder_cfg['n_cls'] = model_cfg['n_cls']
encoder = create_vit(model_cfg)
decoder = create_decoder(encoder, decoder_cfg)
model = Segmenter(encoder, decoder, n_cls=model_cfg['n_cls'])
return... |
def load_model(model_path):
variant_path = (Path(model_path).parent / 'variant.yml')
with open(variant_path, 'r') as f:
variant = yaml.load(f, Loader=yaml.FullLoader)
net_kwargs = variant['net_kwargs']
model = create_segmenter(net_kwargs)
data = torch.load(model_path, map_location=ptu.devi... |
def create_scheduler(opt_args, optimizer):
if (opt_args.sched == 'polynomial'):
lr_scheduler = PolynomialLR(optimizer, opt_args.poly_step_size, opt_args.iter_warmup, opt_args.iter_max, opt_args.poly_power, opt_args.min_lr)
else:
(lr_scheduler, _) = scheduler.create_scheduler(opt_args, optimize... |
def create_optimizer(opt_args, model):
return optim.create_optimizer(opt_args, model)
|
class PolynomialLR(_LRScheduler):
def __init__(self, optimizer, step_size, iter_warmup, iter_max, power, min_lr=0, last_epoch=(- 1)):
self.step_size = step_size
self.iter_warmup = int(iter_warmup)
self.iter_max = int(iter_max)
self.power = power
self.min_lr = min_lr
... |
def download_ade(path, overwrite=False):
_AUG_DOWNLOAD_URLS = [('http://data.csail.mit.edu/places/ADEchallenge/ADEChallengeData2016.zip', '219e1696abb36c8ba3a3afe7fb2f4b4606a897c7'), ('http://data.csail.mit.edu/places/ADEchallenge/release_test.zip', 'e05747892219d10e9243933371a497e905a4860c')]
download_dir = ... |
@click.command(help='Initialize ADE20K dataset.')
@click.argument('download_dir', type=str)
def main(download_dir):
dataset_dir = (Path(download_dir) / 'ade20k')
download_ade(dataset_dir, overwrite=False)
|
def download_cityscapes(path, username, password, overwrite=False):
_CITY_DOWNLOAD_URLS = [('gtFine_trainvaltest.zip', '99f532cb1af174f5fcc4c5bc8feea8c66246ddbc'), ('leftImg8bit_trainvaltest.zip', '2c0b77ce9933cc635adda307fbba5566f5d9d404')]
download_dir = (path / 'downloads')
download_dir.mkdir(parents=T... |
def install_cityscapes_api():
os.system('pip install cityscapesscripts')
try:
import cityscapesscripts
except Exception:
print(('Installing Cityscapes API failed, please install it manually %s' % repo_url))
|
def convert_json_to_label(json_file):
from cityscapesscripts.preparation.json2labelImg import json2labelImg
label_file = json_file.replace('_polygons.json', '_labelTrainIds.png')
json2labelImg(json_file, label_file, 'trainIds')
|
@click.command(help='Initialize Cityscapes dataset.')
@click.argument('download_dir', type=str)
@click.option('--username', default=USERNAME, type=str)
@click.option('--password', default=PASSWORD, type=str)
@click.option('--nproc', default=10, type=int)
def main(download_dir, username, password, nproc):
dataset_... |
def download_pcontext(path, overwrite=False):
_AUG_DOWNLOAD_URLS = [('https://www.dropbox.com/s/wtdibo9lb2fur70/VOCtrainval_03-May-2010.tar?dl=1', 'VOCtrainval_03-May-2010.tar', 'bf9985e9f2b064752bf6bd654d89f017c76c395a'), ('https://codalabuser.blob.core.windows.net/public/trainval_merged.json', '', '169325d9f7e9... |
@click.command(help='Initialize PASCAL Context dataset.')
@click.argument('download_dir', type=str)
def main(download_dir):
dataset_dir = (Path(download_dir) / 'pcontext')
download_pcontext(dataset_dir, overwrite=False)
devkit_path = (dataset_dir / 'VOCdevkit')
out_dir = ((devkit_path / 'VOC2010') / '... |
@click.command(help='')
@click.option('--log-dir', type=str, help='logging directory')
@click.option('--dataset', type=str)
@click.option('--im-size', default=None, type=int, help='dataset resize size')
@click.option('--crop-size', default=None, type=int)
@click.option('--window-size', default=None, type=int)
@click.... |
def init_process(backend='nccl'):
print(f'Starting process with rank {ptu.dist_rank}...', flush=True)
if ('SLURM_STEPS_GPUS' in os.environ):
gpu_ids = os.environ['SLURM_STEP_GPUS'].split(',')
os.environ['MASTER_PORT'] = str((12345 + int(min(gpu_ids))))
else:
os.environ['MASTER_PORT... |
def silence_print(is_master):
'\n This function disables printing when not in master process\n '
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop('force', False)
if (is_master or force):
builtin_print(*ar... |
def sync_model(sync_dir, model):
sync_path = (Path(sync_dir).resolve() / 'sync_model.pkl')
if ((ptu.dist_rank == 0) and (ptu.world_size > 1)):
torch.save(model.state_dict(), sync_path)
dist.barrier()
if (ptu.dist_rank > 0):
model.load_state_dict(torch.load(sync_path))
dist.barrier(... |
def barrier():
dist.barrier()
|
def destroy_process():
dist.destroy_process_group()
|
def check_sha1(filename, sha1_hash):
'Check whether the sha1 hash of the file content matches the expected hash.\n Parameters\n ----------\n filename : str\n Path to the file.\n sha1_hash : str\n Expected sha1 hash in hexadecimal digits.\n Returns\n -------\n bool\n Wheth... |
def download(url, path=None, overwrite=False, sha1_hash=None):
"\n https://github.com/junfu1115/DANet/blob/master/encoding/utils/files.py\n Download a given URL\n Parameters\n ----------\n url : str\n URL to download\n path : str, optional\n Destination path to store downloaded fil... |
class SmoothedValue(object):
'Track a series of values and provide access to smoothed values over a\n window or the global series average.\n '
def __init__(self, window_size=20, fmt=None):
if (fmt is None):
fmt = '{median:.4f} ({global_avg:.4f})'
self.deque = deque(maxlen=wi... |
class MetricLogger(object):
def __init__(self, delimiter='\t'):
self.meters = defaultdict(SmoothedValue)
self.delimiter = delimiter
def update(self, n=1, **kwargs):
for (k, v) in kwargs.items():
if isinstance(v, torch.Tensor):
v = v.item()
asse... |
def is_dist_avail_and_initialized():
if (not dist.is_available()):
return False
if (not dist.is_initialized()):
return False
return True
|
def set_gpu_mode(mode):
global use_gpu
global device
global gpu_id
global distributed
global dist_rank
global world_size
gpu_id = int(os.environ.get('SLURM_LOCALID', 0))
dist_rank = int(os.environ.get('SLURM_PROCID', 0))
world_size = int(os.environ.get('SLURM_NTASKS', 1))
distr... |
def read_requirements_file(filename):
req_file_path = path.join(path.dirname(path.realpath(__file__)), filename)
with open(req_file_path) as f:
return [line.strip() for line in f]
|
def build_optimizer(model, length_train_loader, config):
optimizer_class = getattr(transformers, 'AdamW')
optimizer = optimizer_class(model.model.parameters(), lr=float(config['lr']))
num_training_steps = (config['train_epochs'] * length_train_loader)
lr_scheduler = get_scheduler(name='linear', optimi... |
def build_model(config):
available_models = ['bertqa', 'longformer', 'bigbird', 'layoutlmv2', 'layoutlmv3', 't5', 'vt5', 'hi-vt5']
if ((config['model_name'].lower() == 'bert') or (config['model_name'].lower() == 'bertqa')):
from models.BertQA import BertQA
model = BertQA(config)
elif (conf... |
def build_dataset(config, split):
dataset_kwargs = {}
if (config['model_name'].lower() in ['layoutlmv2', 'layoutlmv3', 'lt5', 'vt5', 'hilt5', 'hi-lt5', 'hivt5', 'hi-vt5']):
dataset_kwargs['get_raw_ocr_data'] = True
if (config['model_name'].lower() in ['layoutlmv2', 'layoutlmv3', 'vt5', 'hivt5', 'h... |
def save_model(model, epoch, update_best=False, **kwargs):
save_dir = os.path.join(kwargs['save_dir'], 'checkpoints', '{:s}_{:s}_{:s}'.format(kwargs['model_name'].lower(), kwargs.get('page_retrieval', '').lower(), kwargs['dataset_name'].lower()))
model.model.save_pretrained(os.path.join(save_dir, 'model__{:d}... |
def load_model(base_model, ckpt_name, **kwargs):
load_dir = kwargs['save_dir']
base_model.model.from_pretrained(os.path.join(load_dir, ckpt_name))
|
class DUDE(MPDocVQA):
def __init__(self, imbd_dir, images_dir, page_retrieval, split, kwargs):
super(DUDE, self).__init__(imbd_dir, images_dir, page_retrieval, split, kwargs)
if (self.page_retrieval == 'oracle'):
raise ValueError("'Oracle' set-up is not valid for DUDE, since there is ... |
class MPDocVQA(Dataset):
def __init__(self, imbd_dir, images_dir, page_retrieval, split, kwargs):
data = np.load(os.path.join(imbd_dir, 'imdb_{:s}.npy'.format(split)), allow_pickle=True)
self.header = data[0]
self.imdb = data[1:]
self.page_retrieval = page_retrieval.lower()
... |
def mpdocvqa_collate_fn(batch):
batch = {k: [dic[k] for dic in batch] for k in batch[0]}
return batch
|
class SPDocVQA(Dataset):
def __init__(self, imbd_dir, images_dir, split, kwargs):
data = np.load(os.path.join(imbd_dir, 'new_imdb_{:s}.npy'.format(split)), allow_pickle=True)
self.header = data[0]
self.imdb = data[1:]
self.hierarchical_method = kwargs.get('hierarchical_method', Fa... |
def singlepage_docvqa_collate_fn(batch):
batch = {k: [dic[k] for dic in batch] for k in batch[0]}
return batch
|
def evaluate(data_loader, model, evaluator, **kwargs):
return_scores_by_sample = kwargs.get('return_scores_by_sample', False)
return_answers = kwargs.get('return_answers', False)
if return_scores_by_sample:
scores_by_samples = {}
total_accuracies = []
total_anls = []
total_... |
class Logger():
def __init__(self, config):
self.log_folder = config['save_dir']
experiment_date = datetime.datetime.now().strftime('%Y.%m.%d_%H.%M.%S')
self.experiment_name = '{:s}__{:}'.format(config['model_name'], experiment_date)
machine_dict = {'cvc117': 'Local', 'cudahpc16':... |
class Evaluator():
def __init__(self, case_sensitive=False):
self.case_sensitive = case_sensitive
self.get_edit_distance = editdistance.eval
self.anls_threshold = 0.5
self.total_accuracies = []
self.total_anls = []
self.best_accuracy = 0
self.best_epoch = 0... |
class BertQA():
def __init__(self, config):
self.batch_size = config['batch_size']
self.model = AutoModelForQuestionAnswering.from_pretrained(config['model_weights'])
self.tokenizer = AutoTokenizer.from_pretrained(config['model_weights'])
self.page_retrieval = (config['page_retrie... |
class BigBird():
def __init__(self, config):
self.batch_size = config['batch_size']
self.tokenizer = BigBirdTokenizerFast.from_pretrained(config['model_weights'])
self.model = BigBirdForQuestionAnswering.from_pretrained(config['model_weights'])
self.page_retrieval = (config['page_... |
class LayoutLMv2():
def __init__(self, config):
self.batch_size = config['batch_size']
self.processor = LayoutLMv2Processor.from_pretrained(config['model_weights'], apply_ocr=False)
self.model = LayoutLMv2ForQuestionAnswering.from_pretrained(config['model_weights'])
self.page_retr... |
class LayoutLMv3():
def __init__(self, config):
self.batch_size = config['batch_size']
self.processor = LayoutLMv3Processor.from_pretrained(config['model_weights'], apply_ocr=False)
self.model = LayoutLMv3ForQuestionAnswering.from_pretrained(config['model_weights'])
self.page_retr... |
class LongT5():
def __init__(self, config):
self.batch_size = config['batch_size']
self.tokenizer = AutoTokenizer.from_pretrained(config['model_weights'])
self.model = LongT5ForConditionalGeneration.from_pretrained(config['model_weights'])
self.page_retrieval = (config['page_retri... |
class Longformer():
def __init__(self, config):
self.batch_size = config['batch_size']
self.tokenizer = LongformerTokenizerFast.from_pretrained(config['model_weights'])
self.model = LongformerForQuestionAnswering.from_pretrained(config['model_weights'])
self.page_retrieval = (conf... |
class T5():
def __init__(self, config):
self.batch_size = config['batch_size']
self.tokenizer = T5Tokenizer.from_pretrained(config['model_weights'])
self.model = T5ForConditionalGeneration.from_pretrained(config['model_weights'])
self.page_retrieval = (config['page_retrieval'].low... |
def train_epoch(data_loader, model, optimizer, lr_scheduler, evaluator, logger, **kwargs):
model.model.train()
for (batch_idx, batch) in enumerate(tqdm(data_loader)):
gt_answers = batch['answers']
(outputs, pred_answers, pred_answer_page, answer_conf) = model.forward(batch, return_pred_answer=... |
def train(model, **kwargs):
epochs = kwargs['train_epochs']
batch_size = kwargs['batch_size']
seed_everything(kwargs['seed'])
evaluator = Evaluator(case_sensitive=False)
logger = Logger(config=kwargs)
logger.log_model_parameters(model)
train_dataset = build_dataset(config, 'train')
val... |
class BouncingBallExample(nn.Module):
def __init__(self, radius=0.2, gravity=9.8, adjoint=False):
super().__init__()
self.gravity = nn.Parameter(torch.as_tensor([gravity]))
self.log_radius = nn.Parameter(torch.log(torch.as_tensor([radius])))
self.t0 = nn.Parameter(torch.tensor([0.... |
def gradcheck(nbounces):
system = BouncingBallExample()
variables = {'init_pos': system.init_pos, 'init_vel': system.init_vel, 't0': system.t0, 'gravity': system.gravity, 'log_radius': system.log_radius}
event_t = system.get_collision_times(nbounces)[(- 1)]
event_t.backward()
analytical_grads = {}... |
class NFEDiffEq():
def __init__(self, diffeq):
self.diffeq = diffeq
self.nfe = 0
def __call__(self, t, y):
self.nfe += 1
return self.diffeq(t, y)
|
def main():
sol = dict()
for method in ['dopri5', 'adams']:
for tol in [0.001, 1e-06, 1e-09]:
print('======= {} | tol={:e} ======='.format(method, tol))
nfes = []
times = []
errs = []
for c in ['A', 'B', 'C', 'D', 'E']:
for i ... |
class TestCollectionState(unittest.TestCase):
def test_forward(self):
for dtype in DTYPES:
eps = EPS[dtype]
for device in DEVICES:
(f, y0, t_points, sol) = construct_problem(dtype=dtype, device=device)
tuple_f = (lambda t, y: (f(t, y[0]), f(t, y[1])... |
def rel_error(true, estimate):
return ((true - estimate) / true).abs().max()
|
class TestEventHandling(unittest.TestCase):
def test_odeint(self):
for reverse in (False, True):
for dtype in DTYPES:
for device in DEVICES:
for method in METHODS:
if (method == 'scipy_solver'):
continue
... |
def max_abs(tensor):
return torch.max(torch.abs(tensor))
|
class TestGradient(unittest.TestCase):
def test_odeint(self):
for device in DEVICES:
for method in METHODS:
if (method == 'scipy_solver'):
continue
with self.subTest(device=device, method=method):
(f, y0, t_points, _) = c... |
class TestCompareAdjointGradient(unittest.TestCase):
def problem(self, device):
class Odefunc(torch.nn.Module):
def __init__(self):
super(Odefunc, self).__init__()
self.A = torch.nn.Parameter(torch.tensor([[(- 0.1), 2.0], [(- 2.0), (- 0.1)]]))
... |
@contextlib.contextmanager
def random_seed_torch(seed):
cpu_rng_state = torch.get_rng_state()
torch.manual_seed(seed)
try:
(yield)
finally:
torch.set_rng_state(cpu_rng_state)
|
class _NeuralF(torch.nn.Module):
def __init__(self, width, oscillate):
super(_NeuralF, self).__init__()
with random_seed_torch(0):
self.linears = torch.nn.Sequential(torch.nn.Linear(2, width), torch.nn.Tanh(), torch.nn.Linear(width, 2), torch.nn.Tanh())
self.nfe = 0
se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.