code
stringlengths
17
6.64M
@tenacity.retry(stop=tenacity.stop_after_attempt(3), retry=tenacity.retry_if_result(is_false), retry_error_callback=return_last_value) def sync_dir(source, target, file_ext=None, verbose=True): "Sync a directory from source to target (either local to s3, s3 to s3, s3 to local)\n\n Parameters\n ----------\n ...
def parallel_s3_sync(source_paths, target_paths, threadpool_size=None): 'Copy directories from local to s3, s3 to local, or s3 to s3 using a threadpool.\n Retry the operation if any files fail to sync. Throw an AssertionError if it fails the 2nd time.\n\n Parameters\n ----------\n source_paths: List o...
def sync_dir_safe(source, target, verbose=True): 'Sync a directory from local to s3 by first ensuring that NONE of the files in `target`\n have been edited in `source` (new files can exist in `source` that are not in `target`)\n (NOTE: only checks files from `target` that exist in `source`)\n\n Parameter...
def s3_bucket(bucket_name): 'Instantiate S3 bucket object from its bucket name\n\n Parameters\n ----------\n bucket_name : str\n Bucket name to instantiate.\n\n Returns\n -------\n S3 bucket\n ' return boto3.session.Session().resource('s3').Bucket(bucket_name)
def list_s3_objects(bucket_name, url): 'List all files within a valid S3 bucket\n\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n url : str\n The remote URL of the object to be fetched\n ' return list(s3_bucket(bucket_name).objects.filter(Prefix=url))
def exists_s3_object(bucket_name, url): 'Uses a valid S3 bucket to check the existence of a remote file as AWS URL.\n\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n url : str\n The remote URL of the object to be fetched\n\n Returns\n -------\n bool:\...
def convert_uri_to_bucket_path(uri, strip_trailing_slash=True): "Parse a URI into a bucket and path.\n\n Parameters\n ----------\n uri: str\n A full s3 path (e.g. 's3://<s3-bucket>/<s3-prefix>')\n\n strip_trailing_slash: bool, optional\n If True, we strip any trailing slash in `s3_path` ...
def parallel_download_s3_objects(s3_files, destination_filepaths, bucket_name, process_pool_size=None): 'Download a list of s3 objects using a processpool.\n\n Parameters\n ----------\n s3_files: list\n List of all files from s3 to download\n\n destination_filepaths: list\n List of where to ...
def parallel_upload_s3_objects(source_filepaths, s3_destinations, bucket_name, process_pool_size=None): 'Upload a list of s3 objects using a processpool.\n\n Parameters\n ----------\n source_filepaths: list\n List of all local files to upload.\n\n s3_destinations: list\n Paths relative to bu...
def download_s3_object_to_path(bucket_name, s3_path, local_path): 'Download an object from s3 to a path on the local filesystem.\n\n Parameters\n ----------\n bucket_name: str\n S3 bucket from which to fetch.\n\n s3_path: str\n The path on the s3 bucket to the file to fetch.\n\n local...
def delete_s3_object(bucket_name, object_key, verbose=True): 'Delete an object in s3.\n\n Parameters\n ----------\n bucket_name: str\n S3 bucket of the object to delete.\n\n object_key: str\n Key name of the object to delete.\n\n verbose: bool, optional\n If True print messages...
def upload_file_to_s3(bucket_name, local_file_path, bucket_rel_path): '\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n local_file_path: str\n Local path to file we want to upload\n\n bucket_rel_path: str\n Path where file is uploaded, relative to S3...
def get_s3_object(bucket_name, url): 'Uses a valid S3 bucket to retrieve a file from a remote AWS URL.\n Raises ValueError if non-existent.\n\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n url : str\n The remote URL of the object to be fetched\n\n Retur...
def get_string_from_s3_file(bucket_name, url): 'Uses a valid S3 bucket to retrieve an UTF-8 decoded string from a remote AWS URL.\n Raises ValueError if non-existent.\n\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n url : str\n The remote URL of the object...
def open_remote_json(s3_path): 'Loads a remote JSON file\n\n Parameters\n ----------\n s3_path: str\n Full s3 path to JSON file\n\n Returns\n -------\n dict:\n Loaded JSON\n ' assert (s3_path.startswith('s3://') and s3_path.endswith('.json')) (bucket, rel_path) = convert...
class RemoteArtifactFile(): def __init__(self, artifact): 'Context manager for a remote file on S3.\n\n Parameters\n ----------\n artifact : mgp.remote_pb2.RemoteArtifact\n Remote artifact object that contains the url and the sha1sum of the file\n\n url : str\n ...
def list_prefixes_in_s3_dir(s3_path): '\n List prefixes in S3 path.\n *CAVEAT*: This function was only tested for S3 path that contains purely one-level prefix, i.e. no regular objects.\n Parameters\n ----------\n s3_path: str\n An S3 path.\n Returns\n -------\n prefixes: List of st...
def list_prefixes_in_s3(s3_prefix): '\n List prefixes in S3 path.\n *CAVEAT*: This function was only tested for S3 prefix for files. E.g., if the bucket looks like the following,\n - s3://aa/bb/cc_v01.json\n - s3://aa/bb/cc_v02.json\n - s3://aa/bb/cc_v03.json\n then list_prefixes...
def get_split_to_scenes(dataset): '\n Retrieve a dictionary of split to scenes of a DGP-compliant scene dataset.\n\n Parameters\n ----------\n dataset: dgp.proto.dataset_pb2.SceneDataset\n SceneDataset proto object.\n\n Returns\n -------\n split_to_scene_json: dict\n A dictionar...
def open_pbobject(path, pb_class): 'Load JSON as a protobuf (pb2) object.\n\n Any calls to load protobuf objects from JSON in this repository should be through this function.\n Returns `None` if the loading failed.\n\n Parameters\n ----------\n path: str\n Local JSON file path or remote scen...
def parse_pbobject(source, pb_class): 'Like open_pboject but source can be a path or a bytestring\n\n Parameters\n ----------\n source: str or bytes\n Local JSON file path, remote s3 path to object, or bytestring of serialized object\n\n pb_class: object\n Protobuf pb2 object we want to ...
def open_remote_pb_object(s3_object_uri, pb_class): 'Load JSON as a protobuf (pb2) object from S3 remote\n\n Parameters\n ----------\n s3_object_uri: str\n Remote scene dataset JSON URI.\n\n pb_class: object\n Protobuf pb2 object we want to load into.\n\n Returns\n ----------\n ...
def save_pbobject_as_json(pb_object, save_path): '\n Save protobuf (pb2) object to JSON file with our standard indent, key ordering, and other\n settings.\n\n Any calls to save protobuf objects to JSON in this repository should be through this function.\n\n Parameters\n ----------\n pb_object: o...
def open_ontology_pbobject(ontology_file): 'Open ontology objects, first attempt to open V2 before trying V1.\n\n Parameters\n ----------\n ontology_file: str or bytes\n JSON ontology file path to load or bytestring.\n\n Returns\n -------\n ontology: Ontology object\n Desired Ontol...
def open_feature_ontology_pbobject(ontology_file): 'Open feature ontology objects.\n\n Parameters\n ----------\n ontology_file: str\n JSON ontology file path to load.\n\n Returns\n -------\n ontology: FeatureOntology object\n Desired Feature Ontology pb2 object to be opened. Return...
def generate_uid_from_pbobject(pb_object): 'Given a pb object, return the deterministic SHA1 hash hexdigest.\n Used for creating unique IDs.\n\n Parameters\n ----------\n pb_object: object\n A protobuf pb2 object to be hashed.\n\n Returns\n -------\n Hexdigest of annotation content\n ...
def get_latest_scene(s3_scene_jsons): "From a list of 'scene.json' and/or 'scene_<sha1>.json' paths in s3,\n return a Scene object for the one with the latest timestamp.\n Parameters\n ----------\n s3_scene_jsons: List[str]\n List of 'scene.json' or 'scene_<sha1>.json' paths in s3\n Returns\...
def get_scene_statistics(scene, verbose=True): 'Given a DGP scene, return simple statistics (counts) of the scene.\n\n Parameters\n ----------\n scene: dgp.proto.scene_pb2.Scene\n Scene Object.\n\n verbose: bool, optional\n Print the stats if True. Default: True.\n\n Returns\n ----...
def _get_bounding_box_annotation_info(annotation_enum): 'Returns datum_type, annotation_pb given an ontology\n Parameters\n ----------\n annotation_enum: dgp.proto.annotations_pb2.AnnotationType\n Annotation type enum\n\n Returns\n -------\n str, dgp.proto.annotations_pb2.[AnnotationClass...
def get_scene_class_statistics(scene, scene_dir, annotation_enum, ontology=None): 'Given a DGP scene, return class counts of the annotations in the scene.\n\n Parameters\n ----------\n scene: dgp.proto.scene_pb2.Scene\n Scene Object.\n\n scene_dir: string\n s3 URL or local path to scene....
class BoundingBox2D(): '2D bounding box object.\n\n Parameters\n ----------\n box: np.ndarray[np.float32]\n Array of 4 floats describing bounding box coordinates. Can be either ([l, t, r, b] or [l, t, w, h]).\n\n class_id: int, default: GENERIC_OBJECT_CLASS\n Integer class ID (0 reserved...
class InstanceMask2D(): '2D instance mask object.\n\n Parameters\n ----------\n mask: np.ndarray[bool, np.uint8, np.int64]\n 2D boolean array describiing instance mask.\n\n class_id: int, default: GENERIC_OBJECT_CLASS\n Integer class ID (0 reserved for background).\n\n instance_id: in...
class RLEMask(): 'Container of RLE-encoded mask.\n\n See https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/mask.py for RLE format.\n\n Parameters\n ----------\n size: list[int] or np.ndarray[int]\n Height and width of mask.\n counts: list[int]\n Count-encoding o...
class KeyLine2D(): '2D keyline object.\n\n Parameters\n ----------\n line: np.ndarray[np.float32]\n Array of N*2 floats describing keyline coordinates [x, y].\n\n class_id: int, default: GENERIC_OBJECT_CLASS\n Integer class ID\n\n instance_id: int, default: None\n Unique instan...
class KeyLine3D(): '3D keyline object.\n\n Parameters\n ----------\n line: np.ndarray[np.float32]\n Array of (N,3) floats describing keyline coordinates [x, y, z].\n\n class_id: int, default: GENERIC_OBJECT_CLASS_ID\n Integer class ID\n\n instance_id: int, default: None\n Uniqu...
class KeyPoint2D(): '2D keypoint object.\n\n Parameters\n ----------\n point: np.ndarray[np.float32]\n Array of 2 floats describing keypoint coordinates [x, y].\n\n class_id: int, default: GENERIC_OBJECT_CLASS\n Integer class ID (0 reserved for background).\n\n instance_id: int, defau...
class KeyPoint3D(): '3D keypoint object.\n\n Parameters\n ----------\n point: np.ndarray[np.float32]\n Array of 3 floats describing keypoint coordinates [x, y, z].\n\n class_id: int, default: GENERIC_OBJECT_CLASS_ID\n Integer class ID (0 reserved for background).\n\n instance_id: int,...
def assert_between(value, low, high, low_inclusive=True, high_inclusive=True): '\n Assert ``value`` is inside the specified range.\n Parameters\n ----------\n value : comparable\n Value to be asserted.\n\n low : comparable\n Range lower bound.\n\n high : comparable\n Range u...
@lru_cache(maxsize=None) def meshgrid(B, H, W, dtype, device, normalized=False): 'Create mesh-grid given batch size, height and width dimensions.\n\n Parameters\n ----------\n B: int\n Batch size\n H: int\n Grid Height\n W: int\n Batch size\n dtype: torch.dtype\n Tens...
@lru_cache(maxsize=None) def image_grid(B, H, W, dtype, device, normalized=False): 'Create an image mesh grid with shape B3HW given image shape BHW\n\n Parameters\n ----------\n B: int\n Batch size\n H: int\n Grid Height\n W: int\n Batch size\n dtype: str\n Tensor dty...
def load_midas_net(name: str) -> tuple[(nn.Module, Compose)]: 'Load a frozen pre-trained Midas network from the PyTorch Hub.\n From: https://arxiv.org/abs/1907.01341 & https://arxiv.org/abs/2103.13413\n\n Pre-processing: ImageNet standarization & resizing (provided by `tfm`).\n Pre-processing: Bicubic re...
class NewCRFDepth(nn.Module): '\n Depth network based on neural window FC-CRFs architecture.\n ' def __init__(self, version=None, inv_depth=False, pretrained=None, frozen_stages=(- 1), min_depth=0.1, max_depth=100.0, **kwargs): super().__init__() self.inv_depth = inv_depth self....
class DispHead(nn.Module): def __init__(self, input_dim=100): super(DispHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, 1, 3, padding=1) self.sigmoid = nn.Sigmoid() def forward(self, x, scale): x = self.sigmoid(self.conv1(x)) if (scale > 1): x = u...
class DispUnpack(nn.Module): def __init__(self, input_dim=100, hidden_dim=128): super(DispUnpack, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 16, 3, padding=1) self.relu = nn.ReLU(inplace=True) self.sigmoi...
def upsample(x, scale_factor=2, mode='bilinear', align_corners=False): 'Upsample input tensor by a factor of 2\n ' return F.interpolate(x, scale_factor=scale_factor, mode=mode, align_corners=align_corners)
def resize(input, size=None, scale_factor=None, mode='nearest', align_corners=None, warning=True): if warning: if ((size is not None) and align_corners): (input_h, input_w) = tuple((int(x) for x in input.shape[2:])) (output_h, output_w) = tuple((int(x) for x in size)) i...
def normal_init(module, mean=0, std=1, bias=0): if (hasattr(module, 'weight') and (module.weight is not None)): nn.init.normal_(module.weight, mean, std) if (hasattr(module, 'bias') and (module.bias is not None)): nn.init.constant_(module.bias, bias)
def is_module_wrapper(module): module_wrappers = (DataParallel, DistributedDataParallel) return isinstance(module, module_wrappers)
def get_dist_info(): if (TORCH_VERSION < '1.0'): initialized = dist._initialized elif dist.is_available(): initialized = dist.is_initialized() else: initialized = False if initialized: rank = dist.get_rank() world_size = dist.get_world_size() else: r...
def load_state_dict(module, state_dict, strict=False, logger=None): "Load state_dict to a module.\n\n This method is modified from :meth:`torch.nn.Module.load_state_dict`.\n Default value for ``strict`` is set to ``False`` and the message for\n param mismatch will be shown even if strict is False.\n\n ...
def load_url_dist(url, model_dir=None): 'In distributed setting, this function only download checkpoint at local\n rank 0.' (rank, world_size) = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if (rank == 0): checkpoint = model_zoo.load_url(url, model_dir=model_dir) if (w...
def get_torchvision_models(): model_urls = dict() for (_, name, ispkg) in pkgutil.walk_packages(torchvision.models.__path__): if ispkg: continue _zoo = import_module(f'torchvision.models.{name}') if hasattr(_zoo, 'model_urls'): _urls = getattr(_zoo, 'model_urls'...
def _load_checkpoint(filename, map_location=None): 'Load checkpoint from somewhere (modelzoo, file, url).\n\n Args:\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for\n details.\n map_locatio...
def load_checkpoint(model, filename, map_location='cpu', strict=False, logger=None): 'Load checkpoint from a file or URI.\n\n Args:\n model (Module): Module to load checkpoint.\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ...
class PPM(nn.ModuleList): 'Pooling Pyramid Module used in PSPNet.\n\n Args:\n pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid\n Module.\n in_channels (int): Input channels.\n channels (int): Channels after modules, before conv_seg.\n conv_cfg (dict|None):...
class BaseDecodeHead(nn.Module): "Base class for BaseDecodeHead.\n\n Args:\n in_channels (int|Sequence[int]): Input channels.\n channels (int): Channels after modules, before conv_seg.\n num_classes (int): Number of classes.\n dropout_ratio (float): Ratio of dropout layer. Default: ...
class UPerHead(BaseDecodeHead): def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs): super(UPerHead, self).__init__(input_transform='multiple_select', **kwargs) self.lateral_convs = nn.ModuleList() self.fpn_convs = nn.ModuleList() for in_channels in self.in_channels: ...
class PSP(BaseDecodeHead): 'Unified Perceptual Parsing for Scene Understanding.\n\n This head is the implementation of `UPerNet\n <https://arxiv.org/abs/1807.10221>`_.\n\n Args:\n pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid\n Module applied on the last feature. Defa...
def load_newcrfs_net(scene: str, max_depth: Optional[float]=None) -> nn.Module: 'Load a frozen pre-trained NeWCRFs network.\n From https://arxiv.org/abs/2203.01502.\n\n Pre-processing: ImageNet standarization & resizing.\n\n Training shapes:\n - Outdoor: (Kitti) (352, 1216)\n - Indoor: (NYU...
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