code stringlengths 17 6.64M |
|---|
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,... |
@map_container
def to_numpy(x: Any, /, permute: bool=True) -> Any:
'Convert given input to numpy.ndarrays.\n\n :param x: (Any) Arbitrary structure to convert to ndarrays (see map_apply).\n :param permute: (bool) If `True`, permute from PyTorch convention (b, c, h, w) -> (b, h, w, c).\n :return: (Any) Inp... |
@map_container
def op(_x: Any, /, *args, fn: Union[(str, Callable)], **kwargs) -> Any:
"Apply a function to and arbitrary input structure. `fn` can be either a function or a method to search on `_x`.\n\n Example:\n >>> out = fn(input, device, op='to') # Apply x.to(device) to each item in `x`\n >... |
@opt_args_deco
def allow_np(fn: Optional[Callable], permute: bool=False) -> Callable:
"Decorator to allow for numpy.ndarray inputs in a torch function.\n\n Main idea is to implement the function using torch ops and apply this decorator to also make it numpy friendly.\n Since numpy.ndarray and torch.Tensor s... |
@allow_np(permute=True)
def standardize(x: Tensor, /, mean: StatsRGB=_mean, std: StatsRGB=_std) -> Tensor:
'Apply standardization. Default uses ImageNet statistics.'
shape = (([1] * (x.ndim - 3)) + [3, 1, 1])
mean = x.new_tensor(mean).view(shape)
std = x.new_tensor(std).view(shape)
x = ((x - mean)... |
@allow_np(permute=True)
def unstandardize(x: Tensor, /, mean: StatsRGB=_mean, std: StatsRGB=_std) -> Tensor:
'Remove standardization. Default uses ImageNet statistics.'
shape = (([1] * (x.ndim - 3)) + [3, 1, 1])
mean = x.new_tensor(mean).view(shape)
std = x.new_tensor(std).view(shape)
x = ((x * st... |
@allow_np(permute=True)
def to_gray(x: Tensor, /, coeffs: StatsRGB=_coeffs, keepdim: bool=False) -> Tensor:
'Convert image to grayscale.'
shape = (([1] * (x.ndim - 3)) + [3, 1, 1])
coeffs = x.new_tensor(coeffs).view(shape)
x = (x * coeffs).sum(dim=1, keepdim=keepdim)
return x
|
def mean_normalize(x: Tensor, /, dim: Union[(int, Sequence[int])]=(2, 3)) -> Tensor:
'Apply mean normalization across the specified dimensions.\n\n :param x: (Tensor) (*) Input tensor to normalize of any shape.\n :param dim: (int | Sequence[int]) Dimension(s) to compute the mean across.\n :return: (Tenso... |
def eye_like(x: Tensor, /) -> Tensor:
'Create an Identity matrix of the same dtype and size as the input.\n\n NOTE: The input can be of any shape, expect the final two dimensions, which must be square.\n\n :param x: (Tensor) (*, n, n) Input reference tensor, where `*` can be any size (including zero).\n ... |
def interpolate_like(input: Tensor, /, other: Tensor, mode: str='nearest', align_corners: bool=False) -> Tensor:
'Interpolate to match the size of `other` tensor.'
if (mode == 'nearest'):
align_corners = None
return F.interpolate(input, size=other.shape[(- 2):], mode=mode, align_corners=align_corn... |
def expand_dim(x: Tensor, /, num: Union[(int, Sequence[int])], dim: Union[(int, Sequence[int])]=0, insert: bool=False) -> Tensor:
'Expand the specified input tensor dimensions, inserting new ones if required.\n\n >>> expand_dim(torch.rand(1, 1, 1), num=5, dim=1, insert=False) # (1, 1, 1) -> (1, 5, ... |
def get_cls(cls_dict: dict[(str, Type[T])], /, *args, type: str, **kwargs) -> T:
'Instantiate an arbitrary class from a collection.\n\n Including `type` makes it a keyword-only argument. This has the double benefit of forcing the user to pass it as a\n keyword argument, as well as popping it from the config... |
def get_net(cfg: NetCfg) -> nn.ModuleDict:
"Instantiate the target networks from a config dict.\n\n The depth estimation algorithm typically consists of multiple networks, commonly at least `depth` and `pose`.\n We're assuming that, within a given category, we can use different classes interchangeably.\n ... |
def get_loss(cfg: LossCfg) -> tuple[(nn.ModuleDict, nn.ParameterDict)]:
'Instantiate the target losses from a config dict.\n\n :param cfg: (Dict[str, Dict[str, Any]]) Target loss `types` and kwargs to forward to them.\n :return:\n '
(losses, weights) = (nn.ModuleDict(), nn.ParameterDict())
for (k... |
def get_ds(cfg: DataCfg) -> Dataset:
'Instantiate the target data from a config dict.\n\n :param cfg: (Dict[str, Any]]) Target loss `types` and kwargs to forward to them.\n :return:\n '
ds = get_cls(DATA_REG, **cfg)
return ds
|
def get_dl(mode: str, cfg_ds: DataCfg, cfg_dl: LoaderCfg) -> DataLoader:
"Instantiate the target dataset loader from a config dict.\n\n Supports the presence of a common config, which gets overriden by specific cfg within each mode.\n Example:\n ```\n dataset:\n type: kitti\n ... |
def get_opt(parameters: Union[(Iterable, nn.Module)], cfg: OptCfg) -> optim.Optimizer:
'Instantiate the target learning rate scheduler from a config dict.\n\n Serves as a wrapper for `timm` `create_optimizer_v2` to maintain consistency in the export interface.\n\n :param parameters: (Iterable | nn.Module) P... |
def get_sched(opt: optim.Optimizer, cfg: SchedCfg) -> optim.lr_scheduler._LRScheduler:
'Instantiate the target learning rate scheduler from a config dict.\n\n TODO: Deprecate in favour of `timm` schedulers?\n\n :param opt: (optim.Optimizer) Optimizer to forward to the LR scheduler.\n :param cfg: (Dict[st... |
def get_metrics() -> nn.ModuleDict:
'Instantiate the collection of depth metrics to monitor.'
return nn.ModuleDict({'MAE': metrics.MAE(), 'RMSE': metrics.RMSE(), 'LogSI': metrics.ScaleInvariant(mode='log'), 'AbsRel': metrics.AbsRel(), 'Acc': metrics.DeltaAcc(delta=1.25)})
|
class TableFormatter():
'Class to format a table as a LaTeX `booktabs` table.\n\n :param header: (Sequence[str]) (m,) Header elements represented as strings.\n :param labels: (Sequence[str]) (n,) Row names represented as strings.\n :param body: (Sequence[Sequence[float]]) (n, m) Table data for each `tag`... |
def _get_percentile(x: NDArray, p: int) -> float:
'Safe percentile to handle NaNs/Inf values.'
try:
return np.percentile(x, p)
except IndexError:
return 0.0
|
@ops.allow_np(permute=True)
def rgb_from_disp(disp: Tensor, invert: bool=False, cmap: str='turbo', vmin: float=0, vmax: Optional[Union[(float, Sequence[float])]]=None) -> Tensor:
'Convert a disparity map into an RGB colormap visualization.\n\n :param disp: (Tensor) (b, 1, h, w) or (h, w)\n :param invert: (b... |
@ops.allow_np(permute=True)
def rgb_from_feat(feat: Tensor) -> Tensor:
'Convert dense features into an RGB image via PCA.\n\n NOTE: PCA is computed using all features in the batch, i.e. the representation is batch dependent.\n\n :param feat: (Tensor) (*b, c, h, w) Dense feature representation.\n :return:... |
class BaseNetCfg(TypedDict):
'Confing for a base network.'
type: str
|
class BaseLossCfg(TypedDict):
'Config for a loss without parameters. We only require a weighting factor.'
weight: float
|
class NetCfg(TypedDict):
'Config dict for a collection of networks.'
depth: BaseNetCfg
pose: BaseNetCfg
|
class LossCfg(TypedDict):
'Config dict for a collection of losses.'
recon: BaseLossCfg
smoooth: Optional[BaseLossCfg]
|
class DataCfg(TypedDict):
'Config dict for a collection of BaseDataset. Configs in {core, val, test} override values in main config.'
type: str
mode: str
size: Sequence[int]
supp_idxs: Optional[Sequence[int]]
use_depth: Optional[bool]
use_hints: Optional[bool]
use_benchmark: Optional[b... |
class LoaderCfg(TypedDict):
'Config dict for a torch DataLoader.'
batch_size: int
num_workers: Optional[int]
drop_last: Optional[bool]
shuffle: Optional[bool]
pin_memory: Optional[bool]
train: Optional['LoaderCfg']
val: Optional['LoaderCfg']
test: Optional['LoaderCfg']
|
class OptCfg(TypedDict):
'Config dict for a torch Optimizer.'
type: Optional[str]
opt: Optional[str]
lr: float
|
class SchedCfg(TypedDict):
'Config dict for a torch LRScheduler.'
type: str
|
class TrainCfg(TypedDict):
'Config dict for training options.'
max_epochs: bool
resume_training: Optional[bool]
load_ckpt: Optional[PathLike]
log_every_n_steps: Optional[int]
monitor: Optional[str]
benchmark: Optional[bool]
gradient_clip_val: Optional[float]
precision: Optional[int... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.