id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
26,493
import argparse import torch from mmcv.runner import save_checkpoint from torch import nn as nn from mmdet3d.apis import init_model def parse_args(): parser = argparse.ArgumentParser( description='fuse Conv and BN layers in a model') parser.add_argument('config', help='config file path') parser.add...
null
26,495
from argparse import ArgumentParser, Namespace from pathlib import Path from tempfile import TemporaryDirectory import mmcv The provided code snippet includes necessary dependencies for implementing the `mmdet3d2torchserve` function. Write a Python function `def mmdet3d2torchserve( config_file: str, checkpoint...
Converts MMDetection3D model (config + checkpoint) to TorchServe `.mar`. Args: config_file (str): In MMDetection3D config format. The contents vary for each task repository. checkpoint_file (str): In MMDetection3D checkpoint format. The contents vary for each task repository. output_folder (str): Folder where `{model_n...
26,496
from argparse import ArgumentParser, Namespace from pathlib import Path from tempfile import TemporaryDirectory import mmcv def parse_args(): parser = ArgumentParser( description='Convert MMDetection models to TorchServe `.mar` format.') parser.add_argument('config', type=str, help='config file path') ...
null
26,497
import argparse import time from os import path as osp import mmcv import numpy as np from mmdet3d.core.bbox import limit_period def update_sunrgbd_infos(root_dir, out_dir, pkl_files): print(f'{pkl_files} will be modified because ' f'of the refactor of the Depth coordinate system.') if root_dir == ou...
null
26,498
import argparse import time from os import path as osp import mmcv import numpy as np from mmdet3d.core.bbox import limit_period def update_outdoor_dbinfos(root_dir, out_dir, pkl_files): print(f'{pkl_files} will be modified because ' f'of the refactor of the LIDAR coordinate system.') if root_dir == ...
null
26,499
import argparse import time from os import path as osp import mmcv import numpy as np from mmdet3d.core.bbox import limit_period def update_nuscenes_or_lyft_infos(root_dir, out_dir, pkl_files): print(f'{pkl_files} will be modified because ' f'of the refactor of the LIDAR coordinate system.') if root...
null
26,500
import numpy as np from mmdet.datasets.builder import PIPELINES from shapely.geometry import LineString def evaluate_line(polyline): edge = np.linalg.norm(polyline[1:] - polyline[:-1], axis=-1) start_end_weight = edge[(0, -1), ].copy() mid_weight = (edge[:-1] + edge[1:]) * .5 pts_weight = np.concate...
null
26,501
import numpy as np from mmdet.datasets.builder import PIPELINES from shapely.geometry import LineString The provided code snippet includes necessary dependencies for implementing the `quantize_verts` function. Write a Python function `def quantize_verts(verts, canvas_size, coord_dim)` to solve the following problem: C...
Convert vertices from its original range ([-1,1]) to discrete values in [0, n_bits**2 - 1]. Args: verts (array): vertices coordinates, shape (seqlen, coords_dim) canvas_size (tuple): bev feature size coord_dim (int): dimension of point coordinates Returns: quantized_verts (array): quantized vertices, shape (seqlen, coo...
26,502
import numpy as np from mmdet.datasets.builder import PIPELINES from shapely.geometry import LineString The provided code snippet includes necessary dependencies for implementing the `get_bbox` function. Write a Python function `def get_bbox(polyline, threshold)` to solve the following problem: Convert vertices from i...
Convert vertices from its original range ([-1,1]) to discrete values in [0, n_bits**2 - 1]. Args: polyline (array): point coordinates, shape (seqlen, 2) threshold (float): threshold for minimum bbox size Returns: bbox (array): bounding box in xyxy format, shape (2, 2)
26,503
import numpy as np from .distance import chamfer_distance, frechet_distance from typing import List, Tuple, Union from numpy.typing import NDArray The provided code snippet includes necessary dependencies for implementing the `average_precision` function. Write a Python function `def average_precision(recalls, precisi...
Calculate average precision. Args: recalls (ndarray): shape (num_dets, ) precisions (ndarray): shape (num_dets, ) mode (str): 'area' or '11points', 'area' means calculating the area under precision-recall curve, '11points' means calculating the average precision of recalls at [0, 0.1, ..., 1] Returns: float: calculated...
26,504
import numpy as np from .distance import chamfer_distance, frechet_distance from typing import List, Tuple, Union from numpy.typing import NDArray def chamfer_distance(line1: NDArray, line2: NDArray) -> float: ''' Calculate chamfer distance between two lines. Make sure the lines are interpolated. Args: ...
Compute whether detected lines are true positive or false positive. Args: pred_lines (List): Detected lines of a sample, each line has shape (INTERP_NUM, 2 or 3). scores (array): Confidence score of each line, of shape (M, ). gt_lines (List): GT lines of a sample, each line has shape (INTERP_NUM, 2 or 3). thresholds (l...
26,505
import torch from torch import nn as nn from torch.nn import functional as F from mmdet.models.losses import l1_loss from mmdet.models.losses.utils import weighted_loss import mmcv from mmdet.models.builder import LOSSES The provided code snippet includes necessary dependencies for implementing the `smooth_l1_loss` fu...
Smooth L1 loss. Args: pred (torch.Tensor): The prediction. target (torch.Tensor): The learning target of the prediction. beta (float, optional): The threshold in the piecewise function. Defaults to 1.0. Returns: torch.Tensor: Calculated loss
26,506
import torch from torch import nn as nn from torch.nn import functional as F from mmdet.models.losses import l1_loss from mmdet.models.losses.utils import weighted_loss import mmcv from mmdet.models.builder import LOSSES The provided code snippet includes necessary dependencies for implementing the `bce` function. Wri...
pred: B,nquery,npts label: B,nquery,npts
26,507
import torch from torch import nn as nn from torch.nn import functional as F from mmdet.models.losses import l1_loss from mmdet.models.losses.utils import weighted_loss import mmcv from mmdet.models.builder import LOSSES The provided code snippet includes necessary dependencies for implementing the `ce` function. Writ...
pred: B*nquery,npts label: B*nquery,
26,508
import mmcv import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import pad_sequence from torchvision.models.resnet import resnet18, resnet50 from mmdet3d.models.builder import (build_backbone, build_head, build_neck) from .bas...
null
26,509
import mmcv import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import pad_sequence from torchvision.models.resnet import resnet18, resnet50 from mmdet3d.models.builder import (build_backbone, build_head, build_neck) from .bas...
null
26,510
import copy import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from mmdet3d.models.builder import BACKBONES from mmdet.models import build_backbone, build_neck The provided code snippet includes necessary dependencies for implementing the `construct_plane_grid` function. ...
Returns: plane: H, W, 3
26,511
import copy import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from mmdet3d.models.builder import BACKBONES from mmdet.models import build_backbone, build_neck The provided code snippet includes necessary dependencies for implementing the `get_campos` function. Write a Py...
Find the each refence point's corresponding pixel in each camera Args: reference_points: [B, num_query, 3] ego2cam: (B, num_cam, 4, 4) Outs: reference_points_cam: (B*num_cam, num_query, 2) mask: (B, num_cam, num_query) num_query == W*H
26,512
import copy import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from mmdet3d.models.builder import BACKBONES from mmdet.models import build_backbone, build_neck def _test(): pass
null
26,513
import torch import torch.nn as nn from collections import OrderedDict import torch.utils.checkpoint as checkpoint from timm.models.layers import trunc_normal_, DropPath from mmcv.runner import _load_checkpoint from mmcv.cnn import constant_init, trunc_normal_init from mmseg.utils import get_root_logger from ops_dcnv3 ...
null
26,514
import torch import torch.nn as nn from collections import OrderedDict import torch.utils.checkpoint as checkpoint from timm.models.layers import trunc_normal_, DropPath from mmcv.runner import _load_checkpoint from mmcv.cnn import constant_init, trunc_normal_init from mmseg.utils import get_root_logger from ops_dcnv3 ...
null
26,515
import torch from mmdet.core.bbox.match_costs.builder import MATCH_COST from mmdet.core.bbox.match_costs import build_match_cost from mmdet.core.bbox.iou_calculators import bbox_overlaps from mmdet.core.bbox.transforms import bbox_cxcywh_to_xyxy The provided code snippet includes necessary dependencies for implementin...
Args: pred: [num_points, 2] gt: [num_gt, 2] Out: torch.FloatTensor of shape (1, )
26,516
import copy import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import Conv2d, Linear from mmcv.runner import force_fp32 from torch.distributions.categorical import Categorical from mmdet.core import multi_apply, reduce_mean from mmdet.models import HEADS from .detr_head import DETRMapFixed...
null
26,517
import torch import torch.nn.functional as F from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `generate_square_subsequent_mask` function. Write a Python function `def generate_square_subsequent_mask(sz: int, condition_len: int = 1, bool_out=False, device: str = "c...
Generate the attention mask for causal decoding
26,518
import torch import torch.nn.functional as F from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `dequantize_verts` function. Write a Python function `def dequantize_verts(verts, canvas_size: Tensor, add_noise=False)` to solve the following problem: Quantizes vertice...
Quantizes vertices and outputs integers with specified n_bits.
26,519
import torch import torch.nn.functional as F from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `quantize_verts` function. Write a Python function `def quantize_verts( verts, canvas_size: Tensor)` to solve the following problem: Convert vertices from...
Convert vertices from its original range ([-1,1]) to discrete values in [0, n_bits**2 - 1]. Args: verts: seqlen, 2
26,520
import torch import torch.nn.functional as F from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `top_k_logits` function. Write a Python function `def top_k_logits(logits, k)` to solve the following problem: Masks logits such that logits not in top-k are small. Here...
Masks logits such that logits not in top-k are small.
26,521
import torch import torch.nn.functional as F from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `top_p_logits` function. Write a Python function `def top_p_logits(logits, p)` to solve the following problem: Masks logits using nucleus (top-p) sampling. Here is the f...
Masks logits using nucleus (top-p) sampling.
26,522
import torch import torch.nn as nn from typing import Optional from torch import Tensor from mmcv.cnn.bricks.registry import ATTENTION from mmcv.utils import build_from_cfg The provided code snippet includes necessary dependencies for implementing the `build_attention` function. Write a Python function `def build_atte...
Builder for attention.
26,523
import torch import torch.nn as nn from typing import Optional from torch import Tensor from mmcv.cnn.bricks.registry import ATTENTION from mmcv.utils import build_from_cfg The provided code snippet includes necessary dependencies for implementing the `generate_square_subsequent_mask` function. Write a Python function...
Generate the attention mask for causal decoding
26,524
import copy import torch import torch.nn as nn from mmcv.cnn import Linear, bias_init_with_prob, build_activation_layer from mmcv.cnn.bricks.transformer import build_positional_encoding from mmcv.runner import force_fp32 from mmdet.models import HEADS, build_head, build_loss from mmdet.models.utils import build_transfo...
null
26,525
import math import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions.categorical import Categorical from mmdet.models import HEADS from .detgen_utils.causal_trans import (CausalTransformerDecoder, CausalTransformerDecoderLayer) from .detgen_utils.utils impor...
null
26,526
import math import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions.categorical import Categorical from mmdet.models import HEADS from .detgen_utils.causal_trans import (CausalTransformerDecoder, CausalTransformerDecoderLayer) from .detgen_utils.utils impor...
null
26,527
import math import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions.categorical import Categorical from mmdet.models import HEADS from .detgen_utils.causal_trans import (CausalTransformerDecoder, CausalTransformerDecoderLayer) from .detgen_utils.utils impor...
null
26,528
from turtle import forward import warnings from mmcv.runner import force_fp32, auto_fp16 from mmcv.cnn.bricks.registry import ATTENTION from mmcv.runner.base_module import BaseModule, ModuleList, Sequential from mmcv.cnn.bricks.transformer import build_attention import math import warnings import torch import torch.nn ...
CPU version of multi-scale deformable attention. Args: value (Tensor): The value has shape (bs, num_keys, mum_heads, embed_dims//num_heads) value_spatial_shapes (Tensor): Spatial shape of each feature map, has shape (num_levels, 2), last dimension 2 represent (h, w) sampling_locations (Tensor): The location of sampling...
26,529
import math import warnings import torch import torch.nn as nn from mmcv.cnn import build_activation_layer, build_norm_layer, xavier_init from mmcv.cnn.bricks.registry import (TRANSFORMER_LAYER, TRANSFORMER_LAYER_SEQUENCE) from mmcv.cnn.bricks.transformer import (BaseTransformerLay...
Inverse function of sigmoid. Args: x (Tensor): The tensor to do the inverse. eps (float): EPS avoid numerical overflow. Defaults 1e-5. Returns: Tensor: The x has passed the inverse function of sigmoid, has same shape with input.
26,530
from __future__ import division import argparse import copy import mmcv import os import time import torch import warnings from mmcv import Config, DictAction from mmcv.runner import get_dist_info, init_dist from os import path as osp from mmdet import __version__ as mmdet_version from mmdet3d import __version__ as mmd...
null
26,531
import random import warnings import numpy as np import torch from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import (HOOKS, DistSamplerSeedHook, EpochBasedRunner, Fp16OptimizerHook, OptimizerHook, build_optimizer, build_runner) from...
Set random seed. Args: seed (int): Seed to be used. deterministic (bool): Whether to set the deterministic option for CUDNN backend, i.e., set `torch.backends.cudnn.deterministic` to True and `torch.backends.cudnn.benchmark` to False. Default: False.
26,532
import random import warnings import numpy as np import torch from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import (HOOKS, DistSamplerSeedHook, EpochBasedRunner, Fp16OptimizerHook, OptimizerHook, build_optimizer, build_runner) from...
null
26,533
import argparse import mmcv from mmcv import Config import os from renderer import Renderer def parse_args(): parser = argparse.ArgumentParser( description='Visualize groundtruth and results') parser.add_argument('log_id', type=str, help='log_id of data to visualize') parser.add_argume...
null
26,534
import argparse import mmcv from mmcv import Config import os from renderer import Renderer The provided code snippet includes necessary dependencies for implementing the `import_plugin` function. Write a Python function `def import_plugin(cfg)` to solve the following problem: import modules, registry will be update ...
import modules, registry will be update
26,535
import os.path as osp import os import numpy as np import copy import cv2 import matplotlib.pyplot as plt from PIL import Image from shapely.geometry import LineString def points_ego2img(pts_ego, extrinsics, intrinsics): pts_ego_4d = np.concatenate([pts_ego, np.ones([len(pts_ego), 1])], axis=-1) pts_cam_4d = ex...
null
26,536
import sys import os from src.datasets.evaluation.vector_eval import VectorEvaluate import argparse def parse_args(): parser = argparse.ArgumentParser( description='Evaluate a submission file') parser.add_argument('submission', help='submission file in pickle or json format to be eval...
null
26,537
import torch def normalize_bbox(bboxes, pc_range): cx = bboxes[..., 0:1] cy = bboxes[..., 1:2] cz = bboxes[..., 2:3] w = bboxes[..., 3:4].log() l = bboxes[..., 4:5].log() h = bboxes[..., 5:6].log() rot = bboxes[..., 6:7] if bboxes.size(-1) > 7: vx = bboxes[..., 7:8] v...
null
26,539
import bisect import os.path as osp import mmcv import torch.distributed as dist from mmcv.runner import DistEvalHook as BaseDistEvalHook from mmcv.runner import EvalHook as BaseEvalHook from torch.nn.modules.batchnorm import _BatchNorm from mmdet.core.evaluation.eval_hooks import DistEvalHook def _calc_dynamic_interv...
null
26,540
from mmcv.ops.multi_scale_deform_attn import multi_scale_deformable_attn_pytorch import mmcv import cv2 as cv import copy import warnings from matplotlib import pyplot as plt import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import xavier_init, constant_init from mmcv.c...
Inverse function of sigmoid. Args: x (Tensor): The tensor to do the inverse. eps (float): EPS avoid numerical overflow. Defaults 1e-5. Returns: Tensor: The x has passed the inverse function of sigmoid, has same shape with input.
26,541
from .mmdet_train import custom_train_detector from mmseg.apis import train_segmentor from mmdet.apis import train_detector def custom_train_detector(model, dataset, cfg, distributed=False, validate=False, timestamp=None, ...
A function wrapper for launching model training according to cfg. Because we need different eval_hook in runner. Should be deprecated in the future.
26,542
from .mmdet_train import custom_train_detector from mmseg.apis import train_segmentor from mmdet.apis import train_detector The provided code snippet includes necessary dependencies for implementing the `train_model` function. Write a Python function `def train_model(model, dataset, cfg...
A function wrapper for launching model training according to cfg. Because we need different eval_hook in runner. Should be deprecated in the future.
26,545
import json from mmcv.runner import OPTIMIZER_BUILDERS, DefaultOptimizerConstructor from mmcv.runner import get_dist_info from mmdet.utils import get_root_logger def get_num_layer_for_swin(var_name, num_max_layer, depths): if var_name.startswith("img_backbone.patch_embed"): return 0 elif "level_embeds"...
null
26,546
from __future__ import absolute_import from __future__ import print_function from __future__ import division import warnings import torch from torch import nn import torch.nn.functional as F from torch.nn.init import xavier_uniform_, constant_ from ..functions import DCNv3Function, dcnv3_core_pytorch class to_channels_...
null
26,550
from __future__ import absolute_import from __future__ import print_function from __future__ import division import torch import torch.nn.functional as F from torch.autograd import Function from torch.autograd.function import once_differentiable from torch.cuda.amp import custom_bwd, custom_fwd import DCNv3 def _get_re...
null
26,551
import numpy as np import os from pathlib import Path from tqdm import tqdm import pickle as pkl import argparse import time import torch import sys, platform from sklearn.neighbors import KDTree from termcolor import colored from pathlib import Path from copy import deepcopy from functools import reduce The provided ...
Produces a colored string for printing Parameters ---------- string : str String that will be colored color : str Color to use on_color : str Background color to use attrs : list of str Different attributes for the string Returns ------- string: str Colored string
26,552
import numpy as np import os from pathlib import Path from tqdm import tqdm import pickle as pkl import argparse import time import torch import sys, platform from sklearn.neighbors import KDTree from termcolor import colored from pathlib import Path from copy import deepcopy from functools import reduce np.seterr(divi...
null
26,553
import numpy as np import os from pathlib import Path from tqdm import tqdm import pickle as pkl import argparse import time import torch import sys, platform from sklearn.neighbors import KDTree from termcolor import colored from pathlib import Path from copy import deepcopy from functools import reduce np.seterr(divi...
null
26,554
import argparse import copy import json import os import time from typing import Tuple, Dict, Any import torch import numpy as np from nuscenes import NuScenes from nuscenes.eval.common.config import config_factory from nuscenes.eval.common.data_classes import EvalBoxes from nuscenes.eval.detection.data_classes import ...
Plot the true positive curve for the specified class. :param md_list: DetectionMetricDataList instance. :param metrics: DetectionMetrics instance. :param detection_name: :param min_recall: Minimum recall value. :param dist_th_tp: The distance threshold used to determine matches. :param savepath: If given, saves the the...
26,555
import argparse import copy import json import os import time from typing import Tuple, Dict, Any import torch import numpy as np from nuscenes import NuScenes from nuscenes.eval.common.config import config_factory from nuscenes.eval.common.data_classes import EvalBoxes from nuscenes.eval.detection.data_classes import ...
Check if a box is visible in images but not all corners in image . :param box: The box to be checked. :param intrinsic: <float: 3, 3>. Intrinsic camera matrix. :param imsize: (width, height). :param vis_level: One of the enumerations of <BoxVisibility>. :return True if visibility condition is satisfied.
26,556
import argparse import copy import json import os import time from typing import Tuple, Dict, Any import torch import numpy as np from nuscenes import NuScenes from nuscenes.eval.common.config import config_factory from nuscenes.eval.common.data_classes import EvalBoxes from nuscenes.eval.detection.data_classes import ...
Loads ground truth boxes from DB. :param nusc: A NuScenes instance. :param eval_split: The evaluation split for which we load GT boxes. :param box_cls: Type of box to load, e.g. DetectionBox or TrackingBox. :param verbose: Whether to print messages to stdout. :return: The GT boxes.
26,557
import argparse import copy import json import os import time from typing import Tuple, Dict, Any import torch import numpy as np from nuscenes import NuScenes from nuscenes.eval.common.config import config_factory from nuscenes.eval.common.data_classes import EvalBoxes from nuscenes.eval.detection.data_classes import ...
Applies filtering to boxes. Distance, bike-racks and points per box. :param nusc: An instance of the NuScenes class. :param eval_boxes: An instance of the EvalBoxes class. :param is: the anns token set that used to keep bboxes. :param verbose: Whether to print to stdout.
26,558
import argparse import copy import json import os import time from typing import Tuple, Dict, Any import torch import numpy as np from nuscenes import NuScenes from nuscenes.eval.common.config import config_factory from nuscenes.eval.common.data_classes import EvalBoxes from nuscenes.eval.detection.data_classes import ...
Applies filtering to boxes. Distance, bike-racks and points per box. :param nusc: An instance of the NuScenes class. :param eval_boxes: An instance of the EvalBoxes class. :param is: the anns token set that used to keep bboxes. :param verbose: Whether to print to stdout.
26,559
import argparse import copy import json import os import time from typing import Tuple, Dict, Any import torch import numpy as np from nuscenes import NuScenes from nuscenes.eval.common.config import config_factory from nuscenes.eval.common.data_classes import EvalBoxes from nuscenes.eval.detection.data_classes import ...
null
26,560
import argparse import copy import json import os import time from typing import Tuple, Dict, Any import torch import numpy as np from nuscenes import NuScenes from nuscenes.eval.common.config import config_factory from nuscenes.eval.common.data_classes import EvalBoxes from nuscenes.eval.detection.data_classes import ...
Applies filtering to boxes. basedon overlap . :param nusc: An instance of the NuScenes class. :param eval_boxes: An instance of the EvalBoxes class. :param verbose: Whether to print to stdout.
26,561
from collections import OrderedDict from mmcv.runner import BaseModule from mmdet.models.builder import BACKBONES import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.batchnorm import _BatchNorm The provided code snippet includes necessary dependencies for implementing the `dw_conv3...
3x3 convolution with padding
26,562
from collections import OrderedDict from mmcv.runner import BaseModule from mmdet.models.builder import BACKBONES import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.batchnorm import _BatchNorm The provided code snippet includes necessary dependencies for implementing the `conv3x3`...
3x3 convolution with padding
26,563
from collections import OrderedDict from mmcv.runner import BaseModule from mmdet.models.builder import BACKBONES import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.batchnorm import _BatchNorm The provided code snippet includes necessary dependencies for implementing the `conv1x1`...
1x1 convolution with padding
26,564
import torch from torchvision.utils import make_grid import torchvision import matplotlib.pyplot as plt import cv2 def convert_color(img_path): plt.figure() img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) plt.imsave(img_path, img, cmap=plt.get_cmap('viridis')) plt.close() def save_tensor(tensor, path,...
null
26,565
import functools import time from collections import defaultdict import torch time_maps = defaultdict(lambda :0.) count_maps = defaultdict(lambda :0.) def run_time(name): def middle(fn): def wrapper(*args, **kwargs): torch.cuda.synchronize() start = time.time() res = fn(...
null
26,566
from __future__ import division import argparse import copy import mmcv import os import time import torch import warnings from mmcv import Config, DictAction from mmcv.runner import get_dist_info, init_dist from os import path as osp from mmdet import __version__ as mmdet_version from mmdet3d import __version__ as mmd...
null
26,567
from data_converter.create_gt_database import create_groundtruth_database from data_converter import nuscenes_converter as nuscenes_converter from data_converter import nuscenes_occ_converter as occ_converter import argparse from os import path as osp import sys The provided code snippet includes necessary dependencie...
Prepare data related to nuScenes dataset. Related data consists of '.pkl' files recording basic infos, 2D annotations and groundtruth database. Args: root_path (str): Path of dataset root. info_prefix (str): The prefix of info filenames. version (str): Dataset version. dataset_name (str): The dataset class name. out_di...
26,568
from data_converter.create_gt_database import create_groundtruth_database from data_converter import nuscenes_converter as nuscenes_converter from data_converter import nuscenes_occ_converter as occ_converter import argparse from os import path as osp import sys The provided code snippet includes necessary dependencie...
Prepare occ data related to nuScenes dataset. Related data consists of '.pkl' files recording basic infos, 2D annotations and groundtruth database. Args: root_path (str): Path of dataset root. info_prefix (str): The prefix of info filenames. version (str): Dataset version. dataset_name (str): The dataset class name. ou...
26,569
import mmcv from nuscenes.nuscenes import NuScenes from PIL import Image from nuscenes.utils.geometry_utils import view_points, box_in_image, BoxVisibility, transform_matrix from typing import Tuple, List, Iterable import matplotlib.pyplot as plt import numpy as np from PIL import Image from matplotlib import rcParams ...
Render selected annotation. :param anntoken: Sample_annotation token. :param margin: How many meters in each direction to include in LIDAR view. :param view: LIDAR view point. :param box_vis_level: If sample_data is an image, this sets required visibility for boxes. :param out_path: Optional path to save the rendered f...
26,570
import mmcv from nuscenes.nuscenes import NuScenes from PIL import Image from nuscenes.utils.geometry_utils import view_points, box_in_image, BoxVisibility, transform_matrix from typing import Tuple, List, Iterable import matplotlib.pyplot as plt import numpy as np from PIL import Image from matplotlib import rcParams ...
Render sample data onto axis. :param sample_data_token: Sample_data token. :param with_anns: Whether to draw box annotations. :param box_vis_level: If sample_data is an image, this sets required visibility for boxes. :param axes_limit: Axes limit for lidar and radar (measured in meters). :param ax: Axes onto which to r...
26,571
import argparse import json import numpy as np import seaborn as sns from collections import defaultdict from matplotlib import pyplot as plt def cal_train_time(log_dicts, args): for i, log_dict in enumerate(log_dicts): print(f'{"-" * 5}Analyze train time of {args.json_logs[i]}{"-" * 5}') all_times...
null
26,572
import argparse import json import numpy as np import seaborn as sns from collections import defaultdict from matplotlib import pyplot as plt def plot_curve(log_dicts, args): if args.backend is not None: plt.switch_backend(args.backend) sns.set_style(args.style) # if legend is None, use {filename}_...
null
26,573
import argparse import json import numpy as np import seaborn as sns from collections import defaultdict from matplotlib import pyplot as plt def add_plot_parser(subparsers): def add_time_parser(subparsers): def parse_args(): parser = argparse.ArgumentParser(description='Analyze Json Log') # currently only sup...
null
26,574
import argparse import json import numpy as np import seaborn as sns from collections import defaultdict from matplotlib import pyplot as plt def load_json_logs(json_logs): # load and convert json_logs to log_dict, key is epoch, value is a sub dict # keys of sub dict is different metrics, e.g. memory, bbox_mAP...
null
26,575
import argparse import time import torch from mmcv import Config from mmcv.parallel import MMDataParallel from mmcv.runner import load_checkpoint, wrap_fp16_model import sys from projects.mmdet3d_plugin.datasets.builder import build_dataloader from projects.mmdet3d_plugin.datasets import custom_build_dataset from mmdet...
null
26,578
import argparse import torch from collections import OrderedDict def convert_stem(model_key, model_weight, state_dict, converted_names): new_key = model_key.replace('stem.conv', 'conv1') new_key = new_key.replace('stem.bn', 'bn1') state_dict[new_key] = model_weight converted_names.add(model_key) pri...
Convert keys in pycls pretrained RegNet models to mmdet style.
26,581
import mmcv import numpy as np import os from collections import OrderedDict from nuscenes.nuscenes import NuScenes from nuscenes.utils.geometry_utils import view_points from os import path as osp from pyquaternion import Quaternion from shapely.geometry import MultiPoint, box from typing import List, Tuple, Union from...
Create info file of nuscene dataset. Given the raw data, generate its related info file in pkl format. Args: root_path (str): Path of the data root. info_prefix (str): Prefix of the info file to be generated. version (str): Version of the data. Default: 'v1.0-trainval' max_sweeps (int): Max number of sweeps. Default: 1...
26,582
import mmcv import numpy as np import os from collections import OrderedDict from nuscenes.nuscenes import NuScenes from nuscenes.utils.geometry_utils import view_points from os import path as osp from pyquaternion import Quaternion from shapely.geometry import MultiPoint, box from typing import List, Tuple, Union from...
Export 2d annotation from the info file and raw data. Args: root_path (str): Root path of the raw data. info_path (str): Path of the info file. version (str): Dataset version. mono3d (bool): Whether to export mono3d annotation. Default: True.
26,583
import mmcv import numpy as np import pickle from mmcv import track_iter_progress from mmcv.ops import roi_align from os import path as osp from pycocotools import mask as maskUtils from pycocotools.coco import COCO from mmdet3d.core.bbox import box_np_ops as box_np_ops from mmdet3d.datasets import build_dataset from m...
null
26,584
import mmcv import numpy as np import pickle from mmcv import track_iter_progress from mmcv.ops import roi_align from os import path as osp from pycocotools import mask as maskUtils from pycocotools.coco import COCO from mmdet3d.core.bbox import box_np_ops as box_np_ops from mmdet3d.datasets import build_dataset from m...
Given the raw data, generate the ground truth database. Args: dataset_class_name (str): Name of the input dataset. data_path (str): Path of the data. info_prefix (str): Prefix of the info file. info_path (str): Path of the info file. Default: None. mask_anno_path (str): Path of the mask_anno. Default: None. used_classe...
26,585
from __future__ import division import argparse import copy import mmcv import os import time import torch import warnings from mmcv import Config, DictAction from mmcv.runner import get_dist_info, init_dist, wrap_fp16_model from os import path as osp from mmdet import __version__ as mmdet_version from mmdet3d import _...
null
26,586
import argparse import numpy as np import warnings from mmcv import Config, DictAction, mkdir_or_exist, track_iter_progress from os import path as osp from mmdet3d.core.bbox import (Box3DMode, CameraInstance3DBoxes, Coord3DMode, DepthInstance3DBoxes, LiDARInstance3DBoxes) from mmdet3d.cor...
null
26,587
import argparse import numpy as np import warnings from mmcv import Config, DictAction, mkdir_or_exist, track_iter_progress from os import path as osp from mmdet3d.core.bbox import (Box3DMode, CameraInstance3DBoxes, Coord3DMode, DepthInstance3DBoxes, LiDARInstance3DBoxes) from mmdet3d.cor...
Build data config for loading visualization data.
26,588
import argparse import numpy as np import warnings from mmcv import Config, DictAction, mkdir_or_exist, track_iter_progress from os import path as osp from mmdet3d.core.bbox import (Box3DMode, CameraInstance3DBoxes, Coord3DMode, DepthInstance3DBoxes, LiDARInstance3DBoxes) from mmdet3d.cor...
Visualize 3D point cloud and 3D bboxes.
26,589
import argparse import numpy as np import warnings from mmcv import Config, DictAction, mkdir_or_exist, track_iter_progress from os import path as osp from mmdet3d.core.bbox import (Box3DMode, CameraInstance3DBoxes, Coord3DMode, DepthInstance3DBoxes, LiDARInstance3DBoxes) from mmdet3d.cor...
Visualize 3D point cloud and segmentation mask.
26,590
import argparse import numpy as np import warnings from mmcv import Config, DictAction, mkdir_or_exist, track_iter_progress from os import path as osp from mmdet3d.core.bbox import (Box3DMode, CameraInstance3DBoxes, Coord3DMode, DepthInstance3DBoxes, LiDARInstance3DBoxes) from mmdet3d.cor...
Visualize 3D bboxes on 2D image by projection.
26,592
import argparse import torch from mmcv.runner import save_checkpoint from torch import nn as nn from mmdet.apis import init_model def fuse_conv_bn(conv, bn): def fuse_module(m): last_conv = None last_conv_name = None for name, child in m.named_children(): if isinstance(child, (nn.BatchNorm2d, nn.S...
null
26,593
import argparse import torch from mmcv.runner import save_checkpoint from torch import nn as nn from mmdet.apis import init_model def parse_args(): parser = argparse.ArgumentParser( description='fuse Conv and BN layers in a model') parser.add_argument('config', help='config file path') parser.add_a...
null
26,595
import open3d as o3d import pickle import numpy as np import torch import math from pathlib import Path import os from glob import glob The provided code snippet includes necessary dependencies for implementing the `rotz` function. Write a Python function `def rotz(t)` to solve the following problem: Rotation about th...
Rotation about the z-axis.
26,596
import open3d as o3d import pickle import numpy as np import torch import math from pathlib import Path import os from glob import glob color = colors_map[:, :3] / 255 def voxel2points(voxel, voxelSize, range=[-40.0, -40.0, -1.0, 40.0, 40.0, 5.4], ignore_labels=[17, 255]): if isinstance(voxel, np.ndarray): voxel = ...
null
26,597
import argparse import copy import os import os.path as osp import time import warnings import mmcv import torch import torch.distributed as dist from mmcv.cnn.utils import revert_sync_batchnorm from mmcv.runner import get_dist_info, init_dist from mmcv.utils import Config, DictAction, get_git_hash from mmseg import __...
null
26,598
from argparse import ArgumentParser import mmcv import mmcv_custom import mmseg_custom from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot from mmseg.core.evaluation import get_palette from mmcv.runner import load_checkpoint from mmseg.core import get_classes import cv2 import os.path as ...
null
26,599
import argparse import numpy as np import torch from mmcv import Config, DictAction from mmseg.models import build_segmentor import mmcv_custom import mmseg_custom def parse_args(): parser = argparse.ArgumentParser(description='Train a detector') parser.add_argument('config', help='train config file path') ...
null
26,600
import argparse import numpy as np import torch from mmcv import Config, DictAction from mmseg.models import build_segmentor import mmcv_custom import mmseg_custom def dcnv3_flops(n, k, c): return 5 * n * k * c if __name__ == '__main__': args = parse_args() if len(args.shape) == 1: h = w = args....
null
26,601
import argparse import logging import os import os.path as osp from functools import partial import mmcv import torch.multiprocessing as mp from torch.multiprocessing import Process, set_start_method from mmdeploy.apis import (create_calib_input_data, extract_model, get_predefined_partition_c...
null
26,602
import argparse import logging import os import os.path as osp from functools import partial import mmcv import torch.multiprocessing as mp from torch.multiprocessing import Process, set_start_method from mmdeploy.apis import (create_calib_input_data, extract_model, get_predefined_partition_c...
null
26,603
import argparse import logging import os import os.path as osp from functools import partial import mmcv import torch.multiprocessing as mp from torch.multiprocessing import Process, set_start_method from mmdeploy.apis import (create_calib_input_data, extract_model, get_predefined_partition_c...
Return the conversion function from torch to the intermediate representation. Args: ir_type (IR): The type of the intermediate representation.
26,604
from __future__ import absolute_import from __future__ import print_function from __future__ import division import warnings import torch from torch import nn import torch.nn.functional as F from torch.nn.init import xavier_uniform_, constant_ from ..functions import DCNv3Function, dcnv3_core_pytorch import math class ...
null
26,605
from __future__ import absolute_import from __future__ import print_function from __future__ import division import warnings import torch from torch import nn import torch.nn.functional as F from torch.nn.init import xavier_uniform_, constant_ from ..functions import DCNv3Function, dcnv3_core_pytorch import math def b...
null