code stringlengths 17 6.64M |
|---|
@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... |
class MonoDepthCfg(TypedDict):
'Monocular depth trainer config. See each sub-class for details.'
net: NetCfg
loss: LossCfg
dataset: DataCfg
loader: LoaderCfg
optimizer: OptCfg
scheduler: SchedCfg
trainer: TrainCfg
|
def _apply_op(img: Tensor, op_name: str, magnitude: float, interpolation: InterpolationMode, fill: Optional[List[float]]):
if (op_name == 'ShearX'):
raise ValueError(f'Attempted geometric transformation "{op_name}"')
elif (op_name == 'ShearY'):
raise ValueError(f'Attempted geometric transforma... |
class AutoAugmentPolicy(Enum):
'AutoAugment policies learned on different data.\n Available policies are IMAGENET, CIFAR10 and SVHN.\n '
IMAGENET = 'imagenet'
CIFAR10 = 'cifar10'
SVHN = 'svhn'
|
class AutoAugment(torch.nn.Module):
'AutoAugment data augmentation method based on\n `"AutoAugment: Learning Augmentation Strategies from Data" <https://arxiv.org/pdf/1805.09501.pdf>`_.\n If the image is torch Tensor, it should be of type torch.uint8, and it is expected\n to have [..., 1 or 3, H, W] shap... |
class RandAugment(torch.nn.Module):
'RandAugment data augmentation method based on\n `"RandAugment: Practical automated data augmentation with a reduced search space"\n <https://arxiv.org/abs/1909.13719>`_.\n If the image is torch Tensor, it should be of type torch.uint8, and it is expected\n to have ... |
class TrivialAugmentWide(torch.nn.Module):
'Dataset-independent data-augmentation with TrivialAugment Wide, as described in\n `"TrivialAugment: Tuning-free Yet State-of-the-Art Data Augmentation" <https://arxiv.org/abs/2103.10158>`.\n If the image is torch Tensor, it should be of type torch.uint8, and it is... |
class RichProgressBar(plc.RichProgressBar):
'Progress bar that removes all `grad norms` from display.'
def get_metrics(self, trainer, pl_module):
m = super().get_metrics(trainer, pl_module)
m = {k: v for (k, v) in m.items() if ('grad' not in k)}
return m
|
class TQDMProgressBar(plc.TQDMProgressBar):
'Progress bar that removes all `grad norms` from display.'
def get_metrics(self, trainer, pl_module):
m = super().get_metrics(trainer, pl_module)
m = {k: v for (k, v) in m.items() if ('grad' not in k)}
return m
|
class TrainingManager(plc.Callback):
'Callback to save a dummy file as an indicator when training has started/finished.'
def __init__(self, ckpt_dir: Path):
super().__init__()
ckpt_dir.mkdir(exist_ok=True, parents=True)
self.fstart = (ckpt_dir / 'training')
if self.fstart.is_f... |
class DetectAnomaly(plc.Callback):
'Check for NaN/infinite loss at each core step. Replacement for `detect_anomaly=True`.'
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, unused=0):
if (not (loss := outputs['loss']).isfinite()):
raise ValueError(f'Detected NaN/... |
def default_convert(data):
"\n Function that converts each NumPy array element into a :class:`torch.Tensor`. If the input is a `Sequence`,\n `Collection`, or `Mapping`, it tries to convert each element inside to a :class:`torch.Tensor`.\n If the input is not an NumPy array, it is left unchang... |
def default_collate(batch):
"\n Function that takes in a batch of data and puts the elements within the batch\n into a tensor with an additional outer dimension - batch size. The exact output type can be\n a :class:`torch.Tensor`, a `Sequence` of :class:`torch.Tensor`, a\n Collection o... |
def opt_args_deco(deco: Callable) -> Callable:
'Meta-decorator to make implementing of decorators with optional arguments more intuitive\n\n Recall: Decorators are equivalent to applying functions sequentially\n >>> func = deco(func)\n\n If we want to provide optional arguments, it would be the equiv... |
def delegates(to: Optional[Callable]=None, keep: bool=False):
'From https://www.fast.ai/2019/08/06/delegation/\n Decorator to replace `**kwargs` in signature with params from `to`.\n\n This can be used to decorate either a class\n ```\n @delegates()\n class Child(Parent): ...\n ```\n ... |
def map_container(f: Callable) -> Callable:
"Decorator to recursively apply a function to arbitrary nestings of `dict`, `list`, `tuple` & `set`\n\n NOTE: `f` can have an arbitrary signature, but the first arg must be the item we want to apply `f` to.\n\n Example:\n ```\n @map_apply\n def sq... |
@opt_args_deco
def retry_new_on_error(__getitem__: Callable, exc: Union[(BaseException, Sequence[BaseException])]=Exception, silent: bool=False, max: Optional[int]=None, use_blacklist: bool=False) -> Callable:
'Decorator to wrap a BaseDataset __getitem__ function, and retry a different index if there is an error.... |
def readlines(file: PathLike, /, encoding=None) -> list[str]:
'Read file as a list of strings.'
with open(file, encoding=encoding) as f:
return f.read().splitlines()
|
def pil2np(img: Image, /) -> NDArray:
'Convert PIL image [0, 255] into numpy [0, 1].'
return (np.array(img, dtype=np.float32) / 255.0)
|
def np2pil(arr: NDArray, /) -> Image:
'Convert numpy image [0, 1] into PIL [0, 255].'
return Image.fromarray((arr * 255).astype(np.uint8))
|
def write_yaml(file: PathLike, data: dict, mkdir: bool=False, sort_keys: bool=False) -> None:
'Write data to a yaml file.'
file = Path(file).with_suffix('.yaml')
if mkdir:
file.parent.mkdir(parents=True, exist_ok=True)
with open(file, 'w') as f:
yaml.dump(data, f, sort_keys=sort_keys)
|
def load_yaml(file: PathLike) -> dict:
'Load a single yaml file. '
with open(file) as f:
data = yaml.load(f, Loader=yaml.FullLoader)
return data
|
def load_merge_yaml(*files: PathLike) -> dict:
'Load a list of YAML cfg and recursively merge into a single config.\n\n Following dictionary merging rules, the first file is the "base" config, which gets updated by the second file.\n We chain this rule for however many cfg we have, i.e. ((((1 <- 2) <- 3) <-... |
def _merge_yaml(old: dict, new: dict) -> dict:
'Recursively merge two YAML cfg.\n Dictionaries are recursively merged. All other types simply update the current value.\n\n NOTE: This means that a "list of dicts" will simply be updated to whatever the new value is,\n not appended to or recursively checked... |
class BaseMetric(Metric):
higher_is_better = False
full_state_update = False
'Base class for depth estimation metrics.'
def __init__(self, mode: str='raw', **kwargs):
super().__init__(**kwargs)
assert (mode in MODES)
self.mode: str = mode
self.sf: int = {'raw': 1, 'log... |
class MAE(BaseMetric):
'Compute the mean absolute error.'
def _compute(self, pred: Tensor, target: Tensor) -> Tensor:
return (pred - target).abs().nanmean(dim=1)
|
class RMSE(BaseMetric):
'Compute the root mean squared error.'
def _compute(self, pred: Tensor, target: Tensor) -> Tensor:
return (pred - target).pow(2).nanmean(dim=1).sqrt()
|
class ScaleInvariant(BaseMetric):
'Compute the scale invariant error.'
def _compute(self, pred: Tensor, target: Tensor) -> Tensor:
err = (pred - target)
return (err.pow(2).nanmean(dim=1) - err.nanmean(dim=1).pow(2)).sqrt()
|
class AbsRel(BaseMetric):
'Compute the absolute relative error.'
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.sf = 100
def _compute(self, pred: Tensor, target: Tensor) -> Tensor:
return ((pred - target).abs() / target).nanmean(dim=1)
|
class SqRel(BaseMetric):
'Compute the absolute relative squared error.'
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.sf = 100
def _compute(self, pred: Tensor, target: Tensor) -> Tensor:
return ((pred - target).pow(2) / target.pow(2)).nanmean(dim=1)
|
class DeltaAcc(BaseMetric):
higher_is_better = True
'Compute the accuracy for a given error threshold.'
def __init__(self, delta: float, **kwargs):
super().__init__(**kwargs)
assert (self.mode == 'raw'), 'Accuracy should only be computed using raw depths.'
self.delta: float = delt... |
class Timer():
"Context manager for timing a block of code.\n\n Attributes:\n :param name: (str) Timer label when printing.\n :param as_ms: (bool) If `True`, store time as `milliseconds`, otherwise `seconds`.\n :param sync_gpu: (bool) If `True`, ensure that GPU is synced on Timer enter and exit.\n ... |
class MultiLevelTimer():
"Context manager Timer capable of being nested across multiple levels.\n\n NOTE: We use the *instance* of this class as a context manager, not the class itself (see examples).\n\n Timers are stored as a dict, mapping labels to (depth, start, end, elapsed).\n In order to allow for... |
def _get_items(split, mode):
file = kr.get_split_file(split, mode)
if ((split == 'benchmark') and (mode == 'test')):
return []
side2cam = {'l': 'image_02', 'r': 'image_03'}
lines = [line.split() for line in io.readlines(file)]
items = [{'seq': line[0], 'cam': side2cam[line[2]], 'stem': int... |
class TestKitti():
def test_image_files(self):
(splits, seqs) = ([], [])
for s in SPLITS:
for m in MODES:
for i in _get_items(s, m):
f = kr.get_image_file(i['seq'], i['cam'], i['stem'])
if (not f.is_file()):
... |
def _get_items(split, mode):
file = kr.get_split_file(split, mode)
if ((split == 'benchmark') and (mode == 'test')):
return []
side2cam = {'l': 'image_02', 'r': 'image_03'}
lines = [line.split() for line in io.readlines(file)]
items = [{'seq': line[0].split('/')[0], 'drive': line[0].split(... |
class TestKitti():
def test_image_files(self):
(splits, seqs) = ([], [])
for s in SPLITS:
for m in MODES:
for i in _get_items(s, m):
f = kr.get_images_path(i['seq'], i['drive'], i['cam'])
if (not f.is_dir()):
... |
def _get_items(mode):
return syp.load_split(mode)[1]
|
class TestKitti():
def test_image_files(self):
(modes, scenes) = ([], [])
for m in MODES:
for i in _get_items(m):
f = syp.get_image_file(*i)
if (not f.is_file()):
scenes.append(i[0])
modes.append(f'{m}')
a... |
class TmpData(BaseDataset):
def __init__(self, n, **kwargs):
self.n = range(n)
super().__init__(**kwargs)
def __len__(self):
return len(self.n)
def load(self, item, x, y, meta):
x['item'] = self.n[item]
return (x, y, meta)
def augment(self, x, y, meta):
... |
class TestBaseDataset():
def test_base(self):
'Test that we have the expected functions.'
with pytest.raises(TypeError):
_ = BaseDataset()
assert hasattr(BaseDataset, '__repr__'), 'Missing attribute from base dataset.'
assert hasattr(BaseDataset, '__len__'), 'Missing a... |
def test_all():
'Check all expected symbols are imported.'
items = {'register', 'NET_REG', 'DATA_REG', 'LOSS_REG', 'SCHED_REG'}
assert (set(registry.__all__) == items), 'Incorrect keys in `__all__`.'
|
def test_sched():
'Check scheduler registry has all expected keys.'
keys = {'steplr', 'exp', 'cos', 'cos_warm', 'plateau'}
assert (set(SCHED_REG.keys()) == keys), f'Incorrect SCHEDULER keys.'
|
def test_add_net():
'Check adding to the network registry.'
(name, type) = ('test', 'net')
@register(name, type)
class Test():
...
assert (name in NET_REG), 'Missing item from NETWORK registry.'
NET_REG.pop(name)
|
def test_add_loss():
'Check adding to the loss registry.'
(name, type) = ('test', 'loss')
@register(name, type)
class Test():
...
assert (name in LOSS_REG), 'Missing item from LOSS registry.'
LOSS_REG.pop(name)
|
def test_add_dataset():
'Check adding to the dataset registry.'
(name, type) = ('test', 'data')
@register(name, type)
class Test():
...
assert (name in DATA_REG), 'Missing item from DATASET registry.'
DATA_REG.pop(name)
|
def test_add_auto():
'Check automatic adding based on class name.'
name = 'test'
@register(name)
class TestNet():
...
assert (name in NET_REG), 'Missing item from automatic NET registry.'
NET_REG.pop(name)
@register(name)
class TestLoss():
...
assert (name in LOSS... |
def test_add_multiple():
name = ('test1', 'test2')
@register(name, type='net')
class TestNet():
...
for n in name:
assert (n in NET_REG), 'Missing item from automatic NET registry.'
[NET_REG.pop(n) for n in name]
|
def test_register_types():
'Check raised exception when adding to unknown registry.'
with pytest.raises(TypeError):
@register(name='temp', type='foo')
class Test():
...
|
def test_register_duplicates():
'Check raised exception when registering a duplicate name.'
(name, type) = ('test', 'net')
@register(name, type)
class Test():
...
with pytest.raises(ValueError):
@register(name, type)
class Test2():
...
with pytest.raises(V... |
def test_register_overwrite():
'Check registry items can be overwritten if desired.'
(name, type) = ('test', 'net')
@register(name, type)
class Test():
...
assert (NET_REG[name] == Test), 'Unexpected base class when overwriting.'
@register(name, type, overwrite=True)
class Test2(... |
def test_ignore_main():
'Check classes created in `__main__` are ignored.'
from unittest.mock import Mock
(name, type) = ('test', 'loss')
Mock.__module__ = '__main__'
with pytest.warns(UserWarning):
_ = register(name, type)(Mock)
assert (name not in LOSS_REG), 'Class from `__main__` no... |
def test_all():
'Check all expected symbols are imported.'
items = {'MaskReg'}
assert (set(mask.__all__) == items), 'Incorrect keys in `__all__`.'
|
def test_registry():
'Check MaskReg is added to LOSS_REGISTRY.'
assert ('disp_mask' in LOSS_REG), 'Missing key from loss registry.'
assert (LOSS_REG['disp_mask'] == MaskReg), 'Incorrect class in loss registry.'
|
def test_mask():
'Test MaskReg when all values are 1.'
shape = (1, 1, 100, 200)
(loss, loss_dict) = MaskReg().forward(torch.ones(shape))
assert (loss == 0), 'Error in correct BCELoss.'
assert (not loss_dict), 'Unexpected keys in `loss_dict`.'
(loss, loss_dict) = MaskReg().forward(torch.zeros(s... |
def test_all():
'Check all expected symbols are imported.'
items = {'OccReg'}
assert (set(occlusion.__all__) == items), 'Incorrect keys in `__all__`.'
|
def test_registry():
'Check OcclusionReg is added to LOSS_REGISTRY.'
assert ('disp_occ' in LOSS_REG), 'Missing key from loss registry.'
assert (LOSS_REG['disp_occ'] == OccReg), 'Incorrect class in loss registry.'
|
def test_occlusion_ones():
'Test OcclusionReg when all values are 1.'
shape = (1, 1, 100, 200)
input = torch.ones(shape)
(loss, loss_dict) = OccReg(invert=False).forward(input)
assert (loss == 1.0), 'Error in `invert=False`.'
assert (not loss_dict), 'Unexpected keys in `loss_dict`.'
(loss,... |
def test_occlusion_rand():
'Test OcclusionReg with a random tensor.'
shape = (1, 1, 100, 200)
input = torch.rand(shape)
mean = input.mean()
(loss, loss_dict) = OccReg(invert=False).forward(input)
assert (loss == mean), 'Error in `invert=False`.'
assert (not loss_dict), 'Unexpected keys in ... |
def test_all():
'Check all expected symbols are imported.'
items = {'SmoothReg', 'FeatPeakReg', 'FeatSmoothReg'}
assert (set(smooth.__all__) == items), 'Incorrect keys in `__all__`.'
|
def test_registry():
'Check smoothness regularizations are added to LOSS_REGISTRY.'
assert ('disp_smooth' in LOSS_REG), 'Missing key from loss registry.'
assert (LOSS_REG['disp_smooth'] == SmoothReg), 'Incorrect class in loss registry.'
assert ('feat_peaky' in LOSS_REG), 'Missing key from loss registr... |
def test_all():
'Check all expected symbols are imported.'
items = {'rgb_from_disp', 'rgb_from_feat'}
assert (set(viz.__all__) == items), 'Incorrect keys in `__all__`.'
|
class TestRGBfromDisp():
def test_default(self):
x = torch.rand(2, 1, 10, 20)
out = rgb_from_disp(x)
out2 = rgb_from_disp(x, cmap='turbo', vmin=0, vmax=[np.percentile(x[0], 95), np.percentile(x[1], 95)])
assert np.allclose(out, out2), 'Incorrect default params.'
def test_rang... |
class TestRGBfromFeat():
def test_norm(self):
x = torch.rand(1, 5, 10, 20)
out = rgb_from_feat(x).squeeze().flatten((- 2), (- 1))
assert torch.allclose(out.min((- 1))[0], out.new_zeros(3)), 'Incorrect min norm.'
assert torch.allclose(out.max((- 1))[0], out.new_ones(3)), 'Incorrect... |
class TestDefaultCollate():
def test_base(self):
torch_collate = torch.utils.data._utils.collate.default_collate
input = [torch.rand(3, 100, 200) for _ in range(5)]
target = torch_collate(input)
out = default_collate(input)
assert out.allclose(target), 'Error when matching... |
def test_all():
'Check all expected symbols are imported.'
items = {'opt_args_deco', 'delegates', 'map_container', 'retry_new_on_error'}
assert (set(deco.__all__) == items), 'Incorrect keys in `__all__`.'
|
@opt_args_deco
def _deco(func, prefix='', suffix=''):
'Helper.'
def wrapper(*args, **kwargs):
out = func(*args, **kwargs)
return (out, f'{prefix}{out}{suffix}')
return wrapper
|
def _add(a, b):
'Helper.'
return (a + b)
|
class TestOptArgsDeco():
def test_base(self):
'Test different ways of instantiating optional arguments.'
func = _deco(_add)
assert (func(1, 2) == (3, '3')), 'Error with default arguments.'
func = _deco(_add, prefix='***')
assert (func(1, 2) == (3, '***3')), 'Error with fir... |
def _parent(a, b=0, c=None, **kwargs):
...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.