code stringlengths 17 6.64M |
|---|
def blue(string):
return (('\x1b[94m' + string) + '\x1b[0m')
|
def prompt_yes_no(question):
'\n Prompt user to type yes or no.\n '
i = input((question + ' [y/n]: '))
if ((len(i) > 0) and ((i[0] == 'y') or (i[0] == 'Y'))):
return True
else:
return False
|
class Visualizer():
def __init__(self, tb_path):
self.tb_path = tb_path
if os.path.exists(tb_path):
if prompt_yes_no('{} already exists. Proceed?'.format(tb_path)):
os.system('rm -r {}'.format(tb_path))
else:
exit(0)
self.writer = Su... |
def main():
TARGET_DIR = 'depth_benchmark'
(K_RAW, K_DEPTH) = (DATA_PATHS['kitti_raw'], DATA_PATHS['kitti_depth'])
print(f'-> Exporting Kitti Benchmark from "{K_DEPTH}" to "{K_RAW}"...')
ROOT = (K_RAW / TARGET_DIR)
ROOT.mkdir(exist_ok=True)
for seq in kr.SEQS:
(ROOT / seq).mkdir(exist_... |
def process_dataset(src_dir: Path, dst_dir: Path, use_hints: bool=True, use_benchmark: bool=True, overwrite: bool=False) -> None:
'Process the entire Kitti Raw Sync datsets.'
(HINTS_DIR, BENCHMARK_DIR) = ('depth_hints', 'depth_benchmark')
if (not (path := (dst_dir / 'splits')).is_dir()):
shutil.co... |
def process_sequence(src_dir: Path, dst_dir: Path, overwrite: bool=False) -> None:
'Process a full Kitti Raw sequence: e.g. kitti_raw_sync/2011_09_26.'
print(f'-> Processing sequence "{src_dir}"')
for src_path in sorted(src_dir.iterdir()):
if src_path.is_file():
continue
dst_pa... |
def process_drive(src_dir: Path, dst_dir: Path, overwrite: bool=False) -> None:
'Process a full Kitti Raw sequence: e.g. kitti_raw_sync/2011_09_26/2011_09_26_drive_0005.'
print(f' -> Processing drive "{src_dir}"')
for src_path in sorted(src_dir.iterdir()):
dst_path = (dst_dir / src_path.name)
... |
def process_dir(src_dir: Path, dst_dir: Path, overwrite: bool=False) -> None:
'Processes a data directory within a given drive.\n\n Cases:\n - Base dataset: images_00, images_01, velodyne_points, oxts (/data & /timestamps for each)\n - Depth hints: images_02, images_03\n - Depth benchmark:... |
def export_calibration(src_seq: Path, dst_seq: Path, overwrite: bool=False) -> None:
'Exports sequence calibration information as a LabelDatabase of arrays.'
dst_dir = (dst_seq / 'calibration')
if ((not overwrite) and dst_dir.is_dir()):
print(f' -> Skipping calib "{dst_dir}"')
return
e... |
def export_images(src_dir: Path, dst_dir: Path) -> None:
'Export images as an ImageDatabase.'
image_paths = {file.stem: file for file in sorted(src_dir.iterdir())}
write_image_database(image_paths, dst_dir)
|
def export_oxts(src_dir: Path, dst_dir: Path) -> None:
'Export OXTS dicts as a LabelDatabase.'
data = {file.stem: kr.load_oxts(file) for file in sorted(src_dir.iterdir())}
write_label_database(data, dst_dir)
|
def export_velodyne(src_dir: Path, dst_dir: Path) -> None:
'Export Velodyne points as a LabelDatabase of arrays.'
data = {file.stem: kr.load_velo(file) for file in sorted(src_dir.iterdir())}
write_label_database(data, dst_dir)
|
def export_hints(src_dir: Path, dst_dir: Path) -> None:
'Export depth hints as a LabelDatabase of arrays.'
data = {file.stem: np.load(file) for file in sorted(src_dir.iterdir())}
write_array_database(data, dst_dir)
|
def save(file: Path, **kwargs) -> None:
'Save a list of arrays as a npz file.'
print(f'''
-> Saving to "{file}"...''')
np.savez_compressed(file, **kwargs)
|
def export_kitti(depth_split: str, mode: str, use_velo_depth: bool=False, save_stem: Optional[str]=None, overwrite: bool=False) -> None:
"Export the ground truth LiDAR depth images for a given Kitti test split.\n\n :param depth_split: (str) Kitti depth split to load.\n :param mode: (str) Split mode to use. ... |
def save(file: Path, **kwargs) -> None:
'Save a list of arrays as a npz file.'
print(f'-> Saving to "{file}"...')
np.savez_compressed(file, **kwargs)
|
def export_syns(mode, save_stem: Optional[str]=None, overwrite: bool=False) -> None:
'Export the ground truth LiDAR depth images for SYNS.\n\n :param save_stem: (Optional[str]) Exported depth file stem (i.e. no suffix).\n :param overwrite: (bool) If `True`, overwrite existing exported files.\n '
prin... |
def main():
device = ops.get_device('cpu')
root = MODEL_ROOTS[(- 1)]
(exp, ckpt_name) = ('benchmark', 'last')
files = sorted((root / exp).glob(f'**/{ckpt_name}.ckpt'))
for f in files:
n = str(f).replace(str(root), '')
is_training = (f.parent / 'training').is_file()
is_finis... |
def load_dfs(files: dict[(str, Sequence[Path])]):
df = pd.json_normalize([io.load_yaml(f) for fs in files.values() for f in fs])
df.index = [f'{k}' for (k, fs) in files.items() for (i, _) in enumerate(fs)]
return df
|
def load_dfs(files: dict[(str, Sequence[Path])]):
dfs = [pd.json_normalize(io.load_yaml(f)) for fs in files.values() for f in fs]
df = pd.concat(dfs)
models = [f'{k}' for (k, fs) in files.items() for _ in fs]
df.index = pd.MultiIndex.from_product([models, dfs[0].index], names=['Model', 'Item'])
re... |
def save_metrics(file: Path, metrics: Sequence[Metrics]):
'Helper to save metrics. If any strings are present, save metrics separately. Otherwise save means.'
print(f'''
-> Saving results to "{file}"...''')
file.parent.mkdir(exist_ok=True, parents=True)
use_mean = all((isinstance(v, float) for v in me... |
def compute_eval_metrics(preds: NDArray, mode: str, cfg_file: Path) -> Sequence[Metrics]:
'Compute evaluation metrics from network predictions.\n Predictions must be unscaled (see `compute_eval_preds`).\n\n :param preds: (NDArray) (b, h, w) Precomputed unscaled network predictions.\n :param mode: (str) E... |
def save_preds(file: Path, preds: NDArray) -> None:
'Helper to save network predictions to a NPZ file. Required for submitted to the challenge.'
file.parent.mkdir(exist_ok=True, parents=True)
print(f'-> Saving network predictions to "{file}"...')
np.savez_compressed(file, pred=preds)
|
def compute_eval_preds(ckpt_file: Union[(str, Path)], cfg: dict, overwrite: bool=False) -> NDArray:
'Compute network predictions required for evaluation.\n\n The confing in `cfg_dataset` is equivalent to that used by the `Trainer`.\n Note that in most cases, additional outputs, such as depth or edges can be... |
def load_dfs(d):
df = pd.json_normalize([load_yaml(f) for fs in d.values() for f in fs])
df.index = [f'{m}' for (m, fs) in d.items() for (i, _) in enumerate(fs)]
return df
|
def main():
pd.set_option('display.max_rows', None, 'display.max_columns', None)
root = MODEL_ROOTS[(- 1)]
exp = 'benchmark'
split = 'eigen_benchmark'
mode = '*'
ckpt_name = 'best'
res = 'results'
fname = f'kitti_{split}_{ckpt_name}_{mode}.yaml'
metric_type = ([(- 1), (- 1), (- 1),... |
def main():
parser = ArgumentParser(description='Monocular depth trainer.')
parser.add_argument('--cfg-file', '-c', required=True, type=Path, help='Path to YAML config file to load.')
parser.add_argument('--cfg-default', '-d', default=None, type=Path, help='Default YAML config file to overwrite.')
par... |
def main():
parser = ArgumentParser(description='Monocular depth trainer.')
parser.add_argument('--cfg-file', '-c', required=True, type=Path, help='Path to YAML config file to load.')
parser.add_argument('--cfg-default', '-d', default=None, type=Path, help='Default YAML config file to overwrite.')
par... |
def get_augmentations(strong=True):
if strong:
tfm = TrivialAugmentWide()
else:
tfm = ka.ColorJitter(brightness=(0.8, 1.2), contrast=(0.8, 1.2), saturation=(0.8, 1.2), hue=((- 0.1), 0.1), p=1.0, same_on_batch=True, keepdim=True)
return tfm
|
class BaseDataset(ABC, Dataset):
'Base dataset class that all others should inherit from.\n\n The idea is to provide a common structure and format for data to follow. Additionally, provide some nice\n functionality and automation for the more boring stuff. Datasets are defined as providing the following dic... |
@register('kitti_lmdb')
class KittiRawLMDBDataset(KittiRawDataset):
"Kitti Depth based on the kitti_raw_sync dataset.\n\n LMDB variant of KittiRawDataset. This is designed to be a drop-in replacement that can help with IO load.\n As such, we only need to provide wrappers around the loading functions in the ... |
def main():
dataset = KittiRawLMDBDataset(split='benchmark2', mode='train', size=(640, 192), supp_idxs=None, use_depth=True, interpolate_depth=False, use_depth_hints=False, use_poses=False, use_strong_aug=False, as_torch=False, use_aug=False, log_timings=False)
print(dataset)
dataset.play(fps=100)
|
@register('syns_patches')
class SYNSPatchesDataset(BaseDataset):
"SYNS Patches dataset based on SYNS panorama images/LiDAR.\n\n See each function for details.\n\n Attributes:\n :param mode: (str) Split mode to load. {val, test, all}\n :param size: (Sequence[int]) Target image training size as (w, h).\... |
def get_split_file(mode: str) -> Path:
'Get scene information file based on the scene number.'
file = ((PATHS['syns_patches'] / 'splits') / f'{mode}_files.txt')
return file
|
def get_scenes() -> list[Path]:
'Get paths to each of the scenes.'
return sorted((path for path in PATHS['syns_patches'].iterdir() if (path.is_dir() and (path.stem != 'splits'))))
|
def get_scene_files(scene_dir: Path) -> dict[(str, Sequence[Path])]:
'Get paths to all subdir files for a given scene.'
files = {key: sorted((scene_dir / key).iterdir()) for key in SUBDIRS if (scene_dir / key).is_dir()}
return files
|
def get_info_file(scene: str) -> Path:
'Get scene information file based on the scene number.'
paths = (PATHS['syns_patches'] / scene).iterdir()
return next((f for f in paths if (f.suffix == '.txt')))
|
def get_image_file(scene: str, file: str) -> Path:
'Get image filename based on scene and item number.'
return (((PATHS['syns_patches'] / scene) / 'images') / file)
|
def get_depth_file(scene: str, file: str) -> Path:
'Get image filename based on scene and item number.'
return (((PATHS['syns_patches'] / scene) / 'depths') / file).with_suffix('.npy')
|
def get_edges_file(scene: str, subdir: str, file: str) -> Path:
'Get image filename based on scene and item number.'
assert ('edges' in subdir), f'Must provide an "edges" directory. ({subdir})'
assert (subdir in SUBDIRS), f"Non-existent edges directory. ({subdir} vs. {[s for s in SUBDIRS if ('edges' in s)... |
def load_info(scene: str) -> Sequence[str]:
'Load the scene information.'
file = get_info_file(scene)
info = readlines(file, encoding='latin-1')
return info
|
def load_category(scene: str) -> tuple[(str, str)]:
'Load the scene category and subcategory.'
info = load_info(scene)
category = info[1].replace('Scene Category: ', '')
try:
(cat, subcat) = category.split(': ')
except ValueError:
(cat, subcat) = category.split(' - ')
return (c... |
def load_split(mode) -> tuple[(Path, list[list[str]])]:
'Load the list of scenes and filenames that are part of the test split.\n\n Test split file is given as "SEQ ITEM":\n ```\n 01 00.png\n 10 11.png\n ```\n '
file = get_split_file(mode)
lines = readlines(file)
lines = [l.split(' '... |
def load_intrinsics() -> NDArray:
'Computes the virtual camera intrinsics for the `Kitti` based SYNS Patches.\n\n We compute this based on the desired FOV, using basic trigonometry.\n\n :return: (ndarray) (4, 4) Camera intrinsic parameters.\n '
(Fy, Fx) = KITTI_FOV
(h, w) = KITTI_SHAPE
(cx, c... |
def main():
import matplotlib.pyplot as plt
for scene in get_scenes():
print(scene.stem)
(_, axs11) = plt.subplots(3, 3)
plt.tight_layout()
(_, axs12) = plt.subplots(3, 3)
plt.tight_layout()
(_, axs21) = plt.subplots(3, 3)
plt.tight_layout()
(_, ... |
class ChamferDistanceFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, xyz1, xyz2):
(batchsize, n, _) = xyz1.size()
(_, m, _) = xyz2.size()
xyz1 = xyz1.contiguous()
xyz2 = xyz2.contiguous()
dist1 = torch.zeros(batchsize, n)
dist2 = torch.zeros(b... |
class ChamferDistance(torch.nn.Module):
def __init__(self):
super().__init__()
if (cd is None):
raise RuntimeError(f'Chamfer Distance module unavailable')
def forward(self, xyz1, xyz2):
return ChamferDistanceFunction.apply(xyz1, xyz2)
|
class Database():
_database = None
_protocol = None
_length = None
def __init__(self, path: PathLike, readahead: bool=True, pre_open: bool=False):
'Base class for LMDB-backed _databases.\n\n :param path: (PathLike) Path to the database.\n :param readahead: (bool) If `True`, enab... |
class ImageDatabase(Database):
def _convert_value(self, value):
'Converts a byte image back into a PIL Image.\n\n :param value: A byte image.\n :return: A PIL Image image.\n '
return Image.open(io.BytesIO(value))
|
class MaskDatabase(ImageDatabase):
def _convert_value(self, value):
'Converts a byte image back into a PIL Image.\n\n :param value: A byte image.\n :return: A PIL image.\n '
return Image.open(io.BytesIO(value)).convert('1')
|
class LabelDatabase(Database):
pass
|
class ArrayDatabase(Database):
_dtype = None
_shape = None
@property
def dtype(self):
if (self._dtype is None):
protocol = self.protocol
self._dtype = self._get(item='dtype', convert_key=(lambda key: pickle.dumps(key, protocol=protocol)), convert_value=(lambda value: p... |
class TensorDatabase(ArrayDatabase):
def _convert_value(self, value):
return torch.from_numpy(super(TensorDatabase, self)._convert_value(value))
def _convert_values(self, values):
return torch.from_numpy(super(TensorDatabase, self)._convert_values(values))
|
def write_image_database(d: dict, database: Path):
database.parent.mkdir(parents=True, exist_ok=True)
if database.exists():
shutil.rmtree(database)
tmp_dir = (Path('/tmp') / f'TEMP_{time()}')
tmp_dir.mkdir(parents=True)
tmp_database = (tmp_dir / f'{database.name}')
with lmdb.open(path=... |
def write_label_database(d: dict, database: Path):
database.parent.mkdir(parents=True, exist_ok=True)
if database.exists():
shutil.rmtree(database)
tmp_dir = (Path('/tmp') / f'TEMP_{time()}')
tmp_dir.mkdir(parents=True)
tmp_database = (tmp_dir / f'{database.name}')
with lmdb.open(path=... |
def write_array_database(d: dict, database: Path):
database.parent.mkdir(parents=True, exist_ok=True)
if database.exists():
shutil.rmtree(database)
tmp_dir = (Path('/tmp') / f'TEMP_{time()}')
tmp_dir.mkdir(parents=True)
tmp_database = (tmp_dir / f'{database.name}')
with lmdb.open(path=... |
class DenseL1Error(nn.Module):
'Dense L1 loss averaged over channels.'
def forward(self, pred, target):
return (pred - target).abs().mean(dim=1, keepdim=True)
|
class DenseL2Error(nn.Module):
'Dense L2 distance.'
def forward(self, pred, target):
return (pred - target).pow(2).sum(dim=1, keepdim=True).clamp(min=ops.eps(pred)).sqrt()
|
class SSIMError(nn.Module):
'Structural similarity error.'
def __init__(self):
super().__init__()
self.pool: nn.Module = nn.AvgPool2d(kernel_size=3, stride=1)
self.refl: nn.Module = nn.ReflectionPad2d(padding=1)
self.eps1: float = (0.01 ** 2)
self.eps2: float = (0.03 *... |
class PhotoError(nn.Module):
'Class for computing the photometric error.\n From Monodepth (https://arxiv.org/abs/1609.03677)\n\n The SSIMLoss can be deactivated by setting `weight_ssim=0`.\n The L1Loss can be deactivated by setting `weight_ssim=1`.\n Otherwise, the loss is a weighted combination of bo... |
@register(('img_recon', 'feat_recon', 'autoenc_recon'))
class ReconstructionLoss(nn.Module):
"Class to compute the reconstruction loss when synthesising new views.\n\n Contributions:\n - Min reconstruction error: From Monodepth2 (https://arxiv.org/abs/1806.01260)\n - Static pixel automasking: Fro... |
def l1_loss(pred: Tensor, target: Tensor) -> Tensor:
'Dense L1 loss.'
loss = (pred - target).abs()
return loss
|
def log_l1_loss(pred: Tensor, target: Tensor) -> Tensor:
'Dense Log L1 loss.'
loss = (1 + l1_loss(pred, target)).log()
return loss
|
def berhu_loss(pred: Tensor, target: Tensor, delta: float=0.2, dynamic: bool=True) -> Tensor:
'Dense berHu loss.\n\n :param pred: (Tensor) Network prediction.\n :param target: (Tensor) Ground-truth target.\n :param delta: (float) Threshold above which the loss switches from L1.\n :param dynamic: (bool... |
@register(('depth_regr', 'stereo_const'))
class RegressionLoss(nn.Module):
'Class implementing a supervised regression loss.\n\n NOTE: The DepthHints automask is not computed here. Instead, we rely on the `MonoDepthModule` to compute it.\n Probably not the best way of doing it, but it keeps this loss clean.... |
@register('autoencoder')
class AutoencoderNet(nn.Module):
"Image autoencoder network.\n From FeatDepth (https://arxiv.org/abs/2007.10603)\n\n Heavily based on the Depth network with some changes:\n - Single decoder\n - Produces 3 sigmoid channels (RGB)\n - No skip connections, it's an a... |
class StructurePerception(nn.Module):
'Self-attention Structure Perception Module.'
def forward(self, x):
(b, c, h, w) = x.shape
value = x.view(b, c, (- 1))
query = value
key = value.permute(0, 2, 1)
att = (query @ key)
att = (att.max(dim=(- 1), keepdim=True)[0... |
class DetailEmphasis(nn.Module):
'Detail Emphasis Module.\n\n :param ch: (int) Number of input/output channels.\n '
def __init__(self, ch: int):
super().__init__()
self.conv = nn.Sequential(conv3x3(ch, ch), nn.BatchNorm2d(ch), nn.ReLU(inplace=True))
self.att = nn.Sequential(nn.A... |
class CADepthDecoder(nn.Module):
"From CADepth (https://arxiv.org/abs/2112.13047)\n\n :param num_ch_enc: (Sequence[int]) List of channels per encoder stage.\n :param enc_sc: (Sequence[int]) List of downsampling factor per encoder stage.\n :param upsample_mode: (str) Torch upsampling mode. {'nearest', 'bi... |
def get_discrete_bins(n: int, mode: str='linear') -> Tensor:
'Get the discretized disparity value depending on number of bins and quantization mode.\n\n All modes assume that we are quantizing sigmoid disparity, and therefore are in range [0, 1].\n Quantization modes:\n - linear: Evenly spaces out al... |
class SelfAttentionBlock(nn.Module):
'Self-Attention Block.\n\n :param ch: (int) Number of input/output channels.\n '
def __init__(self, ch):
super().__init__()
self.query_conv = nn.Sequential(nn.Conv2d(ch, ch, kernel_size=1, padding=0), nn.ReLU(inplace=True))
self.key_conv = nn... |
class DDVNetDecoder(nn.Module):
"From DDVNet (https://arxiv.org/abs/2003.13951)\n\n :param num_ch_enc: (Sequence[int]) List of channels per encoder stage.\n :param enc_sc: (Sequence[int]) List of downsampling factor per encoder stage.\n :param upsample_mode: (str) Torch upsampling mode. {'nearest', 'bili... |
def upsample_block(in_ch: int, out_ch: int, upsample_mode: str='nearest') -> nn.Module:
'Layer to upsample the input by a factor of 2 without skip connections.'
return nn.Sequential(conv_block(in_ch, out_ch), nn.Upsample(scale_factor=2, mode=upsample_mode), conv_block(out_ch, out_ch))
|
class ChannelAttention(nn.Module):
'Channel Attention Module incorporating Squeeze & Exicitation.\n\n :param in_ch: (int) Number of input channels.\n :param ratio: (int) Channels reduction ratio in bottleneck.\n '
def __init__(self, in_ch: int, ratio: int=16):
super().__init__()
self... |
class AttentionBlock(nn.Module):
"Attention Block incorporating channel attention.\n\n :param in_ch: (int) Number of input channels.\n :param skip_ch: (int) Number of channels in skip connection features.\n :param out_ch: (Optional[int]) Number of output channels.\n :param upsample_mode: (str) Torch u... |
class DiffNetDecoder(nn.Module):
"From DiffNet (https://arxiv.org/abs/2110.09482)\n\n :param num_ch_enc: (Sequence[int]) List of channels per encoder stage.\n :param enc_sc: (Sequence[int]) List of downsampling factor per encoder stage.\n :param upsample_mode: (str) Torch upsampling mode. {'nearest', 'bi... |
class FSEBlock(nn.Module):
def __init__(self, in_ch: int, skip_ch: int, out_ch: Optional[int]=None, upsample_mode: str='nearest'):
super().__init__()
self.in_ch = (in_ch + skip_ch)
self.out_ch = (out_ch or in_ch)
self.upsample_mode = upsample_mode
self.reduction = 16
... |
class HRDepthDecoder(nn.Module):
"From HRDepth (https://arxiv.org/pdf/2012.07356.pdf)\n\n :param num_ch_enc: (Sequence[int]) List of channels per encoder stage.\n :param enc_sc: (Sequence[int]) List of downsampling factor per encoder stage.\n :param upsample_mode: (str) Torch upsampling mode. {'nearest',... |
def main():
num_enc_ch = [64, 64, 128, 256, 512]
enc_sc = [2, 4, 8, 16, 32]
(b, h, w) = (4, 256, 512)
enc_features = [torch.rand((b, c, (h // s), (w // s))) for (s, c) in zip(enc_sc, num_enc_ch)]
net = HRDepthDecoder(num_ch_enc=num_enc_ch, enc_sc=enc_sc, out_sc=range(4), out_ch=1)
out = net(en... |
class MonodepthDecoder(nn.Module):
"From Monodepth(2) (https://arxiv.org/abs/1806.01260)\n\n Generic convolutional decoder incorporating multi-scale predictions and skip connections.\n\n :param num_ch_enc: (Sequence[int]) List of channels per encoder stage.\n :param enc_sc: (Sequence[int]) List of downsa... |
class SubPixelConv(nn.Module):
def __init__(self, ch_in: int, up_factor: int):
super().__init__()
ch_out = (ch_in * (up_factor ** 2))
self.conv = nn.Conv2d(ch_in, ch_out, kernel_size=(3, 3), groups=ch_in, padding=1)
self.shuffle = nn.PixelShuffle(up_factor)
self.init_weigh... |
class SuperdepthDecoder(nn.Module):
"From SuperDepth (https://arxiv.org/abs/1806.01260)\n\n Generic convolutional decoder incorporating multi-scale predictions and skip connections.\n\n :param num_ch_enc: (Sequence[int]) List of channels per encoder stage.\n :param enc_sc: (Sequence[int]) List of downsam... |
def conv1x1(in_ch: int, out_ch: int, bias: bool=True) -> nn.Conv2d:
'Layer to convolve input.'
return nn.Conv2d(in_ch, out_ch, kernel_size=(1, 1), bias=bias)
|
def conv3x3(in_ch: int, out_ch: int, bias: bool=True) -> nn.Conv2d:
'Layer to pad and convolve input.'
return nn.Conv2d(in_ch, out_ch, kernel_size=(3, 3), padding=1, padding_mode='reflect', bias=bias)
|
def conv_block(in_ch: int, out_ch: int) -> nn.Module:
'Layer to perform a convolution followed by ELU.'
return nn.Sequential(OrderedDict({'conv': conv3x3(in_ch, out_ch), 'act': nn.ELU(inplace=True)}))
|
def _load_roots():
'Helper to load the additional model & data roots from the repo config.'
file = (REPO_ROOT / 'PATHS.yaml')
if file.is_file():
paths = load_yaml(file)
model_roots = [Path(p) for p in paths['MODEL_ROOTS']]
data_roots = [Path(p) for p in paths['DATA_ROOTS']]
els... |
def _build_paths(names: dict[(str, str)], roots: list[Path]):
'Helper to build the paths from a list of possible `roots`.\n NOTE: This returns the FIRST found path given by the order of roots. I.e. ordered by priority.\n '
paths = {}
for (k, v) in names.items():
try:
paths[k] = n... |
def find_model_file(name: str) -> Path:
'Helper to find a model file in the available roots.'
if (p := Path(name)).is_file():
return p
try:
return next((p for r in MODEL_ROOTS if (p := (r / name)).is_file()))
except StopIteration:
raise FileNotFoundError(f'No valid path found f... |
def find_data_dir(name: str) -> Path:
'Helper to find a dataset directory in the available roots.'
if (p := Path(name)).is_dir():
return p
try:
return next((p for r in DATA_ROOTS if (p := (r / name)).is_file()))
except StopIteration:
raise FileNotFoundError(f'No valid path foun... |
def register(name: Union[(str, Sequence[str])], type: Optional[str]=None, overwrite: bool=False) -> Callable:
"Class decorator to build a registry of networks, losses & data available during training.\n\n :param name: (str|Sequence[str]) Key(s) to access class in the registry.\n :param type: (None|str) Regi... |
@register('disp_mask')
class MaskReg(nn.Module):
'Class implementing photometric loss masking regularization.\n From SfM-Learner (https://arxiv.org/abs/1704.07813)\n\n Based on the `explainability` mask, which predicts a weighting factor for each pixel in the photometric loss.\n To avoid the degenerate s... |
@register('disp_occ')
class OccReg(nn.Module):
'Class implementing disparity occlusion regularization.\n From DVSO (https://arxiv.org/abs/1807.02570)\n\n This regularization penalizes the overall disparity in the image, encouraging the network to select background\n disparities.\n\n NOTE: In this case... |
def get_device(device: Optional[Union[(str, torch.device)]]=None, /) -> torch.device:
'Create torch device from str or device. Defaults to CUDA if available.'
if isinstance(device, torch.device):
return device
device = (device or ('cuda' if torch.cuda.is_available() else 'cpu'))
return torch.d... |
def get_latest_ckpt(path: PathLike, ignore: Sequence[str]=None, reverse: bool=False, suffix: str='.ckpt') -> Optional[Path]:
'Return latest or earliest checkpoint in the directory. Assumes files can be sorted in a meaningful way.\n\n :param path: (PathLike) Directory to search in.\n :param ignore: (Sequence... |
def eps(x: Optional[torch.Tensor]=None, /) -> float:
'Return the `eps` value for the given `input` dtype. (default=float32 ~= 1.19e-7)'
dtype = (torch.float32 if (x is None) else x.dtype)
return torch.finfo(dtype).eps
|
def freeze(net: nn.Module, /) -> nn.Module:
'Fix all model parameters and prevent training.'
for p in net.parameters():
p.requires_grad = False
return net
|
def unfreeze(net: nn.Module, /) -> nn.Module:
'Make all model parameters trainable.'
for p in net.parameters():
p.requires_grad = True
return net
|
def allclose(net1: nn.Module, net2: nn.Module, /) -> bool:
'Check if two networks are equal.'
for (p1, p2) in zip(net1.parameters(), net2.parameters()):
try:
if (not p1.allclose(p2)):
return False
except RuntimeError:
return False
return True
|
def num_parameters(net: nn.Module, /) -> int:
'Get number of trainable parameters in a network.'
return sum((p.numel() for p in net.parameters() if p.requires_grad))
|
@map_container
def to_torch(x: Any, /, permute: bool=True, device: Optional[torch.device]=None) -> Any:
'Convert given input to torch.Tensors\n\n :param x: (Any) Arbitrary structure to convert to tensors (see `map_apply`).\n :param permute: (bool) If `True`, permute to PyTorch convention (b, h, w, c) -> (b,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.