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 source: str\n Directory from which we want to sync files\n\n target: str\n Directory to which all files will be synced\n\n file_ext: str, optional\n Only sync files ending with this extension. Eg: 'csv' or 'json'. If None, sync all files. Default: None.\n\n verbose: bool, optional\n If True, log some helpful messages. Default: True.\n\n Returns\n -------\n bool: True if operation was successful\n " if verbose: logging.getLogger().setLevel(logging.DEBUG) assert (source.startswith('s3://') or target.startswith('s3://')) additional_flags = '' if (file_ext is not None): additional_flags = f'--exclude=* --include=*{file_ext}' command_str = 'aws s3 sync --quiet --acl bucket-owner-full-control {} {} {}'.format(additional_flags, source, target) success = False logging.debug("Syncing with '{}'".format(command_str)) try: subprocess.check_output(command_str, shell=True) success = True except subprocess.CalledProcessError as e: success = False logging.error('{} failed with error code {}'.format(command_str, e.returncode)) logging.error(e.output) if verbose: logging.info('Done syncing') return success
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 of str\n Directories from which we want to sync files.\n\n target_paths: List of str\n Directories to which all files will be synced.\n\n threadpool_size: int\n Number of threads to use to fetch these files. If not specified, will default to\n number of cores on the machine.\n\n ' if (threadpool_size is None): threadpool_size = cpu_count() s3_and_destination = zip(source_paths, target_paths) with Pool(threadpool_size) as thread_pool: s3_sync_function = functools.partial(sync_dir) success_list = thread_pool.starmap(s3_sync_function, s3_and_destination) num_success = sum(success_list) logging.info(f'{num_success} / {len(success_list)} files copied successfully.') for (success, source, target) in zip(success_list, source_paths, target_paths): if (not success): assert sync_dir(source, target), f'Failed to copy {source} to {target} on 2nd try'
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 Parameters\n ----------\n source: str\n Directory from which we want to sync files\n\n target: str\n Directory to which all files will be synced\n\n verbose: bool, optional\n If True, log some helpful messages. Default: True.\n\n Returns\n -------\n files_fail_to_sync: list\n List of files fail to sync to S3 due to md5sum mismatch.\n ' assert ((not source.startswith('s3://')) and target.startswith('s3://')) (target_files, target_file_md5_sums) = s3_recursive_list(os.path.join(target, '')) rel_target_files = [os.path.relpath(_f, target) for _f in target_files] files_fail_to_sync = [] for (rel_target_file, target_file_md5_sum) in zip(rel_target_files, target_file_md5_sums): local_file = os.path.join(source, rel_target_file) if os.path.exists(local_file): local_file_md5_sum = hashlib.md5(open(local_file, 'rb').read()).hexdigest() if (local_file_md5_sum != target_file_md5_sum): files_fail_to_sync.append(rel_target_file) logging.error('Cannot sync to s3, you have made changes to "{}" locally'.format(rel_target_file)) sync_dir(source, target, verbose=verbose) if verbose: logging.info('{} | {} files synced to S3'.format((len(rel_target_files) - len(files_fail_to_sync)), len(rel_target_files))) return files_fail_to_sync
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:\n Wether or not the object exists in S3.\n ' return (len(list(s3_bucket(bucket_name).objects.filter(Prefix=url))) != 0)
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` before returning it\n (i.e. s3_path='<s3-prefix>' is returned for uri='s3://<s3-bucket>/<s3-prefix>/').\n Otherwise, we do not strip it\n (i.e. s3_path='<s3-prefix>' is returned for uri='s3://<s3-bucket>/<s3-prefix>/').\n\n If there is no trailing slash in `uri` then there will be no trailing slash in `s3_path` regardless\n of the value of this parameter.\n Default: True.\n\n Returns\n -------\n str:\n The bucket of the S3 object (e.g. '<s3-bucket>')\n\n str:\n The path within the bucket of the S3 object (e.g. '<s3-prefix>')\n " s3_uri = urlparse(uri) s3_path = s3_uri.path.lstrip('/') if strip_trailing_slash: s3_path = s3_path.rstrip('/') return (s3_uri.netloc, 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 download all files locally\n\n bucket_name: str\n S3 bucket to pull from\n\n process_pool_size: int, optional\n Number of threads to use to fetch these files. If not specified, will default to\n number of cores on the machine. Default: None.\n ' if (process_pool_size is None): process_pool_size = cpu_count() s3_and_destination = zip(s3_files, destination_filepaths) with Pool(process_pool_size, init_s3_client) as proc: results = proc.starmap(functools.partial(download_s3_object_to_path, bucket_name), s3_and_destination) failed_files = [os.path.join('s3://', bucket_name, s3_file) for (result, s3_file) in zip(results, s3_files) if (not result)] assert (len(failed_files) == 0), 'Failed downloading {}/{} files:\n{}'.format(len(failed_files), len(results), '\n'.join(failed_files))
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 bucket in S3 where files are uploaded.\n\n bucket_name: str\n S3 bucket to upload to.\n\n process_pool_size: int, optional\n Number of threads to use to fetch these files. If not specified, will default to\n number of cores on the machine. Default: None.\n ' if (process_pool_size is None): process_pool_size = cpu_count() s3_and_destination = zip(source_filepaths, s3_destinations) with Pool(process_pool_size, init_s3_client) as proc: proc.starmap(functools.partial(upload_file_to_s3, bucket_name), s3_and_destination)
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_path: str\n Path on the local filesystem to place the object.\n\n Returns\n -------\n bool\n True if successful, False if not.\n ' s3_client = init_s3_client() logging.debug('Downloading file {} => {}'.format(s3_path, local_path)) try: os.makedirs(os.path.dirname(local_path), exist_ok=True) except OSError: pass try: s3_client.download_file(bucket_name, s3_path, local_path) return True except botocore.exceptions.ClientError: logging.error('Traceback downloading {}:\n{}'.format(os.path.join('s3://', bucket_name, s3_path), traceback.format_exc())) return False
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. Default: True.\n\n ' s3_client = init_s3_client() if verbose: logging.warning('Deleting S3 Object {}'.format(os.path.join('s3://', bucket_name, object_key))) s3_client.delete_object(Bucket=bucket_name, Key=object_key)
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 bucket root\n\n Returns\n -------\n s3_url: str\n s3_url to which file was uploaded\n e.g. "s3://<s3-bucket>/<task-name>/<wandb-run>/<model-weights-file>"\n\n ' assert os.path.exists(local_file_path) s3_bucket(bucket_name).upload_file(local_file_path, bucket_rel_path) return os.path.join('s3://', bucket_name, bucket_rel_path)
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 Returns\n -------\n S3 object\n\n Raises\n ------\n ValueError\n Raised if `url` cannot be found in S3.\n ' result = list(s3_bucket(bucket_name).objects.filter(Prefix=url)) if (not result): raise ValueError(url, 'cannot be found!') return result[0]
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 to be fetched\n\n Returns\n -------\n A string representation of the remote file\n ' s3_obj = get_s3_object(bucket_name, url) return s3_obj.get()['Body'].read().decode('utf-8')
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_uri_to_bucket_path(s3_path) return json.loads(get_string_from_s3_file(bucket, rel_path))
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 The remote URL of the object to be fetched\n\n Returns\n -------\n bool\n ' self._artifact = artifact self._dirname = None url = artifact.url.value self._bucket = url.split('//')[(- 1)].split('/')[0] self._url = url self._relpath = url[((url.rfind(self._bucket) + len(self._bucket)) + 1):] self._s3_client = init_s3_client() _s3_bucket = boto3.session.Session().resource('s3').Bucket(self._bucket) assert exists_s3_object(_s3_bucket, self._relpath), 'Remote artifact does not exist {}'.format(self._url) def __enter__(self): self._dirname = tempfile.TemporaryDirectory() local_path = os.path.join(self._dirname.name, os.path.basename(self._relpath)) logging.info('Downloading {} to {}'.format(self._url, local_path)) self._s3_client.download_file(self._bucket, self._relpath, local_path) sha1 = hashlib.sha1(open(local_path, 'rb').read()).hexdigest() assert (sha1 == self._artifact.sha1), 'sha1sum inconsistent {} != {}'.format(sha1, self._artifact.sha1) return local_path def __exit__(self, *args): self._dirname.__exit__(*args)
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 str\n List of prefixes under `s3_path`\n ' s3_client = init_s3_client() assert s3_path.startswith('s3://') (bucket, path) = convert_uri_to_bucket_path(s3_path) prefixes = [] kwargs = {'Bucket': bucket, 'Prefix': os.path.join(path, ''), 'Delimiter': '/'} while True: response = s3_client.list_objects_v2(**kwargs) for obj in response['CommonPrefixes']: prefixes.append(os.path.basename(obj['Prefix'].rstrip('/'))) try: kwargs['ContinuationToken'] = response['NextContinuationToken'] except KeyError: break return prefixes
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_in_s3("s3://aa/bb/cc_v") returns [\'cc_v01.json\', \'cc_v02.json\', \'cc_v03.json\']\n Parameters\n ----------\n s3_prefix: str\n An S3 prefix.\n Returns\n -------\n prefixes: List of str\n List of basename prefixes that starts with `s3_prefix`.\n ' (bucket_name, prefix) = convert_uri_to_bucket_path(s3_prefix) bucket = s3_bucket(bucket_name) prefixes = [os.path.basename(obj.key) for obj in bucket.objects.filter(Prefix=prefix)] return 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 dictionary of split to a list of scene JSONs.\n\n split_to_scene_dir: dict\n A dictionary of split to a list of scene_dirs.\n ' split_to_scene_json = OrderedDict() split_to_scene_dir = OrderedDict() for (k, v) in dataset_pb2.DatasetSplit.DESCRIPTOR.values_by_number.items(): scene_jsons = dataset.scene_splits[k].filenames split_to_scene_json[v.name] = scene_jsons split_to_scene_dir[v.name] = [os.path.dirname(scene_json) for scene_json in scene_jsons] assert (len(set(split_to_scene_dir[v.name])) == len(split_to_scene_dir[v.name])) return (split_to_scene_json, split_to_scene_dir)
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 scene dataset JSON URI to load.\n\n pb_class: object\n Protobuf pb2 object we want to load into.\n\n Returns\n ----------\n pb_object: pb2 object\n Desired pb2 object to be opened.\n ' assert path.endswith('.json'), 'File extension for {} needs to be json.'.format(path) if path.startswith('s3://'): return open_remote_pb_object(path, pb_class) assert os.path.exists(path), f'Path not found: {path}' with open(path, 'r', encoding='UTF-8') as json_file: pb_object = Parse(json_file.read(), pb_class()) return pb_object
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 load into.\n\n Returns\n -------\n pb_object: pb2 object or None\n Desired pb2 ojbect to be parsed or None if loading fails\n ' if isinstance(source, str): return open_pbobject(source, pb_class) elif isinstance(source, bytes): pb_object = pb_class() pb_object.ParseFromString(source) return pb_object else: logging.error(f'cannot parse type {type(source)}')
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 pb_object: pb2 object\n Desired pb2 object to be opened.\n\n Raises\n ------\n ValueError\n Raised if s3_object_uri is not a valid S3 path.\n ' if s3_object_uri.startswith('s3://'): (bucket_name, s3_base_path) = convert_uri_to_bucket_path(s3_object_uri) else: raise ValueError('Expected path to S3 bucket but got {}'.format(s3_object_uri)) pb_object = Parse(get_string_from_s3_file(bucket_name, s3_base_path), pb_class()) return pb_object
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: object\n Protobuf pb2 object we want to save to file\n\n save_path: str\n If save path is a JSON, serialized object is saved to that path. If save path is directory,\n the `pb_object` is saved in <save_path>/<pb_object_sha>.json.\n\n Returns\n -------\n save_path: str\n Returns path to saved pb_object JSON\n ' if os.path.isdir(save_path): save_path = os.path.join(save_path, (generate_uid_from_pbobject(pb_object) + '.json')) assert save_path.endswith('.json'), 'File extension for {} needs to be json.'.format(save_path) with open(save_path, 'w', encoding='UTF-8') as _f: json.dump(MessageToDict(pb_object, including_default_value_fields=True, preserving_proto_field_name=True), _f, indent=2, sort_keys=True) return save_path
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 Ontology pb2 object to be opened (either V2 or V1). Returns\n None if neither fails to load.\n ' try: ontology = parse_pbobject(ontology_file, OntologyV2Pb2) if (ontology is not None): logging.info('Successfully loaded Ontology V2 spec.') return ontology except Exception: logging.error('Failed to load ontology file with V2 spec, trying V1 spec.') try: ontology = parse_pbobject(ontology_file, OntologyV1Pb2) if (ontology is not None): logging.info('Successfully loaded Ontology V1 spec.') return ontology except Exception: if isinstance(ontology_file, str): logging.error((('Failed to load ontology file' + ontology_file) + 'with V1 spec also, returning None.')) else: logging.error('Failed to load ontology file with V1 spec also, returning None.')
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. Returns\n None if neither fails to load.\n ' try: ontology = open_pbobject(ontology_file, FeatureOntologyPb2) if (ontology is not None): logging.info('Successfully loaded FeatureOntology spec.') return ontology except Exception: logging.error((('Failed to load ontology file' + ontology_file) + '.'))
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 ' json_string = json.dumps(MessageToDict(pb_object, including_default_value_fields=True, preserving_proto_field_name=True), indent=2, sort_keys=True) out = StringIO() out.write(json_string) uid = hashlib.sha1(out.getvalue().encode('utf-8')).hexdigest() out.close() return uid
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\n -------\n latest_scene: dgp.proto.scene_pb2.Scene\n Scene pb object with the latest creation timestamp.\n scene_json_path: str\n S3 Path to the latest scene JSON.\n Notes\n -----\n This function can be called on the output:\n out, _ = s3_recursive_list(os.path.join(scene_s3_dir, 'scene')\n which is grabbing all 'scene*' files from the Scene directory\n " scenes = [open_remote_pb_object(scene_json, Scene) for scene_json in s3_scene_jsons] creation_ts = [_s.creation_date.ToMicroseconds() for _s in scenes] index = creation_ts.index(max(creation_ts)) return (scenes[index], s3_scene_jsons[index])
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 --------\n scene_stats: OrderedDict\n num_samples: int\n Number of samples in the Scene\n num_images: int\n Number of image datums in the Scene.\n num_point_clouds: int\n Number of point_cloud datums in the Scene.\n <datum_type>_<annotation_type>: int\n Number of <datum_type> with associated <annotation_type> annotation files.\n ' num_samples = len(scene.samples) (num_images, num_point_clouds) = (0, 0) annotation_counts = defaultdict(int) datum_index = {datum.key: idx for (idx, datum) in enumerate(scene.data)} for sample in scene.samples: for datum_key in sample.datum_keys: datum = scene.data[datum_index[datum_key]] if datum.datum.HasField('image'): num_images += 1 elif datum.datum.HasField('point_cloud'): num_point_clouds += 1 else: continue datum_type = datum.datum.WhichOneof('datum_oneof') datum_value = getattr(datum.datum, datum_type) annotations = datum_value.annotations for key in annotations: name = annotations_pb2.AnnotationType.DESCRIPTOR.values_by_number[key].name annotation_counts['{}_{}'.format(datum_type.upper(), name)] += 1 if verbose: print(('-' * 80)) sample_info = 'Samples: {},\t Images: {},\t Point Clouds: {}\n\t'.format(num_samples, num_images, num_point_clouds) sample_info += ', '.join(['{}: {}'.format(k, v) for (k, v) in annotation_counts.items()]) print(('Scene: {}\n\t'.format(scene.name) + sample_info)) return OrderedDict({'num_samples': num_samples, 'num_images': num_images, 'num_point_clouds': num_point_clouds, **annotation_counts})
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]\n The datum type, and annotation class corresponding to the annotation enum\n\n Raises\n ------\n Exception\n Raised if annotation_enum value does not map to a supported box type.\n ' if (annotation_enum == annotations_pb2.BOUNDING_BOX_3D): return ('point_cloud', annotations_pb2.BoundingBox3DAnnotations) elif (annotation_enum == annotations_pb2.BOUNDING_BOX_2D): return ('image', annotations_pb2.BoundingBox2DAnnotations) else: raise Exception('Annotation info not supported')
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.\n\n annotation_enum: dgp.proto.ontology_pb2.AnnotationType\n Annotation type enum\n\n ontology: dgp.proto.ontology_pb2.Ontology or None\n Stats will be computed for this ontology. If None, the ontology will be read from the scene.\n\n Returns\n --------\n scene_stats: OrderedDict\n class_name: int\n Counts of annotations for each class.\n ' (datum_type, annotation_pb) = _get_bounding_box_annotation_info(annotation_enum) if (ontology is not None): class_counts = OrderedDict({item.name: 0 for item in ontology.items}) id_name_map = {item.id: item.name for item in ontology.items} ontology_sha = generate_uid_from_pbobject(ontology) assert (annotation_enum in scene.ontologies), 'Given annotation_enum not in scene.ontologies!' assert (scene.ontologies[annotation_enum] == ontology_sha), 'Input ontology does not match Scene ontology!' else: ontology_path = os.path.join(scene_dir, ONTOLOGY_FOLDER, (scene.ontologies[annotation_enum] + '.json')) ontology = Ontology(open_ontology_pbobject(ontology_path)) id_name_map = ontology.id_to_name class_counts = OrderedDict({name: 0 for name in ontology.name_to_id}) for datum in scene.data: if (not (datum.datum.WhichOneof('datum_oneof') == datum_type)): continue datum_value = getattr(datum.datum, datum_type) annotations = datum_value.annotations if (annotation_enum not in annotations): continue annotation_path = os.path.join(scene_dir, annotations[annotation_enum]) if annotation_path.startswith('s3://'): annotation_object = open_remote_pb_object(annotation_path, annotation_pb) else: annotation_object = open_pbobject(annotation_path, annotation_pb) for annotation in annotation_object.annotations: class_counts[id_name_map[annotation.class_id]] += 1 return class_counts
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 for background).\n\n instance_id: int, default: None\n Unique instance ID for bounding box. If None provided, the ID is a hash of the bounding box\n location and class.\n\n color: tuple, default: (0, 0, 0)\n RGB tuple for bounding box color\n\n attributes: dict, default: None\n Dictionary of attributes associated with bounding box. If None provided,\n defaults to empty dict.\n\n mode: str, default: ltwh\n One of "ltwh" or "ltrb". Corresponds to "[left, top, width, height]" representation\n or "[left, top, right, bottom]"\n\n Raises\n ------\n Exception\n Raised if the value of mode is unsupported.\n ' def __init__(self, box, class_id=GENERIC_OBJECT_CLASS, instance_id=None, color=(0, 0, 0), attributes=None, mode='ltwh'): assert (box.dtype in (np.float32, np.float64)) assert (box.shape[0] == 4) assert (class_id != 0), '0 is reserved for background, your class must have a different ID' self._box = box self.l = box[0] self.t = box[1] if (mode == 'ltwh'): self.w = box[2] self.h = box[3] elif (mode == 'ltrb'): self.w = (box[2] - box[0]) self.h = (box[3] - box[1]) else: raise Exception(f"Bounding box must be initialized as 'ltrb' or 'ltwh', cannot recognize {mode}") self._class_id = class_id self._instance_id = instance_id self._color = color self._attributes = (dict(attributes) if (attributes is not None) else {}) def intersection_over_union(self, other): 'Compute intersection over union of this box against other(s).\n\n Parameters\n ----------\n other: BoundingBox2D\n A separate BoundingBox2D instance to compute IoU against.\n\n Raises\n ------\n NotImplementedError\n Unconditionally\n ' raise NotImplementedError @property def ltrb(self): return np.array([self.l, self.t, (self.l + self.w), (self.t + self.h)], dtype=np.float32) @property def ltwh(self): return np.array([self.l, self.t, self.w, self.h], dtype=np.float32) @property def class_id(self): return self._class_id @class_id.setter def class_id(self, class_id): self._class_id = class_id @property def instance_id(self): if (self._instance_id is None): return self.hexdigest return self._instance_id @property def area(self): return (self.w * self.h) @property def color(self): return self._color @property def attributes(self): return self._attributes @property def hexdigest(self): return hashlib.md5((self.ltrb.tobytes() + bytes(self._class_id))).hexdigest() def __repr__(self): return '{}[{}, Class: {}, Attributes: {}]'.format(self.__class__.__name__, list(self.ltrb), self.class_id, self.attributes) def __eq__(self, other): return (self.hexdigest == other.hexdigest) def render(self, image): 'Render bounding boxes on an image.\n\n Parameters\n ----------\n image: PIL.Image or np.ndarray\n Background image on which boxes are rendered\n\n Returns\n -------\n image: PIL.Image or np.ndarray\n Image with boxes rendered\n ' raise NotImplementedError def to_proto(self): 'Serialize bounding box to proto object.\n\n NOTE: Does not serialize class or instance information, just box geometry.\n To serialize a complete annotation, see `dgp/annotations/bounding_box_2d_annotation.py`\n\n Returns\n -------\n BoundingBox2D.pb2\n As defined in `proto/annotations.proto`\n ' return annotations_pb2.BoundingBox2D(x=int(self.l), y=int(self.t), w=int(self.w), h=int(self.h))
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: int, default: None\n Unique instance ID for instance mask. If None provided, the ID is a hash of the instance mask,\n location and class.\n\n attributes: dict, default: None\n Dictionary of attributes associated with instance mask. If None provided,\n defaults to empty dict.\n ' def __init__(self, mask, class_id=GENERIC_OBJECT_CLASS, instance_id=None, color=(0, 0, 0), attributes=None): assert (mask.dtype in (bool, np.uint8, np.int64)) self._bitmask = mask self._class_id = class_id self._instance_id = instance_id self._color = color self._attributes = (dict(attributes) if (attributes is not None) else {}) def intersection_over_union(self, other): 'Compute intersection over union of this box against other(s).\n\n Parameters\n ----------\n other: InstanceMask2D\n Another instance of InstanceMask2D to compute IoU against.\n\n Raises\n ------\n NotImplementedError\n Unconditionally.\n ' raise NotImplementedError @property def bitmask(self): return self._bitmask @property def class_id(self): return self._class_id @class_id.setter def class_id(self, class_id): self._class_id = class_id @property def color(self): return self._color @property def instance_id(self): if (self._instance_id is None): return self.hexdigest return self._instance_id @property def area(self): 'Compute intersection over union of this box against other(s).' return np.sum(self.bitmask) @property def attributes(self): return self._attributes @property def hexdigest(self): return hashlib.md5(((self.bitmask.tobytes() + bytes(self._class_id)) + bytes(self._instance_id))).hexdigest() def __repr__(self): return '{}[Class: {}, Attributes: {}]'.format(self.__class__.__name__, self.class_id, self.attributes) def __eq__(self, other): return (self.hexdigest == other.hexdigest) def render(self, image): 'Render instance masks on an image.\n\n Parameters\n ----------\n image: PIL.Image or np.ndarray\n Background image on which boxes are rendered\n\n Returns\n -------\n image: PIL.Image or np.ndarray\n Image with boxes rendered\n ' raise NotImplementedError @property def rle(self): _rle = mask_util.encode(np.array(self.bitmask, np.uint8, order='F')) return RLEMask(_rle['size'], _rle['counts'])
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 of RLE format.\n ' def __init__(self, size, counts): self.size = size self.counts = counts def to_dict(self): return OrderedDict([('size', self.size), ('counts', self.counts)])
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 instance ID for keyline. If None provided, the ID is a hash of the keyline\n location and class.\n\n color: tuple, default: (0, 0, 0)\n RGB tuple for keyline color\n\n attributes: dict, default: None\n Dictionary of attributes associated with keyline. If None provided,\n defaults to empty dict.\n\n ' def __init__(self, line, class_id=GENERIC_OBJECT_CLASS, instance_id=None, color=(0, 0, 0), attributes=None): assert (line.dtype in (np.float32, np.float64)) assert (line.shape[1] == 2) self._point = line self.x = [] self.y = [] for point in line: self.x.append(point[0]) self.y.append(point[1]) self._class_id = class_id self._instance_id = instance_id self._color = color self._attributes = (dict(attributes) if (attributes is not None) else {}) @property def xy(self): return np.array([self.x, self.y], dtype=np.float32) @property def class_id(self): return self._class_id @property def instance_id(self): if (self._instance_id is None): return self.hexdigest return self._instance_id @property def color(self): return self._color @property def attributes(self): return self._attributes @property def hexdigest(self): return hashlib.md5((self.xy.tobytes() + bytes(self._class_id))).hexdigest() def __repr__(self): return '{}[{}, Class: {}, Attributes: {}]'.format(self.__class__.__name__, list(self.xy), self.class_id, self.attributes) def __eq__(self, other): return (self.hexdigest == other.hexdigest) def to_proto(self): 'Serialize keyline to proto object.\n\n NOTE: Does not serialize class or instance information, just line geometry.\n To serialize a complete annotation, see `dgp/annotations/key_line_2d_annotation.py`\n\n Returns\n -------\n KeyLine2D.pb2\n As defined in `proto/annotations.proto`\n ' return [annotations_pb2.KeyPoint2D(x=int(self.x[j]), y=int(self.y[j])) for (j, k) in enumerate(self.x)]
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 Unique instance ID for keyline. If None provided, the ID is a hash of the keyline\n location and class.\n\n color: tuple, default: (0, 0, 0)\n RGB tuple for keyline color\n\n attributes: dict, default: None\n Dictionary of attributes associated with keyline. If None provided,\n defaults to empty dict.\n\n ' def __init__(self, line, class_id=GENERIC_OBJECT_CLASS_ID, instance_id=None, color=(0, 0, 0), attributes=None): assert (line.dtype in (np.float32, np.float64)) assert (line.shape[1] == 3) self._point = line self.x = [] self.y = [] self.z = [] for point in line: self.x.append(point[0]) self.y.append(point[1]) self.z.append(point[2]) self._class_id = class_id self._instance_id = instance_id self._color = color self._attributes = (dict(attributes) if (attributes is not None) else {}) @property def xyz(self): return np.array([self.x, self.y, self.z], dtype=np.float32) @property def class_id(self): return self._class_id @property def instance_id(self): if (self._instance_id is None): return self.hexdigest return self._instance_id @property def color(self): return self._color @property def attributes(self): return self._attributes @property def hexdigest(self): return hashlib.md5((self.xyz.tobytes() + bytes(self._class_id))).hexdigest() def __repr__(self): return '{}[{}, Class: {}, Attributes: {}]'.format(self.__class__.__name__, list(self.xyz), self.class_id, self.attributes) def __eq__(self, other): return (self.hexdigest == other.hexdigest) def to_proto(self): 'Serialize keyline to proto object.\n\n Does not serialize class or instance information, just line geometry.\n To serialize a complete annotation, see `dgp/annotations/key_line_3d_annotation.py`\n\n Returns\n -------\n KeyLine3D.pb2\n As defined in `proto/annotations.proto`\n ' return [annotations_pb2.KeyPoint3D(x=int(self.x[j]), y=int(self.y[j]), z=int(self.z[j])) for (j, _) in enumerate(self.x)]
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, default: None\n Unique instance ID for keypoint. If None provided, the ID is a hash of the keypoint\n location and class.\n\n color: tuple, default: (0, 0, 0)\n RGB tuple for keypoint color\n\n attributes: dict, default: None\n Dictionary of attributes associated with keypoint. If None provided,\n defaults to empty dict.\n\n ' def __init__(self, point, class_id=GENERIC_OBJECT_CLASS, instance_id=None, color=(0, 0, 0), attributes=None): assert (point.dtype in (np.float32, np.float64)) assert (point.shape[0] == 2) assert (class_id != 0), '0 is reserved for background, your class must have a different ID' self._point = point self.x = point[0] self.y = point[1] self._class_id = class_id self._instance_id = instance_id self._color = color self._attributes = (dict(attributes) if (attributes is not None) else {}) @property def xy(self): return np.array([self.x, self.y], dtype=np.float32) @property def class_id(self): return self._class_id @property def instance_id(self): if (self._instance_id is None): return self.hexdigest return self._instance_id @property def color(self): return self._color @property def attributes(self): return self._attributes @property def hexdigest(self): return hashlib.md5((self.xy.tobytes() + bytes(self._class_id))).hexdigest() def __repr__(self): return '{}[{}, Class: {}, Attributes: {}]'.format(self.__class__.__name__, list(self.xy), self.class_id, self.attributes) def __eq__(self, other): return (self.hexdigest == other.hexdigest) def to_proto(self): 'Serialize keypoint to proto object.\n\n NOTE: Does not serialize class or instance information, just point geometry.\n To serialize a complete annotation, see `dgp/annotations/key_point_2d_annotation.py`\n\n Returns\n -------\n KeyPoint2D.pb2\n As defined in `proto/annotations.proto`\n ' return annotations_pb2.KeyPoint2D(x=int(self.x), y=int(self.y))
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, default: None\n Unique instance ID for keypoint. If None provided, the ID is a hash of the keypoint\n location and class.\n\n color: tuple, default: (0, 0, 0)\n RGB tuple for keypoint color\n\n attributes: dict, default: None\n Dictionary of attributes associated with keypoint. If None provided,\n defaults to empty dict.\n\n ' def __init__(self, point, class_id=GENERIC_OBJECT_CLASS_ID, instance_id=None, color=(0, 0, 0), attributes=None): assert (point.dtype in (np.float32, np.float64)) assert (point.shape[0] == 3) self._point = point self.x = point[0] self.y = point[1] self.z = point[2] self._class_id = class_id self._instance_id = instance_id self._color = color self._attributes = (dict(attributes) if (attributes is not None) else {}) @property def xyz(self): return np.array([self.x, self.y, self.z], dtype=np.float32) @property def class_id(self): return self._class_id @property def instance_id(self): if (self._instance_id is None): return self.hexdigest return self._instance_id @property def color(self): return self._color @property def attributes(self): return self._attributes @property def hexdigest(self): return hashlib.md5((self.xyz.tobytes() + bytes(self._class_id))).hexdigest() def __repr__(self): return '{}[{}, Class: {}, Attributes: {}]'.format(self.__class__.__name__, list(self.xyz), self.class_id, self.attributes) def __eq__(self, other): return (self.hexdigest == other.hexdigest) def to_proto(self): 'Serialize keypoint to proto object.\n\n Does not serialize class or instance information, just point geometry.\n To serialize a complete annotation, see `dgp/annotations/key_point_3d_annotation.py`\n\n Returns\n -------\n KeyPoint3D.pb2\n As defined in `proto/annotations.proto`\n ' return annotations_pb2.KeyPoint3D(x=int(self.x), y=int(self.y), z=int(self.z))
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 upper bound.\n\n low_inclusive : bool, optional\n Allow case when value == low. Default: True.\n\n high_inclusive : bool, optional\n Allow case when value == high. Default: True.\n ' if low_inclusive: assert_greater_equal(value, low) else: assert_greater(value, low) if high_inclusive: assert_less_equal(value, high) else: assert_less(value, high)
@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 Tensor dtype\n device: str\n Tensor device\n normalized: bool\n Normalized image coordinates or integer-grid.\n\n Returns\n -------\n xs: torch.Tensor\n Batched mesh-grid x-coordinates (BHW).\n ys: torch.Tensor\n Batched mesh-grid y-coordinates (BHW).\n ' if normalized: xs = torch.linspace((- 1), 1, W, device=device, dtype=dtype) ys = torch.linspace((- 1), 1, H, device=device, dtype=dtype) else: xs = torch.linspace(0, (W - 1), W, device=device, dtype=dtype) ys = torch.linspace(0, (H - 1), H, device=device, dtype=dtype) (ys, xs) = torch.meshgrid([ys, xs]) return (xs.repeat([B, 1, 1]), ys.repeat([B, 1, 1]))
@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 dtype\n device: str\n Tensor device\n normalized: bool\n Normalized image coordinates or integer-grid.\n\n Returns\n -------\n grid: torch.Tensor\n Mesh-grid for the corresponding image shape (B3HW)\n ' (xs, ys) = meshgrid(B, H, W, dtype, device, normalized=normalized) ones = torch.ones_like(xs) grid = torch.stack([xs, ys, ones], dim=1) return grid
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 resizing.\n\n Training shapes: Images are resized such that the height/width are 384 or 512 and aspect ratio is retained.\n See https://github.com/isl-org/MiDaS/blob/1645b7e1675301fdfac03640738fe5a6531e17d6/midas/transforms.py#L48 for\n additional details\n\n Prediction:\n ```\n # Prediction is made in scaleless disparity.\n img: np.array (unit8)\n pred = net(tfm(img))\n ```\n\n :param name: (str) Model configuration to load.\n :return: (nn.Module, Any) Loaded model & pre-processing transforms.\n ' net = torch.hub.load('intel-isl/MiDaS', name).eval() for p in net.parameters(): p.requires_grad = False tfms = torch.hub.load('intel-isl/MiDaS', 'transforms') if ('DPT' in name): tfm = tfms.dpt_transform elif ('BEiT' in name): tfm = tfms.beit512_transform elif (name == 'MiDaS_small'): tfm = tfms.small_transform else: tfm = tfms.default_transform return (net, tfm)
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.with_auxiliary_head = False self.with_neck = False norm_cfg = dict(type='BN', requires_grad=True) window_size = int(version[(- 2):]) if (version[:(- 2)] == 'base'): embed_dim = 128 depths = [2, 2, 18, 2] num_heads = [4, 8, 16, 32] in_channels = [128, 256, 512, 1024] elif (version[:(- 2)] == 'large'): embed_dim = 192 depths = [2, 2, 18, 2] num_heads = [6, 12, 24, 48] in_channels = [192, 384, 768, 1536] elif (version[:(- 2)] == 'tiny'): embed_dim = 96 depths = [2, 2, 6, 2] num_heads = [3, 6, 12, 24] in_channels = [96, 192, 384, 768] backbone_cfg = dict(embed_dim=embed_dim, depths=depths, num_heads=num_heads, window_size=window_size, ape=False, drop_path_rate=0.3, patch_norm=True, use_checkpoint=False, frozen_stages=frozen_stages) embed_dim = 512 decoder_cfg = dict(in_channels=in_channels, in_index=[0, 1, 2, 3], pool_scales=(1, 2, 3, 6), channels=embed_dim, dropout_ratio=0.0, num_classes=32, norm_cfg=norm_cfg, align_corners=False) self.backbone = SwinTransformer(**backbone_cfg) v_dim = (decoder_cfg['num_classes'] * 4) win = 7 crf_dims = [128, 256, 512, 1024] v_dims = [64, 128, 256, embed_dim] self.crf3 = NewCRF(input_dim=in_channels[3], embed_dim=crf_dims[3], window_size=win, v_dim=v_dims[3], num_heads=32) self.crf2 = NewCRF(input_dim=in_channels[2], embed_dim=crf_dims[2], window_size=win, v_dim=v_dims[2], num_heads=16) self.crf1 = NewCRF(input_dim=in_channels[1], embed_dim=crf_dims[1], window_size=win, v_dim=v_dims[1], num_heads=8) self.crf0 = NewCRF(input_dim=in_channels[0], embed_dim=crf_dims[0], window_size=win, v_dim=v_dims[0], num_heads=4) self.decoder = PSP(**decoder_cfg) self.disp_head1 = DispHead(input_dim=crf_dims[0]) self.up_mode = 'bilinear' if (self.up_mode == 'mask'): self.mask_head = nn.Sequential(nn.Conv2d(crf_dims[0], 64, 3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(64, (16 * 9), 1, padding=0)) self.min_depth = min_depth self.max_depth = max_depth self.init_weights(pretrained=pretrained) def init_weights(self, pretrained=None): 'Initialize the weights in backbone and heads.\n\n Args:\n pretrained (str, optional): Path to pre-trained weights.\n Defaults to None.\n ' print(f'== Load encoder backbone from: {pretrained}') self.backbone.init_weights(pretrained=pretrained) self.decoder.init_weights() if self.with_auxiliary_head: if isinstance(self.auxiliary_head, nn.ModuleList): for aux_head in self.auxiliary_head: aux_head.init_weights() else: self.auxiliary_head.init_weights() def upsample_mask(self, disp, mask): ' Upsample disp [H/4, W/4, 1] -> [H, W, 1] using convex combination ' (N, _, H, W) = disp.shape mask = mask.view(N, 1, 9, 4, 4, H, W) mask = torch.softmax(mask, dim=2) up_disp = F.unfold(disp, kernel_size=3, padding=1) up_disp = up_disp.view(N, 1, 9, 1, 1, H, W) up_disp = torch.sum((mask * up_disp), dim=2) up_disp = up_disp.permute(0, 1, 4, 2, 5, 3) return up_disp.reshape(N, 1, (4 * H), (4 * W)) def forward(self, imgs): feats = self.backbone(imgs) if self.with_neck: feats = self.neck(feats) ppm_out = self.decoder(feats) e3 = self.crf3(feats[3], ppm_out) e3 = nn.PixelShuffle(2)(e3) e2 = self.crf2(feats[2], e3) e2 = nn.PixelShuffle(2)(e2) e1 = self.crf1(feats[1], e2) e1 = nn.PixelShuffle(2)(e1) e0 = self.crf0(feats[0], e1) if (self.up_mode == 'mask'): mask = self.mask_head(e0) d1 = self.disp_head1(e0, 1) d1 = self.upsample_mask(d1, mask) else: d1 = self.disp_head1(e0, 4) depth = (d1 * self.max_depth) return depth
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 = upsample(x, scale_factor=scale) return x
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.sigmoid = nn.Sigmoid() self.pixel_shuffle = nn.PixelShuffle(4) def forward(self, x, output_size): x = self.relu(self.conv1(x)) x = self.sigmoid(self.conv2(x)) x = self.pixel_shuffle(x) return x
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)) if ((output_h > input_h) or (output_w > output_h)): if (((output_h > 1) and (output_w > 1) and (input_h > 1) and (input_w > 1)) and ((output_h - 1) % (input_h - 1)) and ((output_w - 1) % (input_w - 1))): warnings.warn(f'When align_corners={align_corners}, the output would more aligned if input size {(input_h, input_w)} is `x+1` and out size {(output_h, output_w)} is `nx+1`') if isinstance(size, torch.Size): size = tuple((int(x) for x in size)) return F.interpolate(input, size, scale_factor, mode, align_corners)
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: rank = 0 world_size = 1 return (rank, world_size)
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 Args:\n module (Module): Module that receives the state_dict.\n state_dict (OrderedDict): Weights.\n strict (bool): whether to strictly enforce that the keys\n in :attr:`state_dict` match the keys returned by this module's\n :meth:`~torch.nn.Module.state_dict` function. Default: ``False``.\n logger (:obj:`logging.Logger`, optional): Logger to log the error\n message. If not specified, print function will be used.\n " unexpected_keys = [] all_missing_keys = [] err_msg = [] metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.copy() if (metadata is not None): state_dict._metadata = metadata def load(module, prefix=''): if is_module_wrapper(module): module = module.module local_metadata = ({} if (metadata is None) else metadata.get(prefix[:(- 1)], {})) module._load_from_state_dict(state_dict, prefix, local_metadata, True, all_missing_keys, unexpected_keys, err_msg) for (name, child) in module._modules.items(): if (child is not None): load(child, ((prefix + name) + '.')) load(module) load = None missing_keys = [key for key in all_missing_keys if ('num_batches_tracked' not in key)] if unexpected_keys: err_msg.append(f'''unexpected key in source state_dict: {', '.join(unexpected_keys)} ''') if missing_keys: err_msg.append(f'''missing keys in source state_dict: {', '.join(missing_keys)} ''') (rank, _) = get_dist_info() if ((len(err_msg) > 0) and (rank == 0)): err_msg.insert(0, 'The model and loaded state dict do not match exactly\n') err_msg = '\n'.join(err_msg) if strict: raise RuntimeError(err_msg) elif (logger is not None): logger.warning(err_msg) else: print(err_msg)
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 (world_size > 1): torch.distributed.barrier() if (rank > 0): checkpoint = model_zoo.load_url(url, model_dir=model_dir) return checkpoint
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') model_urls.update(_urls) return 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_location (str | None): Same as :func:`torch.load`. Default: None.\n\n Returns:\n dict | OrderedDict: The loaded checkpoint. It can be either an\n OrderedDict storing model weights or a dict containing other\n information, which depends on the checkpoint.\n ' if filename.startswith('modelzoo://'): warnings.warn('The URL scheme of "modelzoo://" is deprecated, please use "torchvision://" instead') model_urls = get_torchvision_models() model_name = filename[11:] checkpoint = load_url_dist(model_urls[model_name]) else: if (not osp.isfile(filename)): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) return checkpoint
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 ``docs/model_zoo.md`` for\n details.\n map_location (str): Same as :func:`torch.load`.\n strict (bool): Whether to allow different params for the model and\n checkpoint.\n logger (:mod:`logging.Logger` or None): The logger for error message.\n\n Returns:\n dict or OrderedDict: The loaded checkpoint.\n ' checkpoint = _load_checkpoint(filename, map_location) if (not isinstance(checkpoint, dict)): raise RuntimeError(f'No state_dict found in checkpoint file {filename}') if ('state_dict' in checkpoint): state_dict = checkpoint['state_dict'] elif ('model' in checkpoint): state_dict = checkpoint['model'] else: state_dict = checkpoint if list(state_dict.keys())[0].startswith('module.'): state_dict = {k[7:]: v for (k, v) in state_dict.items()} if sorted(list(state_dict.keys()))[0].startswith('encoder'): state_dict = {k.replace('encoder.', ''): v for (k, v) in state_dict.items() if k.startswith('encoder.')} if (state_dict.get('absolute_pos_embed') is not None): absolute_pos_embed = state_dict['absolute_pos_embed'] (N1, L, C1) = absolute_pos_embed.size() (N2, C2, H, W) = model.absolute_pos_embed.size() if ((N1 != N2) or (C1 != C2) or (L != (H * W))): logger.warning('Error in loading absolute_pos_embed, pass') else: state_dict['absolute_pos_embed'] = absolute_pos_embed.view(N2, H, W, C2).permute(0, 3, 1, 2) relative_position_bias_table_keys = [k for k in state_dict.keys() if ('relative_position_bias_table' in k)] for table_key in relative_position_bias_table_keys: table_pretrained = state_dict[table_key] table_current = model.state_dict()[table_key] (L1, nH1) = table_pretrained.size() (L2, nH2) = table_current.size() if (nH1 != nH2): logger.warning(f'Error in loading {table_key}, pass') elif (L1 != L2): S1 = int((L1 ** 0.5)) S2 = int((L2 ** 0.5)) table_pretrained_resized = F.interpolate(table_pretrained.permute(1, 0).view(1, nH1, S1, S1), size=(S2, S2), mode='bicubic') state_dict[table_key] = table_pretrained_resized.view(nH2, L2).permute(1, 0) load_state_dict(model, state_dict, strict, logger) return checkpoint
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): Config of conv layers.\n norm_cfg (dict|None): Config of norm layers.\n act_cfg (dict): Config of activation layers.\n align_corners (bool): align_corners argument of F.interpolate.\n ' def __init__(self, pool_scales, in_channels, channels, conv_cfg, norm_cfg, act_cfg, align_corners): super(PPM, self).__init__() self.pool_scales = pool_scales self.align_corners = align_corners self.in_channels = in_channels self.channels = channels self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.act_cfg = act_cfg for pool_scale in pool_scales: if (pool_scale == 1): norm_cfg = dict(type='GN', requires_grad=True, num_groups=256) self.append(nn.Sequential(nn.AdaptiveAvgPool2d(pool_scale), ConvModule(self.in_channels, self.channels, 1, conv_cfg=self.conv_cfg, norm_cfg=norm_cfg, act_cfg=self.act_cfg))) def forward(self, x): 'Forward function.' ppm_outs = [] for ppm in self: ppm_out = ppm(x) upsampled_ppm_out = resize(ppm_out, size=x.size()[2:], mode='bilinear', align_corners=self.align_corners) ppm_outs.append(upsampled_ppm_out) return ppm_outs
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: 0.1.\n conv_cfg (dict|None): Config of conv layers. Default: None.\n norm_cfg (dict|None): Config of norm layers. Default: None.\n act_cfg (dict): Config of activation layers.\n Default: dict(type='ReLU')\n in_index (int|Sequence[int]): Input feature index. Default: -1\n input_transform (str|None): Transformation type of input features.\n Options: 'resize_concat', 'multiple_select', None.\n 'resize_concat': Multiple feature maps will be resize to the\n same size as first one and than concat together.\n Usually used in FCN head of HRNet.\n 'multiple_select': Multiple feature maps will be bundle into\n a list and passed into decode head.\n None: Only one select feature map is allowed.\n Default: None.\n loss_decode (dict): Config of decode loss.\n Default: dict(type='CrossEntropyLoss').\n ignore_index (int | None): The label index to be ignored. When using\n masked BCE loss, ignore_index should be set to None. Default: 255\n sampler (dict|None): The config of segmentation map sampler.\n Default: None.\n align_corners (bool): align_corners argument of F.interpolate.\n Default: False.\n " def __init__(self, in_channels, channels, *, num_classes, dropout_ratio=0.1, conv_cfg=None, norm_cfg=None, act_cfg=dict(type='ReLU'), in_index=(- 1), input_transform=None, loss_decode=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), ignore_index=255, sampler=None, align_corners=False): super(BaseDecodeHead, self).__init__() self._init_inputs(in_channels, in_index, input_transform) self.channels = channels self.num_classes = num_classes self.dropout_ratio = dropout_ratio self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.act_cfg = act_cfg self.in_index = in_index self.ignore_index = ignore_index self.align_corners = align_corners if (dropout_ratio > 0): self.dropout = nn.Dropout2d(dropout_ratio) else: self.dropout = None self.fp16_enabled = False def extra_repr(self): 'Extra repr.' s = f'input_transform={self.input_transform}, ignore_index={self.ignore_index}, align_corners={self.align_corners}' return s def _init_inputs(self, in_channels, in_index, input_transform): "Check and initialize input transforms.\n\n The in_channels, in_index and input_transform must match.\n Specifically, when input_transform is None, only single feature map\n will be selected. So in_channels and in_index must be of type int.\n When input_transform\n\n Args:\n in_channels (int|Sequence[int]): Input channels.\n in_index (int|Sequence[int]): Input feature index.\n input_transform (str|None): Transformation type of input features.\n Options: 'resize_concat', 'multiple_select', None.\n 'resize_concat': Multiple feature maps will be resize to the\n same size as first one and than concat together.\n Usually used in FCN head of HRNet.\n 'multiple_select': Multiple feature maps will be bundle into\n a list and passed into decode head.\n None: Only one select feature map is allowed.\n " if (input_transform is not None): assert (input_transform in ['resize_concat', 'multiple_select']) self.input_transform = input_transform self.in_index = in_index if (input_transform is not None): assert isinstance(in_channels, (list, tuple)) assert isinstance(in_index, (list, tuple)) assert (len(in_channels) == len(in_index)) if (input_transform == 'resize_concat'): self.in_channels = sum(in_channels) else: self.in_channels = in_channels else: assert isinstance(in_channels, int) assert isinstance(in_index, int) self.in_channels = in_channels def init_weights(self): 'Initialize weights of classification layer.' def _transform_inputs(self, inputs): 'Transform inputs for decoder.\n\n Args:\n inputs (list[Tensor]): List of multi-level img features.\n\n Returns:\n Tensor: The transformed inputs\n ' if (self.input_transform == 'resize_concat'): inputs = [inputs[i] for i in self.in_index] upsampled_inputs = [resize(input=x, size=inputs[0].shape[2:], mode='bilinear', align_corners=self.align_corners) for x in inputs] inputs = torch.cat(upsampled_inputs, dim=1) elif (self.input_transform == 'multiple_select'): inputs = [inputs[i] for i in self.in_index] else: inputs = inputs[self.in_index] return inputs def forward(self, inputs): 'Placeholder of forward function.' pass def forward_train(self, inputs, img_metas, gt_semantic_seg, train_cfg): "Forward function for training.\n Args:\n inputs (list[Tensor]): List of multi-level img features.\n img_metas (list[dict]): List of image info dict where each dict\n has: 'img_shape', 'scale_factor', 'flip', and may also contain\n 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n For details on the values of these keys see\n `mmseg/datasets/pipelines/formatting.py:Collect`.\n gt_semantic_seg (Tensor): Semantic segmentation masks\n used if the architecture supports semantic segmentation task.\n train_cfg (dict): The training config.\n\n Returns:\n dict[str, Tensor]: a dictionary of loss components\n " seg_logits = self.forward(inputs) losses = self.losses(seg_logits, gt_semantic_seg) return losses def forward_test(self, inputs, img_metas, test_cfg): "Forward function for testing.\n\n Args:\n inputs (list[Tensor]): List of multi-level img features.\n img_metas (list[dict]): List of image info dict where each dict\n has: 'img_shape', 'scale_factor', 'flip', and may also contain\n 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n For details on the values of these keys see\n `mmseg/datasets/pipelines/formatting.py:Collect`.\n test_cfg (dict): The testing config.\n\n Returns:\n Tensor: Output segmentation map.\n " return self.forward(inputs)
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: l_conv = ConvModule(in_channels, self.channels, 1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, act_cfg=self.act_cfg, inplace=True) fpn_conv = ConvModule(self.channels, self.channels, 3, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, act_cfg=self.act_cfg, inplace=True) self.lateral_convs.append(l_conv) self.fpn_convs.append(fpn_conv) def forward(self, inputs): 'Forward function.' inputs = self._transform_inputs(inputs) laterals = [lateral_conv(inputs[i]) for (i, lateral_conv) in enumerate(self.lateral_convs)] used_backbone_levels = len(laterals) for i in range((used_backbone_levels - 1), 0, (- 1)): prev_shape = laterals[(i - 1)].shape[2:] laterals[(i - 1)] += resize(laterals[i], size=prev_shape, mode='bilinear', align_corners=self.align_corners) fpn_outs = [self.fpn_convs[i](laterals[i]) for i in range((used_backbone_levels - 1))] fpn_outs.append(laterals[(- 1)]) return fpn_outs[0]
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. Default: (1, 2, 3, 6).\n ' def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs): super(PSP, self).__init__(input_transform='multiple_select', **kwargs) self.psp_modules = PPM(pool_scales, self.in_channels[(- 1)], self.channels, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, act_cfg=self.act_cfg, align_corners=self.align_corners) self.bottleneck = ConvModule((self.in_channels[(- 1)] + (len(pool_scales) * self.channels)), self.channels, 3, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, act_cfg=self.act_cfg) def psp_forward(self, inputs): 'Forward function of PSP module.' x = inputs[(- 1)] psp_outs = [x] psp_outs.extend(self.psp_modules(x)) psp_outs = torch.cat(psp_outs, dim=1) output = self.bottleneck(psp_outs) return output def forward(self, inputs): 'Forward function.' inputs = self._transform_inputs(inputs) return self.psp_forward(inputs)
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: (NYUD) (480, 640)\n\n Prediction:\n ```\n # Prediction is made in METRIC DEPTH, not disparity.\n img: torch.Tensor\n pred = net(ops.standardize(img))\n ```\n\n :param scene: (str) Model type to load. {`indoor`, `outdoor`}\n :param max_depth: (None|float) Maximum expected metric depth.\n :return: (nn.Module) Loaded network.\n ' if (scene not in SCENES): raise ValueError(f'Invalid NeWCRFs model. ({scene} vs. {SCENES})') max_depth = (max_depth or (10 if (scene == 'indoor') else 80)) if (max_depth <= 0): raise ValueError(f'Max depth must be a positive number. Got {max_depth}.') net = nn.DataParallel(NewCRFDepth(version='large07', inv_depth=False, max_depth=max_depth, pretrained=None)) ckpt_file = (PATHS['newcrfs_indoor'] if (scene == 'indoor') else PATHS['newcrfs_outdoor']) ckpt = torch.load(ckpt_file, map_location='cpu') net.load_state_dict(ckpt['model']) net = net.eval() for p in net.parameters(): p.requires_grad = False return net
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 ** 2) def forward(self, pred: ty.T, target: ty.T) -> ty.T: 'Compute the structural similarity error between two images.\n\n :param pred: (Tensor) (b, c, h, w) Predicted reconstructed images.\n :param target: (Tensor) (b, c, h, w) Target images to reconstruct.\n :return: (Tensor) (b, c, h, w) Structural similarity error.\n ' (x, y) = (self.refl(pred), self.refl(target)) (mu_x, mu_y) = (self.pool(x), self.pool(y)) sig_x = (self.pool((x ** 2)) - (mu_x ** 2)) sig_y = (self.pool((y ** 2)) - (mu_y ** 2)) sig_xy = (self.pool((x * y)) - (mu_x * mu_y)) num = ((((2 * mu_x) * mu_y) + self.eps1) * ((2 * sig_xy) + self.eps2)) den = ((((mu_x ** 2) + (mu_y ** 2)) + self.eps1) * ((sig_x + sig_y) + self.eps2)) loss = ((1 - (num / den)) / 2).clamp(min=0, max=1) return loss
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 both.\n\n Attributes:\n :param weight_ssim: (float) Weight controlling the contribution of the SSIMLoss. L1 weight is `1 - ssim_weight`.\n ' def __init__(self, weight_ssim: float=0.85): super().__init__() if (not (0 <= weight_ssim <= 1)): raise ValueError(f'Invalid SSIM weight. ({weight_ssim} vs. [0, 1])') self.weight_ssim: float = weight_ssim self.weight_l1: float = (1 - self.weight_ssim) self.ssim: Optional[nn.Module] = (SSIMError() if (self.weight_ssim > 0) else None) self.l1: Optional[nn.Module] = (DenseL1Error() if (self.weight_l1 > 0) else None) def forward(self, pred: ty.T, target: ty.T) -> ty.T: 'Compute the photometric error between two images.\n\n :param pred: (Tensor) (b, c, h, w) Predicted reconstructed images.\n :param target: (Tensor) (b, c, h, w) Target images to reconstruct.\n :return: (Tensor) (b, 1, h, w) Photometric error.\n ' (b, _, h, w) = pred.shape loss = pred.new_zeros((b, 1, h, w)) if self.ssim: loss += (self.weight_ssim * self.ssim(pred, target).mean(dim=1, keepdim=True)) if self.l1: loss += (self.weight_l1 * self.l1(pred, target)) return loss
@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: From Monodepth2 (https://arxiv.org/abs/1806.01260)\n - Explainability mask: From SfM-Learner (https://arxiv.org/abs/1704.07813)\n - Uncertainty mask: From Klodt (https://openaccess.thecvf.com/content_ECCV_2018/papers/Maria_Klodt_Supervising_the_new_ECCV_2018_paper.pdf)\n\n :param loss_name: (str) Loss type to use.\n :param use_min: (bool) If `True`, take the final loss as the minimum across all available views.\n :param use_automask: (bool) If `True`, mask pixels where the original support image has a lower loss than the warped counterpart.\n :param mask_name: (None|str) Weighting mask used. {'explainability', 'uncertainty', None}\n " def __init__(self, loss_name: str='ssim', use_min: bool=False, use_automask: bool=False, mask_name: ty.U[str]=None): super().__init__() self.loss_name = loss_name self.use_min = use_min self.use_automask = use_automask self.mask_name = mask_name if (self.mask_name not in {'explainability', 'uncertainty', None}): raise ValueError(f'Invalid mask type: {self.mask_name}') self._photo = {'ssim': PhotoError(weight_ssim=0.85), 'l1': DenseL1Error(), 'l2': DenseL2Error()}[self.loss_name] self._reduce = ((lambda x: x.min(dim=1, keepdim=True)[0]) if self.use_min else (lambda x: x.mean(dim=1, keepdim=True))) def apply_mask(self, err: ty.T, mask: ty.N[ty.T]=None) -> ty.T: 'Apply a weighting mask to a photometric loss error.\n\n :param err: (Tensor) (b, n, h, w) Photometric error to mask.\n :param mask: (None|ty.T) (b, n, h, w) Optional weighting mask to apply.\n :return: (Tensor) (b, n, h, w) The weighted photometric error.\n ' if (self.mask_name and (mask is None)): raise ValueError("Must provide a 'mask' when masking...") if (self.mask_name == 'explainability'): err *= mask elif (self.mask_name == 'uncertainty'): err = ((err * (- mask).exp()) + mask) return err def apply_automask(self, err: ty.T, source: ty.T, target: ty.T, mask: ty.N[ty.T]=None) -> tuple[(ty.T, ty.T)]: 'Compute and apply an automask based on the identity reconstruction error.\n\n :param err: (Tensor) (b, 1, h, w) The photometric error between target and warped support frames.\n :param target: (Tensor) (b, 3, h, w) Target image to reconstruct.\n :param source: (None|Tensor) (*n, b, 3, h, w) Original support images.\n :param mask: (None|Tensor) (b, n, h, w) Optional weighting mask for the photometric error.\n :return: (\n err: (Tensor) (b, 1, h, w) The automasked photometric error.\n automask: (Tensor) (b, 1, h, w) Boolean mask indicating valid pixels after automasking.\n )\n ' err_static = self.compute_photo(source, target, mask=mask) err_static += (ops.eps(err_static) * torch.randn_like(err_static)) err = torch.cat((err, err_static), dim=1) (err, idxs) = torch.min(err, dim=1, keepdim=True) automask = (idxs == 0) return (err, automask) def compute_photo(self, pred: ty.T, target: ty.T, mask: ty.N[ty.T]=None) -> ty.T: 'Compute the dense photometric between multiple predictions and a single target.\n\n :param pred: (Tensor) (*n, b, 3, h, w) Synthesized warped support images.\n :param target: (Tensor) (b, 3, h, w) Target image to reconstruct.\n :param mask: (None|Tensor) (b, n, h, w) Optional weighting mask for the photometric error.\n :return: (Tensor) (b, 1, h, w) The reduced photometric error.\n ' if (pred.ndim == 4): err = self._photo(pred, target) else: target = target[None].expand_as(pred) err = self._photo(pred.flatten(0, 1), target.flatten(0, 1)) err = err.squeeze(1).unflatten(0, pred.shape[:2]).permute(1, 0, 2, 3) err = self.apply_mask(err, mask) err = self._reduce(err) return err def forward(self, pred: ty.T, target: ty.T, source: ty.N[ty.T]=None, mask: ty.N[ty.T]=None) -> ty.LossData: 'Compute the reconstruction loss between two images.\n\n :param pred: (Tensor) (*n, b, 3, h, w) Synthesized warped support images.\n :param target: (Tensor) (b, 3, h, w) Target image to reconstruct.\n :param source: (None|Tensor) (*n, b, 3, h, w) Original support images.\n :param mask: (None|Tensor) (b, n, h, w) Optional weighting mask for the photometric error.\n :return: (\n loss: (Tensor) (,) Scalar loss.\n loss_dict: {\n (Optional) (If using automasking)\n automask: (Tensor) (b, 1, h, w) Boolean mask indicating valid pixels after automasking.\n }\n )\n ' ld = {} err = self.compute_photo(pred, target, mask) if self.use_automask: if (source is None): raise ValueError("Must provide the original 'source' images when automasking...") (err, automask) = self.apply_automask(err, source, target, mask) ld['automask'] = automask loss = err.mean() return (loss, ld)
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: (bool) If `True`, set threshold dynamically, using `delta` as the max percentage error.\n :return: (Tensor) (*) The computed `berhu` loss.\n ' diff = l1_loss(pred, target) delta = (delta if (not dynamic) else (delta * diff.max())) diff_delta = ((diff.pow(2) + delta.pow(2)) / ((2 * delta) + ops.eps(pred))) loss = torch.where((diff <= delta), diff, diff_delta) return loss
@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...\n\n Contributions:\n - Virtual stereo consistency: From Monodepth (https://arxiv.org/abs/1609.03677)\n - Proxy berHu regression: From Kuznietsov (https://arxiv.org/abs/1702.02706)\n - Proxy LogL1 regression: From Depth Hints (https://arxiv.org/abs/1909.09051)\n - Proxy loss automasking: From Depth Hints/Monodepth2 (https://arxiv.org/abs/1909.09051)\n\n :param loss_name: (str) Loss type to use. {l1, log_l1, berhu}\n :param invert: (bool) If `True`, convert depth inputs into disparity.\n :param use_automask: (bool) If `True`, use DepthHints automask based on the pred/hints errors.\n ' def __init__(self, loss_name: str='berhu', invert: bool=False, use_automask: bool=False): super().__init__() self.loss_name = loss_name self.use_automask = use_automask self.invert = invert self.criterion = {'l1': l1_loss, 'log_l1': log_l1_loss, 'berhu': berhu_loss}[self.loss_name] def forward(self, pred: ty.T, target: ty.T, mask: ty.N[ty.T]=None) -> ty.LossData: if self.invert: (pred, target) = (to_inv(pred), to_inv(target)) if (mask is None): mask = torch.ones_like(target) err = (mask * self.criterion(pred, target)) loss = (err.sum() / mask.sum()) return (loss, {'err_regr': err, 'mask_regr': mask})
@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 - No skip connections, it's an autoencoder!\n\n :param enc_name: (str) `timm` encoder key (check `timm.list_models()`).\n :param pretrained: (bool) If `True`, load an encoder pretrained on ImageNet.\n :param dec_name: (str) Custom decoder class to use.\n :param out_scales: (int|list[int]) Multi-scale outputs to return as `2**s`.\n " def __init__(self, enc_name: str='resnet18', pretrained: bool=True, dec_name: str='monodepth', out_scales: ty.U[(int, ty.S[int])]=(0, 1, 2, 3)): super().__init__() self.enc_name = enc_name self.pretrained = pretrained self.dec_name = dec_name self.out_scales = ([out_scales] if isinstance(out_scales, int) else out_scales) if (self.dec_name not in DEC_REG): raise KeyError(f'Invalid decoder key. ({self.dec_name} vs. {DEC_REG.keys()}') self.encoder = timm.create_model(self.enc_name, features_only=True, pretrained=pretrained) self.num_ch_enc = self.encoder.feature_info.channels() self.enc_sc = self.encoder.feature_info.reduction() self.decoder = DEC_REG[self.dec_name](num_ch_enc=self.num_ch_enc, enc_sc=self.enc_sc, upsample_mode='nearest', use_skip=False, out_sc=self.out_scales, out_ch=3, out_act='sigmoid') def forward(self, x: ty.T) -> ty.AutoencoderPred: 'Run image autoencoder forward pass.\n\n :param x: (Tensor) (b, 3, h, w) Input image.\n :return: {\n autoenc_feats: (list[Tensor]) Autoencoder encoder multi-scale features.\n autoenc_imgs: (TensorDict) (b, 3, h/2**s, w/2**s) Multi-scale image reconstructions.\n }\n ' feat = self.encoder(x) out = {'autoenc_feats': feat, 'autoenc_imgs': sort_dict(self.decoder(feat))} return out
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) out = (att.softmax(dim=(- 1)) @ v) out = (x + out.view(b, c, h, w)) return out
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, padding=0), nn.ReLU(inplace=True), nn.Conv2d(ch, ch, kernel_size=1, stride=1, padding=0), nn.Sigmoid()) def forward(self, x: ty.T) -> ty.T: x = self.conv(x) x = (x + (x * self.att(x))) return x
@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. {'nearest', 'bilinear'...}\n :param use_skip: (bool) If `True`, add skip connections from corresponding encoder stage.\n :param out_sc: (list[int]) List of multi-scale output downsampling factor as 2**s.\n :param out_ch: (int) Number of output channels.\n :param out_act: (str) Activation to apply to each output stage.\n " def __init__(self, num_ch_enc: ty.S[int], enc_sc: ty.S[int], upsample_mode: str='nearest', use_skip: bool=True, out_sc: ty.S[int]=(0, 1, 2, 3), out_ch: int=1, out_act: str='sigmoid'): super().__init__() self.num_ch_enc = num_ch_enc self.enc_sc = enc_sc self.upsample_mode = upsample_mode self.use_skip = use_skip self.out_sc = out_sc self.out_ch = out_ch self.out_act = out_act if (self.out_act not in ACT): raise KeyError(f'Invalid activation key. ({self.out_act} vs. {tuple(ACT.keys())}') self.num_ch_dec = [16, 32, 64, 128, 256] self.convs = OrderedDict() for i in range(4, (- 1), (- 1)): num_ch_in = (self.num_ch_enc[(- 1)] if (i == 4) else self.num_ch_dec[(i + 1)]) num_ch_out = self.num_ch_dec[i] self.convs[f'upconv_{i}_{0}'] = conv_block(num_ch_in, num_ch_out) num_ch_in = self.num_ch_dec[i] scale_factor = (2 ** i) if (self.use_skip and (scale_factor in self.enc_sc)): idx = self.enc_sc.index(scale_factor) num_ch_in += self.num_ch_enc[idx] num_ch_out = self.num_ch_dec[i] self.convs[f'upconv_{i}_{1}'] = conv_block(num_ch_in, num_ch_out) self.convs[f'detail_emphasis_{i}'] = DetailEmphasis(num_ch_in) for i in self.out_sc: self.convs[f'outconv_{i}'] = conv3x3(self.num_ch_dec[i], self.out_ch) self.structure_perception = StructurePerception() self.decoder = nn.ModuleList(list(self.convs.values())) self.activation = ACT[self.out_act] def forward(self, feat: ty.S[ty.T]) -> dict[(int, ty.T)]: out = {} x = self.structure_perception(feat[(- 1)]) for i in range(4, (- 1), (- 1)): x = self.convs[f'upconv_{i}_{0}'](x) x = [F.interpolate(x, scale_factor=2, mode=self.upsample_mode)] scale_factor = (2 ** i) if (self.use_skip and (scale_factor in self.enc_sc)): idx = self.enc_sc.index(scale_factor) x += [feat[idx]] x = torch.cat(x, 1) x = self.convs[f'detail_emphasis_{i}'](x) x = self.convs[f'upconv_{i}_{1}'](x) if (i in self.out_sc): out[i] = self.activation(self.convs[f'outconv_{i}'](x)) return out
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 bins.\n - exp: Spaces bins out exponentially, providing finer detail at low disparity values, ie higher depth values.\n\n :param n: (int) Number of bins to use.\n :param mode: (str) Quantization mode. {linear, exp}\n :return: (ty.T) (1, n, 1, 1) Computed discrete disparity bins.\n ' bins = (torch.arange(n) / n) if (mode == 'linear'): pass elif (mode == 'exp'): max_depth = torch.tensor(200) bins = torch.exp((torch.log(max_depth) * (bins - 1))) else: raise ValueError(f"Invalid discretization mode. '{mode}'") return bins.view(1, n, 1, 1)
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), nn.ReLU(inplace=True)) self.value_conv = nn.Sequential(nn.Conv2d(ch, ch, kernel_size=1, padding=0), nn.ReLU(inplace=True)) def forward(self, x): (b, c, h, w) = x.shape q = self.query_conv(x).flatten((- 2), (- 1)) k = self.key_conv(x).flatten((- 2), (- 1)).permute(0, 2, 1) v = self.value_conv(x).flatten((- 2), (- 1)) att = (q @ k) out = (att.softmax(dim=(- 1)) @ v) out = out.view(b, c, h, w) return out
@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. {'nearest', 'bilinear'...}\n :param use_skip: (bool) If `True`, add skip connections from corresponding encoder stage.\n :param out_sc: (list[int]) List of multi-scale output downsampling factor as 2**s.\n :param out_ch: (int) Number of output channels.\n :param out_act: (str) Activation to apply to each output stage.\n " def __init__(self, num_ch_enc: ty.S[int], enc_sc: ty.S[int], upsample_mode: str='nearest', use_skip: bool=True, out_sc: ty.S[int]=(0, 1, 2, 3), out_ch: int=1, out_act: str='sigmoid'): super().__init__() self.num_ch_enc = num_ch_enc self.enc_sc = enc_sc self.upsample_mode = upsample_mode self.use_skip = use_skip self.out_sc = out_sc self.out_ch = out_ch self.out_act = out_act if (self.out_act not in ACT): raise KeyError(f'Invalid activation key. ({self.out_act} vs. {tuple(ACT.keys())}') self.num_ch_dec = [16, 32, 64, 128, 256] self.num_bins = 128 self.bins = nn.Parameter(get_discrete_bins(self.num_bins, mode='linear'), requires_grad=False) self.convs = OrderedDict() self.convs['att'] = SelfAttentionBlock(self.num_ch_enc[(- 1)]) for i in range(4, (- 1), (- 1)): num_ch_in = (self.num_ch_enc[(- 1)] if (i == 4) else self.num_ch_dec[(i + 1)]) num_ch_out = self.num_ch_dec[i] self.convs[f'upconv_{i}_{0}'] = conv_block(num_ch_in, num_ch_out) num_ch_in = self.num_ch_dec[i] scale_factor = (2 ** i) if (self.use_skip and (scale_factor in self.enc_sc)): idx = self.enc_sc.index(scale_factor) num_ch_in += self.num_ch_enc[idx] num_ch_out = self.num_ch_dec[i] self.convs[f'upconv_{i}_{1}'] = conv_block(num_ch_in, num_ch_out) for i in self.out_sc: self.convs[f'outconv_{i}'] = conv3x3(self.num_ch_dec[i], (self.num_bins * self.out_ch)) self.decoder = nn.ModuleList(list(self.convs.values())) self.activation = ACT[self.out_act] self.logits = {} def expected_disparity(self, logits: ty.T) -> ty.T: 'Maps discrete disparity logits into the expected weighted disparity.\n\n :param logits: (ty.T) (b, n, h, w) Raw unnormalized predicted probabilities.\n :return: (ty.T) (b, 1, h, w) Expected disparity map.\n ' probs = logits.softmax(dim=1) disp = (probs * self.bins).sum(dim=1, keepdim=True) return disp def argmax_disparity(self, logits: ty.T) -> ty.T: idx = logits.argmax(dim=1) one_hot = F.one_hot(idx, self.num_bins).permute(0, 3, 1, 2) disp = (one_hot * self.bins).sum(dim=1, keepdim=True) return disp def forward(self, feat: ty.S[ty.T]) -> dict[(int, ty.T)]: out = {} x = self.convs['att'](feat[(- 1)]) for i in range(4, (- 1), (- 1)): x = self.convs[f'upconv_{i}_{0}'](x) x = [F.interpolate(x, scale_factor=2, mode=self.upsample_mode)] scale_factor = (2 ** i) if (self.use_skip and (scale_factor in self.enc_sc)): idx = self.enc_sc.index(scale_factor) x += [feat[idx]] x = torch.cat(x, 1) x = self.convs[f'upconv_{i}_{1}'](x) if (i in self.out_sc): logits = self.convs[f'outconv_{i}'](x) self.logits[i] = logits out[i] = torch.cat([self.expected_disparity(l) for l in logits.chunk(self.out_ch, dim=1)], dim=1) return out
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.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential(nn.Linear(in_ch, (in_ch // ratio), bias=False), nn.ReLU(inplace=True), nn.Linear((in_ch // ratio), in_ch, bias=False)) self.init_weights() def init_weights(self): 'Kaiming weight initialization.' for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') def forward(self, x): att = self.avg_pool(x) att = self.fc(att.squeeze()).sigmoid() return (x * att[(..., None, None)])
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 upsampling mode. {'nearest', 'bilinear'...}\n " 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.layers = nn.Sequential(ChannelAttention(self.in_ch), conv3x3(self.in_ch, self.out_ch), nn.ReLU(inplace=True)) def forward(self, x, x_skip): return self.layers(torch.cat((F.interpolate(x, scale_factor=2, mode=self.upsample_mode), x_skip), dim=1))
@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. {'nearest', 'bilinear'...}\n :param use_skip: (bool) If `True`, add skip connections from corresponding encoder stage.\n :param out_sc: (list[int]) List of multi-scale output downsampling factor as 2**s.\n :param out_ch: (int) Number of output channels.\n :param out_act: (str) Activation to apply to each output stage.\n " def __init__(self, num_ch_enc: ty.S[int], enc_sc: ty.S[int], upsample_mode: str='nearest', use_skip: bool=True, out_sc: ty.S[int]=(0, 1, 2, 3), out_ch: int=1, out_act: str='sigmoid'): super().__init__() self.num_ch_enc = num_ch_enc self.enc_sc = enc_sc self.upsample_mode = upsample_mode self.use_skip = use_skip self.out_sc = out_sc self.out_ch = out_ch self.out_act = out_act if (self.out_act not in ACT): raise KeyError(f'Invalid activation key. ({self.out_act} vs. {tuple(ACT.keys())}') self.num_ch_dec = [16, 32, 64, 128, 256] self.convs = nn.ModuleDict() for i in range(4, (- 1), (- 1)): num_ch_in = (self.num_ch_enc[(- 1)] if (i == 4) else self.num_ch_dec[(i + 1)]) num_ch_out = self.num_ch_dec[i] scale_factor = (2 ** i) if (self.use_skip and (scale_factor in self.enc_sc)): idx = self.enc_sc.index(scale_factor) num_ch_skip = self.num_ch_enc[idx] self.convs[f'upconv_{i}'] = AttentionBlock(num_ch_in, num_ch_skip, num_ch_out, self.upsample_mode) else: self.convs[f'upconv_{i}'] = upsample_block(num_ch_in, num_ch_out, self.upsample_mode) for i in range(4): self.convs[f'outconv_{i}'] = conv3x3(self.num_ch_dec[i], self.out_ch) self.decoder = nn.ModuleList(list(self.convs.values())) self.activation = ACT[self.out_act] def forward(self, feat: ty.S[ty.T]) -> dict[(int, ty.T)]: out = {} x = feat[(- 1)] for i in range(4, (- 1), (- 1)): scale_factor = (2 ** i) if (self.use_skip and (scale_factor in self.enc_sc)): idx = self.enc_sc.index(scale_factor) x = self.convs[f'upconv_{i}'](x, feat[idx]) else: x = self.convs[f'upconv_{i}'](x) if (i in self.out_sc): out[i] = self.activation(self.convs[f'outconv_{i}'](x)) return out
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 self.avg_pool = nn.AdaptiveAvgPool2d(1) self.se = nn.Sequential(nn.Linear(self.in_ch, (self.in_ch // self.reduction), bias=False), nn.ReLU(inplace=True), nn.Linear((self.in_ch // self.reduction), self.in_ch, bias=False)) self.conv = nn.Sequential(conv1x1(self.in_ch, self.out_ch, bias=True), nn.ReLU(inplace=True)) def forward(self, x: ty.T, xs_skip: ty.S[ty.T]) -> ty.T: x = F.interpolate(x, scale_factor=2, mode=self.upsample_mode) x = torch.cat([x, *xs_skip], dim=1) y = self.avg_pool(x).squeeze() y = self.se(y).sigmoid() y = y[(..., None, None)].expand_as(x) x = self.conv((x * y)) return x
@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. {'nearest', 'bilinear'...}\n :param out_sc: (ty.S[int]) List of multi-scale output downsampling factor as 2**s.\n :param out_ch: (int) Number of output channels.\n :param out_act: (str) Activation to apply to each output stage.\n " def __init__(self, num_ch_enc: ty.S[int], enc_sc: ty.S[int], upsample_mode: str='nearest', use_skip: bool=True, out_sc: ty.S[int]=(0, 1, 2, 3), out_ch: int=1, out_act: str='sigmoid'): super().__init__() self.num_ch_enc = num_ch_enc self.enc_sc = enc_sc self.upsample_mode = upsample_mode self.use_skip = use_skip self.out_sc = out_sc self.out_ch = out_ch self.out_act = out_act if (not self.use_skip): raise ValueError('HRDepth decoder must use skip connections.') if (len(self.enc_sc) == 4): warnings.warn('HRDepth requires 5 scales, but the provided backbone has only 4. The first scale will be duplicated and upsampled!') self.enc_sc = ([(self.enc_sc[0] // 2)] + self.enc_sc) self.num_ch_enc = ([self.num_ch_enc[0]] + self.num_ch_enc) if (self.out_act not in ACT): raise KeyError(f'Invalid activation key. ({self.out_act} vs. {tuple(ACT.keys())}') self.activation = ACT[self.out_act] self.num_ch_dec = [(ch // 2) for ch in self.num_ch_enc[1:]] self.num_ch_dec = ([(self.num_ch_dec[0] // 2)] + self.num_ch_dec) self.all_idx = ['01', '11', '21', '31', '02', '12', '22', '03', '13', '04'] self.att_idx = ['31', '22', '13', '04'] self.non_att_idx = ['01', '11', '21', '02', '12', '03'] self.convs = nn.ModuleDict() for j in range(5): for i in range((5 - j)): ch_in = self.num_ch_enc[i] if ((i == 0) and (j != 0)): ch_in //= 2 if ((i == 0) and (j == 4)): ch_in = (self.num_ch_enc[(i + 1)] // 2) ch_out = (ch_in // 2) self.convs[f'{i}{j}_conv_0'] = conv_block(ch_in, ch_out) if ((i == 0) and (j == 4)): ch_in = ch_out ch_out = self.num_ch_dec[i] self.convs[f'{i}{j}_conv_1'] = conv_block(ch_in, ch_out) for idx in self.att_idx: (row, col) = (int(idx[0]), int(idx[1])) self.convs[f'{idx}_att'] = FSEBlock(in_ch=(self.num_ch_enc[(row + 1)] // 2), skip_ch=(self.num_ch_enc[row] + (self.num_ch_dec[(row + 1)] * (col - 1))), upsample_mode=self.upsample_mode) for idx in self.non_att_idx: (row, col) = (int(idx[0]), int(idx[1])) if (col == 1): self.convs[f'{(row + 1)}{(col - 1)}_conv_1'] = conv_block(in_ch=((self.num_ch_enc[(row + 1)] // 2) + self.num_ch_enc[row]), out_ch=self.num_ch_dec[(row + 1)]) else: self.convs[f'{idx}_down'] = conv1x1(in_ch=(((self.num_ch_enc[(row + 1)] // 2) + self.num_ch_enc[row]) + (self.num_ch_dec[(row + 1)] * (col - 1))), out_ch=(2 * self.num_ch_dec[(row + 1)]), bias=False) self.convs[f'{(row + 1)}{(col - 1)}_conv_1'] = conv_block(in_ch=(2 * self.num_ch_dec[(row + 1)]), out_ch=self.num_ch_dec[(row + 1)]) channels = self.num_ch_dec for (i, c) in enumerate(channels): if (i in self.out_sc): self.convs[f'outconv_{i}'] = nn.Sequential(conv3x3(c, self.out_ch), self.activation) self.decoder = nn.ModuleList(list(self.convs.values())) def nested_conv(self, convs: ty.S[nn.Module], x: ty.T, xs_skip: ty.S[ty.T]) -> ty.T: x = F.interpolate(convs[0](x), scale_factor=2, mode=self.upsample_mode) x = torch.cat([x, *xs_skip], dim=1) if (len(convs) == 3): x = convs[2](x) x = convs[1](x) return x def forward(self, enc_features: ty.S[ty.T]) -> dict[(int, ty.T)]: if (len(enc_features) == 4): enc_features = ([F.interpolate(enc_features[0], scale_factor=2, mode=self.upsample_mode)] + enc_features) feat = {f'{i}0': f for (i, f) in enumerate(enc_features)} for idx in self.all_idx: (row, col) = (int(idx[0]), int(idx[1])) xs_skip = [feat[f'{row}{i}'] for i in range(col)] if (idx in self.att_idx): feat[f'{idx}'] = self.convs[f'{idx}_att'](self.convs[f'{(row + 1)}{(col - 1)}_conv_0'](feat[f'{(row + 1)}{(col - 1)}']), xs_skip) elif (idx in self.non_att_idx): conv = [self.convs[f'{(row + 1)}{(col - 1)}_conv_0'], self.convs[f'{(row + 1)}{(col - 1)}_conv_1']] if (col != 1): conv.append(self.convs[f'{idx}_down']) feat[f'{idx}'] = self.nested_conv(conv, feat[f'{(row + 1)}{(col - 1)}'], xs_skip) x = feat['04'] x = self.convs['04_conv_0'](x) x = self.convs['04_conv_1'](F.interpolate(x, scale_factor=2, mode=self.upsample_mode)) out_feat = [x, feat['04'], feat['13'], feat['22']] out = {i: self.convs[f'outconv_{i}'](f) for (i, f) in enumerate(out_feat) if (i in self.out_sc)} return out
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(enc_features) [print(key, val.shape) for (key, val) in out.items()]
@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]) List of downsampling factor per encoder stage.\n :param upsample_mode: (str) Torch upsampling mode. {'nearest', 'bilinear'...}\n :param use_skip: (bool) If `True`, add skip connections from corresponding encoder stage.\n :param out_sc: (ty.S[int]) List of multi-scale output downsampling factor as 2**s.\n :param out_ch: (int) Number of output channels.\n :param out_act: (str) Activation to apply to each output stage.\n " def __init__(self, num_ch_enc: ty.S[int], enc_sc: ty.S[int], upsample_mode: str='nearest', use_skip: bool=True, out_sc: ty.S[int]=(0, 1, 2, 3), out_ch: int=1, out_act: str='sigmoid'): super().__init__() self.num_ch_enc = num_ch_enc self.enc_sc = enc_sc self.upsample_mode = upsample_mode self.use_skip = use_skip self.out_sc = out_sc self.out_ch = out_ch self.out_act = out_act if (self.out_act not in ACT): raise KeyError(f'Invalid activation key. ({self.out_act} vs. {tuple(ACT.keys())}') self.act = ACT[self.out_act] self.num_ch_dec = [16, 32, 64, 128, 256] self.convs = OrderedDict() for i in range(4, (- 1), (- 1)): num_ch_in = (self.num_ch_enc[(- 1)] if (i == 4) else self.num_ch_dec[(i + 1)]) num_ch_out = self.num_ch_dec[i] self.convs[f'upconv_{i}_{0}'] = conv_block(num_ch_in, num_ch_out) num_ch_in = self.num_ch_dec[i] sf = (2 ** i) if (self.use_skip and (sf in self.enc_sc)): idx = self.enc_sc.index(sf) num_ch_in += self.num_ch_enc[idx] num_ch_out = self.num_ch_dec[i] self.convs[f'upconv_{i}_{1}'] = conv_block(num_ch_in, num_ch_out) for i in self.out_sc: self.convs[f'outconv_{i}'] = conv3x3(self.num_ch_dec[i], self.out_ch) self.decoder = nn.ModuleList(list(self.convs.values())) def forward(self, feat: ty.S[ty.T]) -> dict[(int, ty.T)]: out = {} x = feat[(- 1)] for i in range(4, (- 1), (- 1)): x = self.convs[f'upconv_{i}_{0}'](x) x = [F.interpolate(x, scale_factor=2, mode=self.upsample_mode)] sf = (2 ** i) if (self.use_skip and (sf in self.enc_sc)): idx = self.enc_sc.index(sf) x += [feat[idx]] x = torch.cat(x, 1) x = self.convs[f'upconv_{i}_{1}'](x) if (i in self.out_sc): out[i] = self.act(self.convs[f'outconv_{i}'](x)) return out
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_weights() def init_weights(self): nn.init.zeros_(self.conv.bias) self.conv.weight = nn.Parameter(self.conv.weight[::4].repeat_interleave(4, 0)) def forward(self, x): return self.shuffle(self.conv(x))
@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]) List of downsampling factor per encoder stage.\n :param upsample_mode: (str) Torch upsampling mode. {'nearest', 'bilinear'...}\n :param use_skip: (bool) If `True`, add skip connections from corresponding encoder stage.\n :param out_sc: (ty.S[int]) List of multi-scale output downsampling factor as 2**s.\n :param out_ch: (int) Number of output channels.\n :param out_act: (str) Activation to apply to each output stage.\n " def __init__(self, num_ch_enc: ty.S[int], enc_sc: ty.S[int], upsample_mode: str='nearest', use_skip: bool=True, out_sc: ty.S[int]=(0, 1, 2, 3), out_ch: int=1, out_act: str='sigmoid'): super().__init__() self.num_ch_enc = num_ch_enc self.enc_sc = enc_sc self.upsample_mode = upsample_mode self.use_skip = use_skip self.out_sc = out_sc self.out_ch = out_ch self.out_act = out_act if (self.out_act not in ACT): raise KeyError(f'Invalid activation key. ({self.out_act} vs. {tuple(ACT.keys())}') self.activation = ACT[self.out_act] self.num_ch_dec = [16, 32, 64, 128, 256] self.convs = OrderedDict() for i in range(4, (- 1), (- 1)): num_ch_in = (self.num_ch_enc[(- 1)] if (i == 4) else self.num_ch_dec[(i + 1)]) num_ch_out = self.num_ch_dec[i] self.convs[f'upconv_{i}_{0}'] = nn.Sequential(conv_block(num_ch_in, num_ch_out), SubPixelConv(num_ch_out, up_factor=2), nn.ReLU(inplace=True)) num_ch_in = self.num_ch_dec[i] scale_factor = (2 ** i) if (self.use_skip and (scale_factor in self.enc_sc)): idx = self.enc_sc.index(scale_factor) num_ch_in += self.num_ch_enc[idx] num_ch_out = self.num_ch_dec[i] self.convs[f'upconv_{i}_{1}'] = conv_block(num_ch_in, num_ch_out) for i in self.out_sc: if (i == 0): self.convs[f'outconv_{i}'] = nn.Sequential(conv3x3(self.num_ch_dec[i], self.out_ch), self.activation) else: self.convs[f'outconv_{i}'] = nn.Sequential(conv_block(self.num_ch_dec[i], self.out_ch), SubPixelConv(self.out_ch, up_factor=(2 ** i)), self.activation) self.decoder = nn.ModuleList(list(self.convs.values())) def forward(self, feat: ty.S[ty.T]) -> dict[(int, ty.T)]: out = {} x = feat[(- 1)] for i in range(4, (- 1), (- 1)): x = [self.convs[f'upconv_{i}_{0}'](x)] sf = (2 ** i) if (self.use_skip and (sf in self.enc_sc)): idx = self.enc_sc.index(sf) x += [feat[idx]] x = torch.cat(x, 1) x = self.convs[f'upconv_{i}_{1}'](x) if (i in self.out_sc): out[i] = self.convs[f'outconv_{i}'](x) return out
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, paths['MODEL_ROOTS']), io.lmap(Path, paths['DATA_ROOTS']))
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: paths[k] = next((p for r in roots if (p := (r / v)).exists())) logging.debug(f"Found {key} path '{k}': {paths[k]}") except StopIteration: logging.warning(f"No valid {key} path found for '{k}:{v}'!") return paths
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 for {name} in {MODEL_ROOTS}...')
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 found for {name} in {DATA_ROOTS}...')
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 class MyNet(nn.Module): ...\n\n # Register to specific type.\n @register('my_loss', type='loss')\n class MyClass(nn.Module): ...\n\n # Register multiple names for the same class.\n @register(('my_dataset1', 'my_dataset2'))\n class MyDataset(Dataset): ...\n ```\n\n :param name: (str|Sequence[str]) Key(s) used to access class in the registry.\n :param type: (None|str) Registry to use. If `None`, guess from class name. {None, net, loss, data, pred}\n :param overwrite: (bool) If `True`, overwrite class `name` in registry `type`.\n :return:\n " def _guess_type(cls: CLS) -> str: 'Helper to identify registry `type` from class name.' try: return next((v for (k, v) in _NAME2TYPE.items() if cls.__name__.endswith(k))) except StopIteration: raise ValueError(f'Class matched no known patterns. ({cls.__name__} vs. {set(_NAME2TYPE)})') def wrapper(cls: CLS) -> CLS: 'Decorator adding `cls` to the specified registry.' if (cls.__module__ == '__main__'): logger.warning(f"Ignoring class '{cls.__name__}' created in the '__main__' module.") return cls ns = ((name,) if isinstance(name, str) else name) t = (type or _guess_type(cls)) if (t not in _REG): raise TypeError(f'Invalid `type`. ({t} vs. {set(_REG)})') reg = _REG[t] for n in ns: if ((not overwrite) and (tgt := reg.get(n))): raise ValueError(f"'{n}' already in '{t}' registry ({tgt} vs. {cls}). Set `overwrite=True` to overwrite.") logger.debug(f"Added '{n}' to the '{t}' registry...") reg[n] = cls return cls return wrapper
@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 solution where all pixels are ignored, this regularization pushes all values towards 1\n using binary cross-entropy.\n ' def forward(self, x: ty.T) -> ty.LossData: 'Mask regularization forward pass.\n\n :param x: (Tensor) (*) Input sigmoid explainability mask.\n :return: {\n loss: (Tensor) (,) Computed loss.\n loss_dict: (TensorDict) {}.\n }\n ' loss = F.binary_cross_entropy(x, torch.ones_like(x)) return (loss, {})
@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 we CANNOT apply mean normalization to the input disparity. By definition, this fixes the mean of\n all elements to 1, meaning the loss is impossible to minimize.\n\n NOTE: The benefits of applying this regularization to purely monocular supervision are unclear,\n since the loss could simply be optimized by making all disparities smaller.\n\n :param invert: (bool) If `True`, encourage foreground disparities instead of background.\n ' def __init__(self, invert: bool=False): super().__init__() self.invert = invert self._sign = ((- 1) if self.invert else 1) def forward(self, x: ty.T) -> ty.LossData: 'Occlusion regularization forward pass.\n\n :param x: (Tensor) (*) Input sigmoid disparities.\n :return: {\n loss: (Tensor) (,) Computed loss.\n loss_dict: (TensorDict) {}.\n }\n ' loss = (self._sign * x.mean()) return (loss, {})
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(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]) Filenames to ignore, e.g. corrupted?\n :param reverse: (bool) If `True`, return earliest checkpoint.\n :param suffix: (str) Expected checkpoint file extension.\n :return: (Path) Latest checkpoint file or `None`.\n ' path = Path(path) ignore = (ignore or []) if (('last' not in ignore) and (last_file := (path / ('last' + suffix))).is_file()): return last_file files = filter((lambda f: ((f.suffix == suffix) and (f.name not in ignore))), sorted(path.iterdir(), reverse=(not reverse))) try: file = next(files) except StopIteration: file = None return file
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