code stringlengths 17 6.64M |
|---|
def post_assets(assets, release_id):
'Post assets to release'
token = os.environ.get('GITHUB_TOKEN')
headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}', 'Content-Type': 'application/zip'}
for asset in assets:
asset_path = os.path.join(os.getcwd(), asset)
... |
def video_to_frame(video_path: str, output_path: str, fps: int=5):
'\n Convert video to frame\n\n Args:\n video_path: path to video\n output_path: path to output folder\n fps: how many frames per second to save \n '
if (not os.path.exists(output_path)):
os.makedirs(output... |
def generate(video_path, gif_path, fps):
'Generate gif from video'
clip = mpy.VideoFileClip(video_path)
clip.write_gif(gif_path, fps=fps)
clip.close()
|
class KITTIDataModule(LightningDataModule):
def __init__(self, dataset_path: str='./data/KITTI', train_sets: str='./data/KITTI/train.txt', val_sets: str='./data/KITTI/val.txt', test_sets: str='./data/KITTI/test.txt', batch_size: int=32, num_worker: int=4):
super().__init__()
self.save_hyperparame... |
class KITTIDataModule2(LightningDataModule):
def __init__(self, dataset_path: str='./data/KITTI', train_sets: str='./data/KITTI/train.txt', val_sets: str='./data/KITTI/val.txt', test_sets: str='./data/KITTI/test.txt', batch_size: int=32, num_worker: int=4):
super().__init__()
self.save_hyperparam... |
class KITTIDataModule3(LightningDataModule):
def __init__(self, dataset_path: str='./data/KITTI', train_sets: str='./data/KITTI/train.txt', val_sets: str='./data/KITTI/val.txt', test_sets: str='./data/KITTI/test.txt', batch_size: int=32, num_worker: int=4):
super().__init__()
self.save_hyperparam... |
@utils.task_wrapper
def evaluate(cfg: DictConfig) -> Tuple[(dict, dict)]:
'Evaluates given checkpoint on a datamodule testset.\n\n This method is wrapped in optional @task_wrapper decorator which applies extra utilities\n before and after the call.\n\n Args:\n cfg (DictConfig): Configuration compo... |
@hydra.main(version_base='1.2', config_path=(root / 'configs'), config_name='eval.yaml')
def main(cfg: DictConfig) -> None:
evaluate(cfg)
|
class RegressorModel(LightningModule):
def __init__(self, net: nn.Module, optimizer: str='adam', lr: float=0.0001, momentum: float=0.9, w: float=0.4, alpha: float=0.6):
super().__init__()
self.save_hyperparameters(logger=False)
self.net = net
self.conf_loss_func = nn.CrossEntropyL... |
class RegressorModel2(LightningModule):
def __init__(self, net: nn.Module, lr: float=0.0001, momentum: float=0.9, w: float=0.4, alpha: float=0.6):
super().__init__()
self.save_hyperparameters(logger=False)
self.net = net
self.conf_loss_func = nn.CrossEntropyLoss()
self.dim... |
class RegressorModel3(LightningModule):
def __init__(self, net: nn.Module, optimizer: str='adam', lr: float=0.0001, momentum: float=0.9, w: float=0.4, alpha: float=0.6):
super().__init__()
self.save_hyperparameters(logger=False)
self.net = net
self.conf_loss_func = nn.CrossEntropy... |
@utils.task_wrapper
def train(cfg: DictConfig) -> Tuple[(dict, dict)]:
'Trains the model. Can additionally evaluate on a testset, using best weights obtained during\n training.\n\n This method is wrapped in optional @task_wrapper decorator which applies extra utilities\n before and after the call.\n\n ... |
@hydra.main(version_base='1.2', config_path=(root / 'configs'), config_name='train.yaml')
def main(cfg: DictConfig) -> Optional[float]:
(metric_dict, _) = train(cfg)
metric_value = utils.get_metric_value(metric_dict=metric_dict, metric_name=cfg.get('optimized_metric'))
return metric_value
|
class DimensionAverages():
'\n Class to calculate the average dimensions of the objects in the dataset.\n '
def __init__(self, categories: List[str]=['car', 'pedestrian', 'cyclist'], save_file: str='dimension_averages.txt'):
self.dimension_map = {}
self.filename = ((os.path.abspath(os.p... |
class ClassAverages():
def __init__(self, classes=[]):
self.dimension_map = {}
self.filename = (os.path.abspath(os.path.dirname(__file__)) + '/class_averages.txt')
if (len(classes) == 0):
self.load_items_from_file()
for detection_class in classes:
class_ = ... |
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
|
def get_pylogger(name=__name__) -> logging.Logger:
'Initializes multi-GPU-friendly python command line logger.'
logger = logging.getLogger(name)
logging_levels = ('debug', 'info', 'warning', 'error', 'exception', 'fatal', 'critical')
for level in logging_levels:
setattr(logger, level, rank_zer... |
@rank_zero_only
def print_config_tree(cfg: DictConfig, print_order: Sequence[str]=('datamodule', 'model', 'callbacks', 'logger', 'trainer', 'paths', 'extras'), resolve: bool=False, save_to_file: bool=False) -> None:
'Prints content of DictConfig using Rich library and its tree structure.\n\n Args:\n cfg... |
@rank_zero_only
def enforce_tags(cfg: DictConfig, save_to_file: bool=False) -> None:
'Prompts user to input tags from command line if no tags are provided in config.'
if (not cfg.get('tags')):
if ('id' in HydraConfig().cfg.hydra.job):
raise ValueError('Specify tags before launching a multi... |
@numba.jit(nopython=True)
def div_up(m, n):
return ((m // n) + ((m % n) > 0))
|
@cuda.jit('(float32[:], float32[:], float32[:])', device=True, inline=True)
def trangle_area(a, b, c):
return ((((a[0] - c[0]) * (b[1] - c[1])) - ((a[1] - c[1]) * (b[0] - c[0]))) / 2.0)
|
@cuda.jit('(float32[:], int32)', device=True, inline=True)
def area(int_pts, num_of_inter):
area_val = 0.0
for i in range((num_of_inter - 2)):
area_val += abs(trangle_area(int_pts[:2], int_pts[((2 * i) + 2):((2 * i) + 4)], int_pts[((2 * i) + 4):((2 * i) + 6)]))
return area_val
|
@cuda.jit('(float32[:], int32)', device=True, inline=True)
def sort_vertex_in_convex_polygon(int_pts, num_of_inter):
if (num_of_inter > 0):
center = cuda.local.array((2,), dtype=numba.float32)
center[:] = 0.0
for i in range(num_of_inter):
center[0] += int_pts[(2 * i)]
... |
@cuda.jit('(float32[:], float32[:], int32, int32, float32[:])', device=True, inline=True)
def line_segment_intersection(pts1, pts2, i, j, temp_pts):
A = cuda.local.array((2,), dtype=numba.float32)
B = cuda.local.array((2,), dtype=numba.float32)
C = cuda.local.array((2,), dtype=numba.float32)
D = cuda.... |
@cuda.jit('(float32[:], float32[:], int32, int32, float32[:])', device=True, inline=True)
def line_segment_intersection_v1(pts1, pts2, i, j, temp_pts):
a = cuda.local.array((2,), dtype=numba.float32)
b = cuda.local.array((2,), dtype=numba.float32)
c = cuda.local.array((2,), dtype=numba.float32)
d = cu... |
@cuda.jit('(float32, float32, float32[:])', device=True, inline=True)
def point_in_quadrilateral(pt_x, pt_y, corners):
ab0 = (corners[2] - corners[0])
ab1 = (corners[3] - corners[1])
ad0 = (corners[6] - corners[0])
ad1 = (corners[7] - corners[1])
ap0 = (pt_x - corners[0])
ap1 = (pt_y - corners... |
@cuda.jit('(float32[:], float32[:], float32[:])', device=True, inline=True)
def quadrilateral_intersection(pts1, pts2, int_pts):
num_of_inter = 0
for i in range(4):
if point_in_quadrilateral(pts1[(2 * i)], pts1[((2 * i) + 1)], pts2):
int_pts[(num_of_inter * 2)] = pts1[(2 * i)]
... |
@cuda.jit('(float32[:], float32[:])', device=True, inline=True)
def rbbox_to_corners(corners, rbbox):
angle = rbbox[4]
a_cos = math.cos(angle)
a_sin = math.sin(angle)
center_x = rbbox[0]
center_y = rbbox[1]
x_d = rbbox[2]
y_d = rbbox[3]
corners_x = cuda.local.array((4,), dtype=numba.fl... |
@cuda.jit('(float32[:], float32[:])', device=True, inline=True)
def inter(rbbox1, rbbox2):
corners1 = cuda.local.array((8,), dtype=numba.float32)
corners2 = cuda.local.array((8,), dtype=numba.float32)
intersection_corners = cuda.local.array((16,), dtype=numba.float32)
rbbox_to_corners(corners1, rbbox1... |
@cuda.jit('(float32[:], float32[:], int32)', device=True, inline=True)
def devRotateIoUEval(rbox1, rbox2, criterion=(- 1)):
area1 = (rbox1[2] * rbox1[3])
area2 = (rbox2[2] * rbox2[3])
area_inter = inter(rbox1, rbox2)
if (criterion == (- 1)):
return (area_inter / ((area1 + area2) - area_inter))... |
@cuda.jit('(int64, int64, float32[:], float32[:], float32[:], int32)', fastmath=False)
def rotate_iou_kernel_eval(N, K, dev_boxes, dev_query_boxes, dev_iou, criterion=(- 1)):
threadsPerBlock = (8 * 8)
row_start = cuda.blockIdx.x
col_start = cuda.blockIdx.y
tx = cuda.threadIdx.x
row_size = min((N -... |
def rotate_iou_gpu_eval(boxes, query_boxes, criterion=(- 1), device_id=0):
'rotated box iou running in gpu. 500x faster than cpu version\n (take 5ms in one example with numba.cuda code).\n convert from [this project](\n https://github.com/hongzhenwang/RRPN-revise/tree/master/lib/rotation).\n \n ... |
@pytest.fixture(scope='package')
def cfg_train_global() -> DictConfig:
with initialize(version_base='1.2', config_path='../configs'):
cfg = compose(config_name='train.yaml', return_hydra_config=True, overrides=[])
with open_dict(cfg):
cfg.paths.root_dir = str(pyrootutils.find_root())
... |
@pytest.fixture(scope='package')
def cfg_eval_global() -> DictConfig:
with initialize(version_base='1.2', config_path='../configs'):
cfg = compose(config_name='eval.yaml', return_hydra_config=True, overrides=['ckpt_path=.'])
with open_dict(cfg):
cfg.paths.root_dir = str(pyrootutils.fin... |
@pytest.fixture(scope='function')
def cfg_train(cfg_train_global, tmp_path) -> DictConfig:
cfg = cfg_train_global.copy()
with open_dict(cfg):
cfg.paths.output_dir = str(tmp_path)
cfg.paths.log_dir = str(tmp_path)
(yield cfg)
GlobalHydra.instance().clear()
|
@pytest.fixture(scope='function')
def cfg_eval(cfg_eval_global, tmp_path) -> DictConfig:
cfg = cfg_eval_global.copy()
with open_dict(cfg):
cfg.paths.output_dir = str(tmp_path)
cfg.paths.log_dir = str(tmp_path)
(yield cfg)
GlobalHydra.instance().clear()
|
def _package_available(package_name: str) -> bool:
'Check if a package is available in your environment.'
try:
return (pkg_resources.require(package_name) is not None)
except pkg_resources.DistributionNotFound:
return False
|
class RunIf():
'RunIf wrapper for conditional skipping of tests.\n\n Fully compatible with `@pytest.mark`.\n\n Example:\n\n @RunIf(min_torch="1.8")\n @pytest.mark.parametrize("arg1", [1.0, 2.0])\n def test_wrapper(arg1):\n assert arg1 > 0\n '
def __new__(self, min_gpu... |
def run_sh_command(command: List[str]):
'Default method for executing shell commands with pytest and sh package.'
msg = None
try:
sh.python(command)
except sh.ErrorReturnCode as e:
msg = e.stderr.decode()
if msg:
pytest.fail(msg=msg)
|
def test_train_config(cfg_train: DictConfig):
assert cfg_train
assert cfg_train.datamodule
assert cfg_train.model
assert cfg_train.trainer
HydraConfig().set_config(cfg_train)
hydra.utils.instantiate(cfg_train.datamodule)
hydra.utils.instantiate(cfg_train.model)
hydra.utils.instantiate(... |
def test_eval_config(cfg_eval: DictConfig):
assert cfg_eval
assert cfg_eval.datamodule
assert cfg_eval.model
assert cfg_eval.trainer
HydraConfig().set_config(cfg_eval)
hydra.utils.instantiate(cfg_eval.datamodule)
hydra.utils.instantiate(cfg_eval.model)
hydra.utils.instantiate(cfg_eval.... |
@pytest.mark.slow
def test_train_eval(tmp_path, cfg_train, cfg_eval):
'Train for 1 epoch with `train.py` and evaluate with `eval.py`'
assert (str(tmp_path) == cfg_train.paths.output_dir == cfg_eval.paths.output_dir)
with open_dict(cfg_train):
cfg_train.trainer.max_epochs = 1
cfg_train.test... |
@pytest.mark.parametrize('batch_size', [32, 128])
def test_mnist_datamodule(batch_size):
data_dir = 'data/'
dm = MNISTDataModule(data_dir=data_dir, batch_size=batch_size)
dm.prepare_data()
assert ((not dm.data_train) and (not dm.data_val) and (not dm.data_test))
assert Path(data_dir, 'MNIST').exis... |
@RunIf(sh=True)
@pytest.mark.slow
def test_experiments(tmp_path):
'Test running all available experiment configs with fast_dev_run=True.'
command = ([startfile, '-m', 'experiment=glob(*)', ('hydra.sweep.dir=' + str(tmp_path)), '++trainer.fast_dev_run=true'] + overrides)
run_sh_command(command)
|
@RunIf(sh=True)
@pytest.mark.slow
def test_hydra_sweep(tmp_path):
'Test default hydra sweep.'
command = ([startfile, '-m', ('hydra.sweep.dir=' + str(tmp_path)), 'model.optimizer.lr=0.005,0.01', '++trainer.fast_dev_run=true'] + overrides)
run_sh_command(command)
|
@RunIf(sh=True)
@pytest.mark.slow
def test_hydra_sweep_ddp_sim(tmp_path):
'Test default hydra sweep with ddp sim.'
command = ([startfile, '-m', ('hydra.sweep.dir=' + str(tmp_path)), 'trainer=ddp_sim', 'trainer.max_epochs=3', '+trainer.limit_train_batches=0.01', '+trainer.limit_val_batches=0.1', '+trainer.limi... |
@RunIf(sh=True)
@pytest.mark.slow
def test_optuna_sweep(tmp_path):
'Test optuna sweep.'
command = ([startfile, '-m', 'hparams_search=mnist_optuna', ('hydra.sweep.dir=' + str(tmp_path)), 'hydra.sweeper.n_trials=10', 'hydra.sweeper.sampler.n_startup_trials=5', '++trainer.fast_dev_run=true'] + overrides)
run... |
@RunIf(wandb=True, sh=True)
@pytest.mark.slow
def test_optuna_sweep_ddp_sim_wandb(tmp_path):
'Test optuna sweep with wandb and ddp sim.'
command = [startfile, '-m', 'hparams_search=mnist_optuna', ('hydra.sweep.dir=' + str(tmp_path)), 'hydra.sweeper.n_trials=5', 'trainer=ddp_sim', 'trainer.max_epochs=3', '+tra... |
def test_train_fast_dev_run(cfg_train):
'Run for 1 train, val and test step.'
HydraConfig().set_config(cfg_train)
with open_dict(cfg_train):
cfg_train.trainer.fast_dev_run = True
cfg_train.trainer.accelerator = 'cpu'
train(cfg_train)
|
@RunIf(min_gpus=1)
def test_train_fast_dev_run_gpu(cfg_train):
'Run for 1 train, val and test step on GPU.'
HydraConfig().set_config(cfg_train)
with open_dict(cfg_train):
cfg_train.trainer.fast_dev_run = True
cfg_train.trainer.accelerator = 'gpu'
train(cfg_train)
|
@RunIf(min_gpus=1)
@pytest.mark.slow
def test_train_epoch_gpu_amp(cfg_train):
'Train 1 epoch on GPU with mixed-precision.'
HydraConfig().set_config(cfg_train)
with open_dict(cfg_train):
cfg_train.trainer.max_epochs = 1
cfg_train.trainer.accelerator = 'cpu'
cfg_train.trainer.precisi... |
@pytest.mark.slow
def test_train_epoch_double_val_loop(cfg_train):
'Train 1 epoch with validation loop twice per epoch.'
HydraConfig().set_config(cfg_train)
with open_dict(cfg_train):
cfg_train.trainer.max_epochs = 1
cfg_train.trainer.val_check_interval = 0.5
train(cfg_train)
|
@pytest.mark.slow
def test_train_ddp_sim(cfg_train):
'Simulate DDP (Distributed Data Parallel) on 2 CPU processes.'
HydraConfig().set_config(cfg_train)
with open_dict(cfg_train):
cfg_train.trainer.max_epochs = 2
cfg_train.trainer.accelerator = 'cpu'
cfg_train.trainer.devices = 2
... |
@pytest.mark.slow
def test_train_resume(tmp_path, cfg_train):
'Run 1 epoch, finish, and resume for another epoch.'
with open_dict(cfg_train):
cfg_train.trainer.max_epochs = 1
HydraConfig().set_config(cfg_train)
(metric_dict_1, _) = train(cfg_train)
files = os.listdir((tmp_path / 'checkpoin... |
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 HierarchyEncoder(nn.Module):
def __init__(self, channel):
super(HierarchyEncoder, self).__init__()
assert (channel == 256)
self.group = [1, 2, 4, 8, 1]
self.layers = nn.ModuleList([nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, groups=1), nn.LeakyReLU(0.2, inplace=T... |
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, scale_factor=2):
super().__init__()
self.conv = nn.Conv2d(input_channel, output_channel, kernel_size=kernel_size, stride=1, padding=padding)
self.s = scale_factor
def forward(self, x)... |
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):
scores = (torch.matmul(query, key.transpose((- 2), (- 1))) / math.sqrt... |
class Vec2Patch(nn.Module):
def __init__(self, channel, hidden, output_size, kernel_size, stride, padding):
super(Vec2Patch, 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(hidd... |
class MultiHeadedAttention(nn.Module):
'\n Take in model size and number of heads.\n '
def __init__(self, tokensize, d_model, head, mode, p=0.1):
super().__init__()
self.mode = mode
self.query_embedding = nn.Linear(d_model, d_model)
self.value_embedding = nn.Linear(d_mod... |
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 TransformerBlock(nn.Module):
'\n Transformer = MultiHead_Attention + Feed_Forward with sublayer connection\n '
def __init__(self, tokensize, hidden=128, num_head=4, mode='s', dropout=0.1):
super().__init__()
self.attention = MultiHeadedAttention(tokensize, d_model=hidden, head=num... |
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
|
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 find_dataset_using_name(dataset_name):
'Import the module "data/[dataset_name]_dataset.py".\n\n In the file, the class called DatasetNameDataset() will\n be instantiated. It has to be a subclass of BaseDataset,\n and it is case-insensitive.\n '
dataset_filename = (('data.' + dataset_name) + '_... |
def get_option_setter(dataset_name):
'Return the static method <modify_commandline_options> of the dataset class.'
dataset_class = find_dataset_using_name(dataset_name)
return dataset_class.modify_commandline_options
|
def create_dataset(opt):
"Create a dataset given the option.\n\n This function wraps the class CustomDatasetDataLoader.\n This is the main interface between this package and 'train.py'/'test.py'\n\n Example:\n >>> from data import create_dataset\n >>> dataset = create_dataset(opt)\n ... |
class CustomDatasetDataLoader():
'Wrapper class of Dataset class that performs multi-threaded data loading'
def __init__(self, opt):
'Initialize this class\n\n Step 1: create a dataset instance given the name [dataset_mode]\n Step 2: create a multi-threaded data loader.\n '
... |
class AlignedDataset(BaseDataset):
"A dataset class for paired image dataset.\n\n It assumes that the directory '/path/to/data/train' contains image pairs in the form of {A,B}.\n During test time, you need to prepare a directory '/path/to/data/test'.\n "
def __init__(self, opt):
'Initialize ... |
class BaseDataset(data.Dataset, ABC):
'This class is an abstract base class (ABC) for datasets.\n\n To create a subclass, you need to implement the following four functions:\n -- <__init__>: initialize the class, first call BaseDataset.__init__(self, opt).\n -- <__len__>: ... |
def get_params(opt, size):
(w, h) = size
new_h = h
new_w = w
if (opt.preprocess == 'resize_and_crop'):
new_h = new_w = opt.load_size
elif (opt.preprocess == 'scale_width_and_crop'):
new_w = opt.load_size
new_h = ((opt.load_size * h) // w)
x = random.randint(0, np.maximu... |
def get_transform(opt, params=None, grayscale=False, method=Image.BICUBIC, convert=True):
transform_list = []
if grayscale:
transform_list.append(transforms.Grayscale(1))
if ('resize' in opt.preprocess):
osize = [opt.load_size, opt.load_size]
transform_list.append(transforms.Resize... |
def __make_power_2(img, base, method=Image.BICUBIC):
(ow, oh) = img.size
h = int((round((oh / base)) * base))
w = int((round((ow / base)) * base))
if ((h == oh) and (w == ow)):
return img
__print_size_warning(ow, oh, w, h)
return img.resize((w, h), method)
|
def __scale_width(img, target_width, method=Image.BICUBIC):
(ow, oh) = img.size
if (ow == target_width):
return img
w = target_width
h = int(((target_width * oh) / ow))
return img.resize((w, h), method)
|
def __crop(img, pos, size):
(ow, oh) = img.size
(x1, y1) = pos
tw = th = size
if ((ow > tw) or (oh > th)):
return img.crop((x1, y1, (x1 + tw), (y1 + th)))
return img
|
def __flip(img, flip):
if flip:
return img.transpose(Image.FLIP_LEFT_RIGHT)
return img
|
def __print_size_warning(ow, oh, w, h):
'Print warning information about image size(only print once)'
if (not hasattr(__print_size_warning, 'has_printed')):
print(('The image size needs to be a multiple of 4. The loaded image size was (%d, %d), so it was adjusted to (%d, %d). This adjustment will be d... |
def is_image_file(filename):
return any((filename.endswith(extension) for extension in IMG_EXTENSIONS))
|
def make_dataset(dir, max_dataset_size=float('inf')):
images = []
assert os.path.isdir(dir), ('%s is not a valid directory' % dir)
for (root, _, fnames) in sorted(os.walk(dir)):
for fname in fnames:
if is_image_file(fname):
path = os.path.join(root, fname)
... |
def default_loader(path):
return Image.open(path).convert('RGB')
|
class ImageFolder(data.Dataset):
def __init__(self, root, transform=None, return_paths=False, loader=default_loader):
imgs = make_dataset(root)
if (len(imgs) == 0):
raise RuntimeError(((('Found 0 images in: ' + root) + '\nSupported image extensions are: ') + ','.join(IMG_EXTENSIONS)))... |
class SingleDataset(BaseDataset):
"This dataset class can load a set of images specified by the path --dataroot /path/to/data.\n\n It can be used for generating CycleGAN results only for one side with the model option '-model test'.\n "
def __init__(self, opt):
'Initialize this dataset class.\n... |
def find_model_using_name(model_name):
'Import the module "models/[model_name]_model.py".\n In the file, the class called DatasetNameModel() will\n be instantiated. It has to be a subclass of BaseModel,\n and it is case-insensitive.\n '
model_filename = (('models.' + model_name) + '_model')
mo... |
def get_option_setter(model_name):
'Return the static method <modify_commandline_options> of the model class.'
model_class = find_model_using_name(model_name)
return model_class.modify_commandline_options
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.