code stringlengths 17 6.64M |
|---|
def compute_columns(datum_names: List[str], datum_types: List[str], requested_annotations: List[str], cuboid_datum: Optional[str]=None, with_ontology_table: bool=True) -> List[str]:
"Method to parse requested datums, types, and annotations into keys for fetching from wicker.\n\n Parameters\n ----------\n ... |
class DGPS3Dataset(S3Dataset):
'\n S3Dataset for data stored in dgp synchronized scene format in wicker. This is a baseclass\n inteded for use with all DGP wicker datasets. It handles conversion from wicker binary formats\n to DGP datum and annotation objects\n '
def __init__(self, *args: Any, wi... |
def gen_wicker_key(datum_name: str, field: str) -> str:
"Generate a key from a datum name and field i.e 'rgb', 'pose' etc\n\n Parameters\n ----------\n datum_name: str\n The name of the datum\n\n field: str\n The field of the datum\n\n Returns\n -------\n key: str\n The w... |
def parse_wicker_key(key: str) -> Tuple[(str, str)]:
'Parse a wicker dataset key into a datum and field combination\n\n Parameters\n ----------\n key: str\n The wicker key name formed from datum_name and field\n\n Returns\n -------\n datum_name: str\n The name of the datum\n\n f... |
def wicker_types_from_sample(sample: List[List[Dict]], ontology_table: Optional[Dict]=None, skip_camera_cuboids: bool=True) -> Dict[(str, Any)]:
'Get the wicker keys and types from an existing dgp sample.\n\n Parameters\n ----------\n sample: List[List[Dict]]\n SynchronizedSceneDataset-style sampl... |
def dgp_to_wicker_sample(sample: List[List[Dict]], wicker_keys: List[str], scene_index: Optional[int], sample_index_in_scene: Optional[int], ontology_table: Optional[Dict], scene_uri: Optional[str]) -> Dict:
'Convert a DGP sample to the Wicker format.\n\n Parameters\n ----------\n sample: List[List[Dict]... |
def get_scenes(scene_dataset_json: str, data_uri: Optional[str]=None) -> List[Tuple[(int, str, str)]]:
'Get all the scene files from scene_dataset_json\n\n Parameters\n ----------\n scene_dataset_json: str\n Path ot dataset json in s3 or local.\n\n data_uri: str, default: None\n Optional... |
def chunk_scenes(scenes: List[Tuple[(int, str, str)]], max_len: int=200, chunk_size: int=100) -> List[Tuple[(int, str, str, Tuple[(int, int)])]]:
'Split each scene into chunks of max length chunk_size samples.\n\n Parameters\n ----------\n scenes: List[str,str]\n List of scene split/path tuples.\n... |
def local_spark() -> pyspark.SparkContext:
'Generate a spark context for local testing of small datasets\n\n Returns\n -------\n spark_context: A spark context\n '
spark = pyspark.sql.SparkSession.builder.master('local[*]').appName('dgp2wicker').config('spark.driver.memory', '56G').config('spark.e... |
def ingest_dgp_to_wicker(scene_dataset_json: str, wicker_dataset_name: str, wicker_dataset_version: str, dataset_kwargs: Dict, spark_context: pyspark.SparkContext, pipeline: Optional[List[Callable]]=None, max_num_scenes: int=None, max_len: int=1000, chunk_size: int=1000, skip_camera_cuboids: bool=True, num_partitions... |
class CustomInstallCommand(install):
'Custom install command'
def run(self):
install.run(self)
|
class CustomDevelopCommand(develop):
'Custom develop command'
def run(self):
develop.run(self)
|
def s3_is_configured():
'Utility to check if there is a valid s3 dataset path configured'
wicker_config_path = os.getenv('WICKER_CONFIG_PATH', os.path.expanduser('~/wickerconfig.json'))
with open(wicker_config_path, 'r', encoding='utf-8') as f:
wicker_config = json.loads(f.read())
return wicke... |
class TestDDGP2Wicker(unittest.TestCase):
def setUp(self):
'Create a local dgp dataset for testing'
self.dataset = SynchronizedSceneDataset(TEST_WICKER_DATASET_JSON, split='train', datum_names=['LIDAR', 'CAMERA_01'], forward_context=0, backward_context=0, requested_annotations=('bounding_box_2d',... |
class BaseAgentDataset():
'A base class representing a Agent Dataset. Provides utilities for parsing and slicing\n DGP format agent datasets.\n\n Parameters\n ----------\n Agent_dataset_metadata: DatasetMetadata\n Dataset metadata object that encapsulates dataset-level agents metadata for\n ... |
class AgentContainer():
'Object-oriented container for holding agent information from a scene.\n '
RANDOM_STR = ''.join([str(random.randint(0, 9)) for _ in range(5)])
cache_suffix = os.environ.get('DGP_SCENE_CACHE_SUFFIX', RANDOM_STR)
cache_dir = os.path.join(DGP_CACHE_DIR, f'dgp_diskcache_{cache_s... |
class AgentDataset(BaseAgentDataset):
'Dataset for agent-centric prediction or planning use cases, works just like normal SynchronizedSceneDataset,\n but guaranteeing trajectory of main agent is present in any fetched sample.\n\n Parameters\n ----------\n scene_dataset_json: str\n Full path to ... |
class AgentDatasetLite(BaseAgentDataset):
'Dataset for agent-centric prediction or planning use cases. It provide two mode of accessing agent, by track\n and by frame. If \'batch_per_agent\' is set true, then the data iterate per track, note, the length of the track\n could vary. Otherwise, the data iterate... |
class AgentMetadata():
'A Wrapper agents metadata class to support two entrypoints for agents dataset\n (reading from agents.json).\n\n Parameters\n ----------\n agent_groups: list[AgentContainer]\n List of AgentContainer objects to be included in the dataset.\n\n directory: str\n Dir... |
class _ParallelDomainDataset(_SynchronizedDataset):
'Dataset for PD data. Works just like normal SynchronizedSceneDataset,\n with special keyword datum name "lidar". When this datum is requested,\n all lidars are coalesced into a single "lidar" datum.\n\n Parameters\n ----------\n dataset_metadata:... |
class ParallelDomainSceneDataset(_ParallelDomainDataset):
'\n Refer to SynchronizedSceneDataset for parameters.\n '
def __init__(self, scene_dataset_json, split='train', datum_names=None, requested_annotations=None, requested_autolabels=None, backward_context=0, forward_context=0, generate_depth_from_d... |
class ParallelDomainScene(_ParallelDomainDataset):
'\n Refer to SynchronizedScene for parameters.\n '
def __init__(self, scene_json, datum_names=None, requested_annotations=None, requested_autolabels=None, backward_context=0, forward_context=0, generate_depth_from_datum=None, only_annotated_datums=Fals... |
class _SynchronizedDataset(BaseDataset):
'Multi-modal dataset with sample-level synchronization.\n See BaseDataset for input parameters for the parent class.\n\n Parameters\n ----------\n dataset_metadata: DatasetMetadata\n Dataset metadata, populated from scene dataset JSON\n\n scenes: list... |
class SynchronizedSceneDataset(_SynchronizedDataset):
'Main entry-point for multi-modal dataset with sample-level\n synchronization using scene directories as input.\n\n Note: This class is primarily used for self-supervised learning tasks where\n the default mode of operation is learning from a collecti... |
class SynchronizedScene(_SynchronizedDataset):
'Main entry-point for multi-modal dataset with sample-level\n synchronization using a single scene JSON as input.\n\n Note: This class can be used to introspect a single scene given a scene\n directory with its associated scene JSON.\n\n Parameters\n -... |
class FeatureOntology():
'Feature ontology object. At bare minimum, we expect ontologies to provide:\n ID: (int) identifier for feature field name\n Name: (str) string identifier for feature field name\n\n Based on the task, additional fields may be populated. Refer to `dataset.proto` and `ontolo... |
class AgentFeatureOntology(FeatureOntology):
'Agent feature ontologies derive directly from Ontology'
|
def tqdm(*args, **kwargs):
kwargs['disable'] = DGP_DISABLE_TQDM
return _tqdm(*args, **kwargs)
|
def points_in_cuboid(query_points, cuboid):
'Tests if a point is contained by a cuboid. Assumes points are in the same frame as the cuboid, \n i.e, cuboid.pose translates points in the cuboid local frame to the query_point frame.\n\n Parameters\n ----------\n query_points: np.ndarray\n Numpy ar... |
def accumulate_points(point_datums, target_datum, transform_boxes=False):
"Accumulates lidar or radar points by transforming all datums in point_datums to the frame used in target_datum.\n\n Parameters\n ----------\n point_datums: list[dict]\n List of datum dictionaries to accumulate\n\n target... |
def is_empty_annotation(annotation_file, annotation_type):
'Check if JSON style annotation files are empty\n\n Parameters\n ----------\n annotation_file: str\n Path to JSON file containing annotations for 2D/3D bounding boxes\n\n annotation_type: object\n Protobuf pb2 object we want to l... |
@diskcache(protocol='npz')
def get_depth_from_point_cloud(dataset, scene_idx, sample_idx_in_scene, cam_datum_name, pc_datum_name):
"Generate the depth map in the camera view using the provided point cloud\n datum within the sample.\n\n Parameters\n ----------\n dataset: dgp.dataset.BaseDataset\n ... |
def clear_cache(directory=DGP_CACHE_DIR):
'Clear DGP cache to avoid growing disk-usage.\n\n Parameters\n ----------\n directory: str, optional\n A pathname to the directory used by DGP for caching. Default: DGP_CACHE_DIR.\n '
if os.path.isdir(directory):
logging.info('Clearing dgp d... |
def diskcache(protocol='npz', cache_dir=None):
'Disk-caching method/function decorator that caches results into\n dgp cache for arbitrary pickle-able / numpy objects.\n\n Parameters\n ----------\n protocol: str, optional\n Serialization protocol. Choices: {npz, pkl}. Default: "npz" (numpy).\n\n... |
def add_options(**kwargs):
'Decorator function to add a list of Click options to a Click subcommand.\n\n Parameters\n ----------\n **kwargs: dict\n The `options` keyword argument shall be a list of string options to extend a Click CLI.\n '
def _add_options(func):
return functools.r... |
def init_s3_client(use_ssl=False):
'Initiate S3 AWS client.\n\n Parameters\n ----------\n use_ssl: bool, optional\n Use secure sockets layer. Provieds better security to s3, but\n can fail intermittently in a multithreaded environment. Default: False.\n\n Returns\n -------\n servic... |
def s3_recursive_list(s3_prefix):
"List all files contained in an s3 location recursively and also return their md5_sums\n NOTE: this is different from 'aws s3 ls' in that it will not return directories, but instead\n the full paths to the files contained in any directories (which is what s3 is actually tra... |
def return_last_value(retry_state):
'Return the result of the last call attempt.\n\n Parameters\n ----------\n retry_state: tenacity.RetryCallState\n Retry-state metadata for a flaky call.\n '
return retry_state.outcome.result()
|
def is_false(value):
return (value is False)
|
@tenacity.retry(stop=tenacity.stop_after_attempt(3), retry=tenacity.retry_if_result(is_false), retry_error_callback=return_last_value)
def s3_copy(source_path, target_path, verbose=True):
'Copy single file from local to s3, s3 to local, or s3 to s3.\n\n Parameters\n ----------\n source_path: str\n ... |
def parallel_s3_copy(source_paths, target_paths, threadpool_size=None):
'Copy files from local to s3, s3 to local, or s3 to s3 using a threadpool.\n Retry the operation if any files fail to copy. Throw an AssertionError if it fails the 2nd time.\n\n Parameters\n ----------\n source_paths: List of str\... |
@tenacity.retry(stop=tenacity.stop_after_attempt(3), retry=tenacity.retry_if_result(is_false), retry_error_callback=return_last_value)
def sync_dir(source, target, file_ext=None, verbose=True):
"Sync a directory from source to target (either local to s3, s3 to s3, s3 to local)\n\n Parameters\n ----------\n ... |
def parallel_s3_sync(source_paths, target_paths, threadpool_size=None):
'Copy directories from local to s3, s3 to local, or s3 to s3 using a threadpool.\n Retry the operation if any files fail to sync. Throw an AssertionError if it fails the 2nd time.\n\n Parameters\n ----------\n source_paths: List o... |
def sync_dir_safe(source, target, verbose=True):
'Sync a directory from local to s3 by first ensuring that NONE of the files in `target`\n have been edited in `source` (new files can exist in `source` that are not in `target`)\n (NOTE: only checks files from `target` that exist in `source`)\n\n Parameter... |
def s3_bucket(bucket_name):
'Instantiate S3 bucket object from its bucket name\n\n Parameters\n ----------\n bucket_name : str\n Bucket name to instantiate.\n\n Returns\n -------\n S3 bucket\n '
return boto3.session.Session().resource('s3').Bucket(bucket_name)
|
def list_s3_objects(bucket_name, url):
'List all files within a valid S3 bucket\n\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n url : str\n The remote URL of the object to be fetched\n '
return list(s3_bucket(bucket_name).objects.filter(Prefix=url))
|
def exists_s3_object(bucket_name, url):
'Uses a valid S3 bucket to check the existence of a remote file as AWS URL.\n\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n url : str\n The remote URL of the object to be fetched\n\n Returns\n -------\n bool:\... |
def convert_uri_to_bucket_path(uri, strip_trailing_slash=True):
"Parse a URI into a bucket and path.\n\n Parameters\n ----------\n uri: str\n A full s3 path (e.g. 's3://<s3-bucket>/<s3-prefix>')\n\n strip_trailing_slash: bool, optional\n If True, we strip any trailing slash in `s3_path` ... |
def parallel_download_s3_objects(s3_files, destination_filepaths, bucket_name, process_pool_size=None):
'Download a list of s3 objects using a processpool.\n\n Parameters\n ----------\n s3_files: list\n List of all files from s3 to download\n\n destination_filepaths: list\n List of where to ... |
def parallel_upload_s3_objects(source_filepaths, s3_destinations, bucket_name, process_pool_size=None):
'Upload a list of s3 objects using a processpool.\n\n Parameters\n ----------\n source_filepaths: list\n List of all local files to upload.\n\n s3_destinations: list\n Paths relative to bu... |
def download_s3_object_to_path(bucket_name, s3_path, local_path):
'Download an object from s3 to a path on the local filesystem.\n\n Parameters\n ----------\n bucket_name: str\n S3 bucket from which to fetch.\n\n s3_path: str\n The path on the s3 bucket to the file to fetch.\n\n local... |
def delete_s3_object(bucket_name, object_key, verbose=True):
'Delete an object in s3.\n\n Parameters\n ----------\n bucket_name: str\n S3 bucket of the object to delete.\n\n object_key: str\n Key name of the object to delete.\n\n verbose: bool, optional\n If True print messages... |
def upload_file_to_s3(bucket_name, local_file_path, bucket_rel_path):
'\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n local_file_path: str\n Local path to file we want to upload\n\n bucket_rel_path: str\n Path where file is uploaded, relative to S3... |
def get_s3_object(bucket_name, url):
'Uses a valid S3 bucket to retrieve a file from a remote AWS URL.\n Raises ValueError if non-existent.\n\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n url : str\n The remote URL of the object to be fetched\n\n Retur... |
def get_string_from_s3_file(bucket_name, url):
'Uses a valid S3 bucket to retrieve an UTF-8 decoded string from a remote AWS URL.\n Raises ValueError if non-existent.\n\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n url : str\n The remote URL of the object... |
def open_remote_json(s3_path):
'Loads a remote JSON file\n\n Parameters\n ----------\n s3_path: str\n Full s3 path to JSON file\n\n Returns\n -------\n dict:\n Loaded JSON\n '
assert (s3_path.startswith('s3://') and s3_path.endswith('.json'))
(bucket, rel_path) = convert... |
class RemoteArtifactFile():
def __init__(self, artifact):
'Context manager for a remote file on S3.\n\n Parameters\n ----------\n artifact : mgp.remote_pb2.RemoteArtifact\n Remote artifact object that contains the url and the sha1sum of the file\n\n url : str\n ... |
def list_prefixes_in_s3_dir(s3_path):
'\n List prefixes in S3 path.\n *CAVEAT*: This function was only tested for S3 path that contains purely one-level prefix, i.e. no regular objects.\n Parameters\n ----------\n s3_path: str\n An S3 path.\n Returns\n -------\n prefixes: List of st... |
def list_prefixes_in_s3(s3_prefix):
'\n List prefixes in S3 path.\n *CAVEAT*: This function was only tested for S3 prefix for files. E.g., if the bucket looks like the following,\n - s3://aa/bb/cc_v01.json\n - s3://aa/bb/cc_v02.json\n - s3://aa/bb/cc_v03.json\n then list_prefixes... |
def get_split_to_scenes(dataset):
'\n Retrieve a dictionary of split to scenes of a DGP-compliant scene dataset.\n\n Parameters\n ----------\n dataset: dgp.proto.dataset_pb2.SceneDataset\n SceneDataset proto object.\n\n Returns\n -------\n split_to_scene_json: dict\n A dictionar... |
def open_pbobject(path, pb_class):
'Load JSON as a protobuf (pb2) object.\n\n Any calls to load protobuf objects from JSON in this repository should be through this function.\n Returns `None` if the loading failed.\n\n Parameters\n ----------\n path: str\n Local JSON file path or remote scen... |
def parse_pbobject(source, pb_class):
'Like open_pboject but source can be a path or a bytestring\n\n Parameters\n ----------\n source: str or bytes\n Local JSON file path, remote s3 path to object, or bytestring of serialized object\n\n pb_class: object\n Protobuf pb2 object we want to ... |
def open_remote_pb_object(s3_object_uri, pb_class):
'Load JSON as a protobuf (pb2) object from S3 remote\n\n Parameters\n ----------\n s3_object_uri: str\n Remote scene dataset JSON URI.\n\n pb_class: object\n Protobuf pb2 object we want to load into.\n\n Returns\n ----------\n ... |
def save_pbobject_as_json(pb_object, save_path):
'\n Save protobuf (pb2) object to JSON file with our standard indent, key ordering, and other\n settings.\n\n Any calls to save protobuf objects to JSON in this repository should be through this function.\n\n Parameters\n ----------\n pb_object: o... |
def open_ontology_pbobject(ontology_file):
'Open ontology objects, first attempt to open V2 before trying V1.\n\n Parameters\n ----------\n ontology_file: str or bytes\n JSON ontology file path to load or bytestring.\n\n Returns\n -------\n ontology: Ontology object\n Desired Ontol... |
def open_feature_ontology_pbobject(ontology_file):
'Open feature ontology objects.\n\n Parameters\n ----------\n ontology_file: str\n JSON ontology file path to load.\n\n Returns\n -------\n ontology: FeatureOntology object\n Desired Feature Ontology pb2 object to be opened. Return... |
def generate_uid_from_pbobject(pb_object):
'Given a pb object, return the deterministic SHA1 hash hexdigest.\n Used for creating unique IDs.\n\n Parameters\n ----------\n pb_object: object\n A protobuf pb2 object to be hashed.\n\n Returns\n -------\n Hexdigest of annotation content\n ... |
def get_latest_scene(s3_scene_jsons):
"From a list of 'scene.json' and/or 'scene_<sha1>.json' paths in s3,\n return a Scene object for the one with the latest timestamp.\n Parameters\n ----------\n s3_scene_jsons: List[str]\n List of 'scene.json' or 'scene_<sha1>.json' paths in s3\n Returns\... |
def get_scene_statistics(scene, verbose=True):
'Given a DGP scene, return simple statistics (counts) of the scene.\n\n Parameters\n ----------\n scene: dgp.proto.scene_pb2.Scene\n Scene Object.\n\n verbose: bool, optional\n Print the stats if True. Default: True.\n\n Returns\n ----... |
def _get_bounding_box_annotation_info(annotation_enum):
'Returns datum_type, annotation_pb given an ontology\n Parameters\n ----------\n annotation_enum: dgp.proto.annotations_pb2.AnnotationType\n Annotation type enum\n\n Returns\n -------\n str, dgp.proto.annotations_pb2.[AnnotationClass... |
def get_scene_class_statistics(scene, scene_dir, annotation_enum, ontology=None):
'Given a DGP scene, return class counts of the annotations in the scene.\n\n Parameters\n ----------\n scene: dgp.proto.scene_pb2.Scene\n Scene Object.\n\n scene_dir: string\n s3 URL or local path to scene.... |
class BoundingBox2D():
'2D bounding box object.\n\n Parameters\n ----------\n box: np.ndarray[np.float32]\n Array of 4 floats describing bounding box coordinates. Can be either ([l, t, r, b] or [l, t, w, h]).\n\n class_id: int, default: GENERIC_OBJECT_CLASS\n Integer class ID (0 reserved... |
class InstanceMask2D():
'2D instance mask object.\n\n Parameters\n ----------\n mask: np.ndarray[bool, np.uint8, np.int64]\n 2D boolean array describiing instance mask.\n\n class_id: int, default: GENERIC_OBJECT_CLASS\n Integer class ID (0 reserved for background).\n\n instance_id: in... |
class RLEMask():
'Container of RLE-encoded mask.\n\n See https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/mask.py for RLE format.\n\n Parameters\n ----------\n size: list[int] or np.ndarray[int]\n Height and width of mask.\n counts: list[int]\n Count-encoding o... |
class KeyLine2D():
'2D keyline object.\n\n Parameters\n ----------\n line: np.ndarray[np.float32]\n Array of N*2 floats describing keyline coordinates [x, y].\n\n class_id: int, default: GENERIC_OBJECT_CLASS\n Integer class ID\n\n instance_id: int, default: None\n Unique instan... |
class KeyLine3D():
'3D keyline object.\n\n Parameters\n ----------\n line: np.ndarray[np.float32]\n Array of (N,3) floats describing keyline coordinates [x, y, z].\n\n class_id: int, default: GENERIC_OBJECT_CLASS_ID\n Integer class ID\n\n instance_id: int, default: None\n Uniqu... |
class KeyPoint2D():
'2D keypoint object.\n\n Parameters\n ----------\n point: np.ndarray[np.float32]\n Array of 2 floats describing keypoint coordinates [x, y].\n\n class_id: int, default: GENERIC_OBJECT_CLASS\n Integer class ID (0 reserved for background).\n\n instance_id: int, defau... |
class KeyPoint3D():
'3D keypoint object.\n\n Parameters\n ----------\n point: np.ndarray[np.float32]\n Array of 3 floats describing keypoint coordinates [x, y, z].\n\n class_id: int, default: GENERIC_OBJECT_CLASS_ID\n Integer class ID (0 reserved for background).\n\n instance_id: int,... |
def assert_between(value, low, high, low_inclusive=True, high_inclusive=True):
'\n Assert ``value`` is inside the specified range.\n Parameters\n ----------\n value : comparable\n Value to be asserted.\n\n low : comparable\n Range lower bound.\n\n high : comparable\n Range u... |
@lru_cache(maxsize=None)
def meshgrid(B, H, W, dtype, device, normalized=False):
'Create mesh-grid given batch size, height and width dimensions.\n\n Parameters\n ----------\n B: int\n Batch size\n H: int\n Grid Height\n W: int\n Batch size\n dtype: torch.dtype\n Tens... |
@lru_cache(maxsize=None)
def image_grid(B, H, W, dtype, device, normalized=False):
'Create an image mesh grid with shape B3HW given image shape BHW\n\n Parameters\n ----------\n B: int\n Batch size\n H: int\n Grid Height\n W: int\n Batch size\n dtype: str\n Tensor dty... |
def load_midas_net(name: str) -> tuple[(nn.Module, Compose)]:
'Load a frozen pre-trained Midas network from the PyTorch Hub.\n From: https://arxiv.org/abs/1907.01341 & https://arxiv.org/abs/2103.13413\n\n Pre-processing: ImageNet standarization & resizing (provided by `tfm`).\n Pre-processing: Bicubic re... |
class NewCRFDepth(nn.Module):
'\n Depth network based on neural window FC-CRFs architecture.\n '
def __init__(self, version=None, inv_depth=False, pretrained=None, frozen_stages=(- 1), min_depth=0.1, max_depth=100.0, **kwargs):
super().__init__()
self.inv_depth = inv_depth
self.... |
class DispHead(nn.Module):
def __init__(self, input_dim=100):
super(DispHead, self).__init__()
self.conv1 = nn.Conv2d(input_dim, 1, 3, padding=1)
self.sigmoid = nn.Sigmoid()
def forward(self, x, scale):
x = self.sigmoid(self.conv1(x))
if (scale > 1):
x = u... |
class DispUnpack(nn.Module):
def __init__(self, input_dim=100, hidden_dim=128):
super(DispUnpack, self).__init__()
self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1)
self.conv2 = nn.Conv2d(hidden_dim, 16, 3, padding=1)
self.relu = nn.ReLU(inplace=True)
self.sigmoi... |
def upsample(x, scale_factor=2, mode='bilinear', align_corners=False):
'Upsample input tensor by a factor of 2\n '
return F.interpolate(x, scale_factor=scale_factor, mode=mode, align_corners=align_corners)
|
def resize(input, size=None, scale_factor=None, mode='nearest', align_corners=None, warning=True):
if warning:
if ((size is not None) and align_corners):
(input_h, input_w) = tuple((int(x) for x in input.shape[2:]))
(output_h, output_w) = tuple((int(x) for x in size))
i... |
def normal_init(module, mean=0, std=1, bias=0):
if (hasattr(module, 'weight') and (module.weight is not None)):
nn.init.normal_(module.weight, mean, std)
if (hasattr(module, 'bias') and (module.bias is not None)):
nn.init.constant_(module.bias, bias)
|
def is_module_wrapper(module):
module_wrappers = (DataParallel, DistributedDataParallel)
return isinstance(module, module_wrappers)
|
def get_dist_info():
if (TORCH_VERSION < '1.0'):
initialized = dist._initialized
elif dist.is_available():
initialized = dist.is_initialized()
else:
initialized = False
if initialized:
rank = dist.get_rank()
world_size = dist.get_world_size()
else:
r... |
def load_state_dict(module, state_dict, strict=False, logger=None):
"Load state_dict to a module.\n\n This method is modified from :meth:`torch.nn.Module.load_state_dict`.\n Default value for ``strict`` is set to ``False`` and the message for\n param mismatch will be shown even if strict is False.\n\n ... |
def load_url_dist(url, model_dir=None):
'In distributed setting, this function only download checkpoint at local\n rank 0.'
(rank, world_size) = get_dist_info()
rank = int(os.environ.get('LOCAL_RANK', rank))
if (rank == 0):
checkpoint = model_zoo.load_url(url, model_dir=model_dir)
if (w... |
def get_torchvision_models():
model_urls = dict()
for (_, name, ispkg) in pkgutil.walk_packages(torchvision.models.__path__):
if ispkg:
continue
_zoo = import_module(f'torchvision.models.{name}')
if hasattr(_zoo, 'model_urls'):
_urls = getattr(_zoo, 'model_urls'... |
def _load_checkpoint(filename, map_location=None):
'Load checkpoint from somewhere (modelzoo, file, url).\n\n Args:\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for\n details.\n map_locatio... |
def load_checkpoint(model, filename, map_location='cpu', strict=False, logger=None):
'Load checkpoint from a file or URI.\n\n Args:\n model (Module): Module to load checkpoint.\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ... |
class PPM(nn.ModuleList):
'Pooling Pyramid Module used in PSPNet.\n\n Args:\n pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid\n Module.\n in_channels (int): Input channels.\n channels (int): Channels after modules, before conv_seg.\n conv_cfg (dict|None):... |
class BaseDecodeHead(nn.Module):
"Base class for BaseDecodeHead.\n\n Args:\n in_channels (int|Sequence[int]): Input channels.\n channels (int): Channels after modules, before conv_seg.\n num_classes (int): Number of classes.\n dropout_ratio (float): Ratio of dropout layer. Default: ... |
class UPerHead(BaseDecodeHead):
def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs):
super(UPerHead, self).__init__(input_transform='multiple_select', **kwargs)
self.lateral_convs = nn.ModuleList()
self.fpn_convs = nn.ModuleList()
for in_channels in self.in_channels:
... |
class PSP(BaseDecodeHead):
'Unified Perceptual Parsing for Scene Understanding.\n\n This head is the implementation of `UPerNet\n <https://arxiv.org/abs/1807.10221>`_.\n\n Args:\n pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid\n Module applied on the last feature. Defa... |
def load_newcrfs_net(scene: str, max_depth: Optional[float]=None) -> nn.Module:
'Load a frozen pre-trained NeWCRFs network.\n From https://arxiv.org/abs/2203.01502.\n\n Pre-processing: ImageNet standarization & resizing.\n\n Training shapes:\n - Outdoor: (Kitti) (352, 1216)\n - Indoor: (NYU... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.