code
stringlengths
17
6.64M
class DenseL1Error(nn.Module): 'Dense L1 loss averaged over channels.' def forward(self, pred: ty.T, target: ty.T) -> ty.T: return (pred - target).abs().mean(dim=1, keepdim=True)
class DenseL2Error(nn.Module): 'Dense L2 distance.' def forward(self, pred: ty.T, target: ty.T) -> ty.T: 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: ty.T, target: ty.T) -> ty.T: 'Dense L1 loss.' loss = (pred - target).abs() return loss
def log_l1_loss(pred: ty.T, target: ty.T) -> ty.T: 'Dense Log L1 loss.' loss = (1 + l1_loss(pred, target)).log() return loss
def berhu_loss(pred: ty.T, target: ty.T, delta: float=0.2, dynamic: bool=True) -> ty.T: '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: (bo...
@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. From FeatDepth (https://arxiv.org/abs/2007.10603).\n\n Heavily based on the Depth network with some changes:\n - Does not accept DPT encoders\n - Single decoder\n - Produces 3 sigmoid channels (RGB)\n ...
class StructurePerception(nn.Module): 'Self-attention Structure Perception Module.' def forward(self, x: ty.T) -> ty.T: (b, c, h, w) = x.shape v = x.view(b, c, (- 1)) (q, k) = (v, v.permute(0, 2, 1)) att = (q @ k) att = (att.max(dim=(- 1), keepdim=True)[0] - att) ...
class DetailEmphasis(nn.Module): 'Detail Emphasis Module.' 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.AdaptiveAvgPool2d(1), nn.Conv2d(ch, ch, kernel_size=1, stride=1,...
@register('cadepth') class CaDepthDecoder(nn.Module): "From CADepth (https://arxiv.org/abs/2112.13047)\n\n :param num_ch_enc: (list[int]) List of channels per encoder stage.\n :param enc_sc: (list[int]) List of downsampling factor per encoder stage.\n :param upsample_mode: (str) Torch upsampling mode. {'...
def get_discrete_bins(n: int, mode: str='linear') -> ty.T: '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 all ...
class SelfAttentionBlock(nn.Module): 'Self-Attention Block.' def __init__(self, ch: int): super().__init__() self.query_conv = nn.Sequential(nn.Conv2d(ch, ch, kernel_size=1, padding=0), nn.ReLU(inplace=True)) self.key_conv = nn.Sequential(nn.Conv2d(ch, ch, kernel_size=1, padding=0), n...
@register('ddvnet') class DDVNetDecoder(nn.Module): "From DDVNet (https://arxiv.org/abs/2003.13951)\n\n :param num_ch_enc: (list[int]) List of channels per encoder stage.\n :param enc_sc: (list[int]) List of downsampling factor per encoder stage.\n :param upsample_mode: (str) Torch upsampling mode. {'nea...
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: (None|int) Number of output channels.\n :param upsample_mode: (str) Torch upsamp...
@register('diffnet') class DiffNetDecoder(nn.Module): "From DiffNet (https://arxiv.org/abs/2110.09482)\n\n :param num_ch_enc: (list[int]) List of channels per encoder stage.\n :param enc_sc: (list[int]) List of downsampling factor per encoder stage.\n :param upsample_mode: (str) Torch upsampling mode. {'...
class FSEBlock(nn.Module): def __init__(self, in_ch: int, skip_ch: int, out_ch: ty.N[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 s...
@register('hrdepth') class HRDepthDecoder(nn.Module): "From HRDepth (https://arxiv.org/pdf/2012.07356.pdf)\n\n :param num_ch_enc: (ty.S[int]) List of channels per encoder stage.\n :param enc_sc: (ty.S[int]) List of downsampling factor per encoder stage.\n :param upsample_mode: (str) Torch upsampling mode...
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...
@register('monodepth') 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: (ty.S[int]) List of channels per encoder stage.\n :param enc_sc: (ty.S[int])...
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...
@register('superdepth') 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: (ty.S[int]) List of channels per encoder stage.\n :param enc_sc: (ty.S[int])...
def _load_roots() -> tuple[(Paths, Paths)]: 'Helper to load the additional model & data roots from the repo config.' file = (REPO_ROOT / 'PATHS.yaml') if (not file.is_file()): warnings.warn(_msg.format(file=file)) return ([], []) paths = io.load_yaml(file) return (io.lmap(Path, pat...
def _build_paths(names: ty.StrDict, roots: Paths, key: str='') -> ty.PathDict: '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: ...
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 trigger_nets() -> None: 'Trigger adding all networks to the registry.' with Timer(as_ms=True) as t: from src import networks logger.debug(f'Triggered registry networks in {t.elapsed}ms...')
def trigger_datas() -> None: 'Trigger adding all datasets to the registry.' with Timer(as_ms=True) as t: from src import datasets logger.debug(f'Triggered registry datasets in {t.elapsed}ms...')
def trigger_losses() -> None: 'Trigger adding all losses to the registry.' with Timer(as_ms=True) as t: from src import losses, regularizers logger.debug(f'Triggered registry losses in {t.elapsed}ms...')
def trigger_preds() -> None: 'Trigger adding all predictors to the registry.' with Timer(as_ms=True) as t: from src.core import predictors logger.debug(f'Triggered registry predictors in {t.elapsed}ms...')
def trigger_decoders() -> None: 'Trigger adding all predictors to the registry.' with Timer(as_ms=True) as t: from src.networks import decoders logger.debug(f'Triggered registry decoders in {t.elapsed}ms...')
def register(name: ty.U[(str, tuple[str])], type: ty.N[str]=None, overwrite: bool=False) -> CLS: "Class decorator to build a registry of networks, losses & data available during training.\n\n Example:\n ```\n # Register using default naming conventions. See `_NAME2TYPE`.\n @register('my_net')\n cla...
@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: ty.N[ty.U[(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.device...
def get_latest_ckpt(path: PathLike, ignore: ty.S[str]=None, reverse: bool=False, suffix: str='.ckpt') -> ty.N[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: (ty.S[str]) Filen...
def eps(x: ty.N[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 have the exact same parameters.' for (p1, p2) in zip(net1.parameters(), net2.parameters()): try: if (not p1.allclose(p2)): return False except RuntimeError: return False ...
def num_parameters(net: nn.Module, /, requires_grad: ty.N[bool]=None) -> int: 'Get number of parameters in a network. By default, all parameters are counted.' if (requires_grad is None): key = (lambda p: True) elif requires_grad: key = (lambda p: p.requires_grad) else: key = (l...
@map_container def to_torch(x: ty.Any, /, permute: bool=True, device: ty.N[torch.device]=None) -> ty.Any: 'Convert given input to `torch.Tensors`.\n\n :param x: (ty.Any) Arbitrary structure to convert to tensors (see `map_container`).\n :param permute: (bool) If `True`, permute to PyTorch convention (b, h, ...
@map_container def to_np(x: ty.Any, /, permute: bool=True) -> ty.Any: 'Convert given input to `numpy.ndarrays`.\n\n :param x: (ty.Any) Arbitrary structure to convert to ndarrays (see map_container).\n :param permute: (bool) If `True`, permute from PyTorch convention (b, c, h, w) -> (b, h, w, c).\n :retur...
@map_container def op(_x: ty.Any, /, *args, fn: ty.U[(str, ty.Callable)], **kwargs) -> ty.Any: "Apply a function to an 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 `input`...
@opt_args_deco def allow_np(fn: ty.N[ty.Callable], permute: bool=False) -> ty.Callable: "Decorator to allow for `np.ndarray` inputs into a torch function.\n\n Objective is to implement the function using torch ops and apply this decorator to also make it numpy friendly.\n Since `numpy.ndarray` and `torch.Te...
def dilate_mask(mask: ty.T, kernel_size: int=3) -> ty.T: 'Apply morphological dilation to the input binary mask.\n\n If any pixel within the kernel is a valid pixel (`True`), the central point is added to the mask.\n\n :param mask: (Tensor) (b, 1, h, w) Boolean mask indicating valid pixels.\n :param kern...
def erode_mask(mask: ty.T, kernel_size: int=3) -> ty.T: 'Apply morphological erosion to the given binary mask.\n\n If any pixel within the kernel is not a valid pixel (`False`), the central point is removed from the mask.\n Since PyTorch does not provide `min_pool` we simply invert the dilation process.\n\n...
@allow_np(permute=True) def standardize(x: ty.T, /, mean: StatsRGB=_mean, std: StatsRGB=_std) -> ty.T: '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) / s...
@allow_np(permute=True) def unstandardize(x: ty.T, /, mean: StatsRGB=_mean, std: StatsRGB=_std) -> ty.T: '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 * std) +...
@allow_np(permute=True) def to_gray(x: ty.T, /, coeffs: StatsRGB=_coeffs, keepdim: bool=False) -> ty.T: '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: ty.T, /, dim: ty.U[(int, ty.S[int])]=(2, 3)) -> ty.T: 'Apply mean normalization across the specified dimensions.\n\n :param x: (Tensor) (*) Input tensor to normalize of any shape.\n :param dim: (int | ty.S[int]) Dimension(s) to compute the mean across.\n :return: (Tensor) (*) Mean n...
def eye_like(x: ty.T, /) -> ty.T: 'Create an Identity matrix of the same dtype and size as the input.\n\n NOTE: The input can be of any shape, except 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 :ret...
def interpolate_like(input: ty.T, /, other: ty.T, mode: str='nearest', align_corners: bool=False) -> ty.T: '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_corners)
def expand_dim(x: ty.T, /, num: ty.U[(int, ty.S[int])], dim: ty.U[(int, ty.S[int])]=0, insert: bool=False) -> ty.T: '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, 1)\n >>> ex...
def min(x: ty.T, dim: ty.N[ty.U[(int, ty.S)]]=None, keepdim: bool=False): 'Find the min values of the input tensor along the desired dimension(s).\n Wrapper around `torch.min` that returns only the min value and can be applied to multiple dimensions.\n\n :param x: (Tensor) (*) Input tensor of any shape.\n ...
def max(x: ty.T, dim: ty.N[ty.U[(int, ty.S)]]=None, keepdim: bool=False): 'Find the max values of the input tensor along the desired dimension(s).\n Wrapper around `torch.max` that returns only the max value and can be applied to multiple dimensions.\n\n :param x: (Tensor) (*) Input tensor of any shape.\n ...
def get_cls(cls_dict: dict[(str, ty.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 cfg...
def get_net(cfg: dict) -> nn.ModuleDict: "Instantiate the target networks from a cfg dict.\n\n Depth estimation typically consists of multiple networks, commonly `depth` and `pose`.\n We assume that, within a given category, we can use different classes interchangeably.\n For instance, all `depth` networ...
def get_loss(cfg: dict) -> tuple[(nn.ModuleDict, nn.ParameterDict)]: "Instantiate the target losses from a cfg dict.\n\n In addition to the kwargs required to instantiate the loss, we also expect a `weight` kwarg, used to\n balance the various losses when computing the final loss. (Default: 1)\n\n Losses...
def get_ds(cfg: dict, mode: ty.N[str]=None) -> dict[(str, Dataset)]: "Instantiate the target datasets from a cfg dict.\n\n Datasets consist of a default cfg for each class, which can be overriden based on a `mode` sub-dict.\n\n Datasets can be omitted by setting their cfg to `None`. Useful when overriding t...
def get_dl(mode: str, cfg_ds: dict, cfg_dl: dict) -> DataLoader: "Instantiate the target dataloader from a cfg dict.\n\n Dataloaders consist of a default cfg, which can be overriden based on a `mode` sub-dict.\n The datasets are expected to be a subclass of `BaseDataset`, which provides a `collate_fn` metho...
def get_opt(parameters: ty.U[(ty.Iterable, nn.Module)], cfg: dict) -> optim.Optimizer: "Instantiate the target optimizer from a cfg dict. Wrapper for `timm` `create_optimizer_v2`.\n\n Example:\n ```\n cfg = {\n 'type': 'adamw',\n 'lr': 1e-3,\n 'weight_decay': 1e-4,\n 'frozen_b...
def get_sched(opt: optim.Optimizer, cfg: dict[(str, dict)]) -> dict[(str, ty._LRScheduler)]: "Instantiate the target schedulers from a cfg dict. Wrapper for `timm` `create_scheduler_v2`.\n\n Example:\n ```\n cfg = {\n 'steplr': {\n 'step_size': 10,\n 'gamma': 0.1,\n },...
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)})
def _get_percentile(x: ty.A, p: int) -> float: 'Safe percentile to handle NaNs/Inf.' try: return np.percentile(x, p) except IndexError: return 0.0
@ops.allow_np(permute=True) def rgb_from_disp(disp: ty.T, invert: bool=False, cmap: str='turbo', vmin: float=0, vmax: ty.N[ty.U[(float, ty.S[float])]]=None) -> ty.T: 'Convert a disparity map into an RGB colormap visualization.\n\n :param disp: (Tensor) (*b, *1, h, w) Input disparity/depth map.\n :param inve...
@ops.allow_np(permute=True) def rgb_from_feat(feat: ty.T) -> ty.T: '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: (Te...
class SuppImageNotFoundError(FileNotFoundError): pass
class Predictor(Protocol): @staticmethod def get_img_shape(data_type: str) -> N[tuple[(int, int)]]: ... def __call__(self, net: nn.Module, dl: DataLoader, use_stereo_blend: bool, device: N[str]) -> NDArray: ... def apply(self, net: nn.Module, dl: DataLoader, func: Callable, use_ster...
class DepthPred(TypedDict, total=False): depth_feats: S[T] disp: dict[(int, T)] disp_stereo: dict[(int, T)] mask: dict[(int, T)] mask_stereo: dict[(int, T)]
class PosePred(TypedDict, total=False): R: T t: T fs: T cs: T
class AutoencoderPred(TypedDict, total=True): autoenc_feats: S[T] autoenc_imgs: dict[(int, T)]
class TQDMProgressBar(plc.TQDMProgressBar): 'Progress bar that removes all `grad norms` from display.' def get_metrics(self, trainer, pl_module) -> dict: m = super().get_metrics(trainer, pl_module) m = {k: v for (k, v) in m.items() if ('grad' not in k)} return m
class RichProgressBar(plc.RichProgressBar): 'Progress bar that removes all `grad norms` from display.' def get_metrics(self, trainer, pl_module) -> dict: m = super().get_metrics(trainer, pl_module) m = {k: v for (k, v) in m.items() if ('grad' not in k)} return m
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) -> None: if (not (loss := outputs['loss']).isfinite()): raise ValueError(f'Detec...
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__() self.ckpt_dir = ckpt_dir self.ckpt_dir.mkdir(exist_ok=True, parents=True) self.host = socket.gethostn...
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 collate(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): "\n General collate function that handles collection type of element within each batch\n and opens function registry to deal with specific element types. `default_collate_fn_map`\n provi...
def collate_tensor_fn(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): elem = batch[0] out = None if (torch.utils.data.get_worker_info() is not None): numel = sum((x.numel() for x in batch)) storage = elem._typed_storage()._new_shared(numel, de...
def collate_numpy_array_fn(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): elem = batch[0] if (np_str_obj_array_pattern.search(elem.dtype.str) is not None): raise TypeError(default_collate_err_msg_format.format(elem.dtype)) return collate([torch.as_te...
def collate_numpy_scalar_fn(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): return torch.as_tensor(batch)
def collate_float_fn(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): return torch.tensor(batch, dtype=torch.float64)
def collate_int_fn(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): return torch.tensor(batch)
def collate_str_fn(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): return batch
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: ty.Callable) -> ty.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...
def delegates(to: ty.N[ty.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: ty.Callable) -> ty.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 readlines(file: Path, /, encoding: str=None, split: bool=False, sep: ty.N[str]=None) -> ty.U[(list[str], list[list[str]])]: 'Read file as a list of strings.' with open(file, encoding=encoding) as f: lines = f.read().splitlines() if split: lines = splitlines(lines, sep) ...
def splitlines(lines: list[str], sep: ty.N[str]=None) -> list[list[str]]: 'Split each line in a list of lines.' return [l.split(sep) for l in lines]
def mymap(fn: str, iterable: ty.Iterable, type: ty.N[T]=list, **kwargs) -> ty.U[(ty.Generator, T)]: 'Apply instance method `fn` to each item in `iterable`.\n\n :param fn: (str) Function name to search as an attribute of each item.\n :param iterable: (Iterable) Iterable to apply function to.\n :param type...
def _map(fn: ty.Callable, *iterables: ty.Iterable, type: T, star: bool=False) -> T: 'Map `fn` to each iterable item and convert to the specified container `type`.' map_fn = (itertools.starmap if star else map) return type(map_fn(fn, *iterables))
def iterdir(path: Path, key: ty.N[Key]=None) -> list[Path]: 'Get sorted contents in path, optionally filtered by the `key`.' key = (key or (lambda f: True)) return sorted(filter(key, path.iterdir()))
def get_dirs(path: Path, key: ty.N[Key]=None) -> list[Path]: 'Get sorted directories in a path, optionally filtered by the `key`.' _key = (lambda p: (p.is_dir() and (key(p) if key else True))) return iterdir(path, _key)
def get_files(path: Path, key: ty.N[Key]=None) -> list[Path]: 'Get sorted files in a path, optionally filtered by the `key`.' _key = (lambda p: (p.is_file() and (key(p) if key else True))) return iterdir(path, _key)
def has_contents(path: Path) -> bool: 'Check if directory is not empty.' return (path.is_dir() and bool(iterdir(path)))