id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
15,175 | import random
import torch
import torch.nn.functional as F
from damo.augmentations.box_level_augs.gaussian_maps import _merge_gaussian
def blend(image1, image2, factor):
"""Blend image1 and image2 using 'factor'.
Factor can be above 0.0. A value of 0.0 means only image1 is used.
A value of 1.0 means only i... | Equivalent of PIL Brightness. |
15,176 | import random
import torch
import torch.nn.functional as F
from damo.augmentations.box_level_augs.gaussian_maps import _merge_gaussian
def blend(image1, image2, factor):
"""Blend image1 and image2 using 'factor'.
Factor can be above 0.0. A value of 0.0 means only image1 is used.
A value of 1.0 means only i... | Implements Sharpness function from PIL using TF ops. |
15,177 | import random
import torch
import torch.nn.functional as F
from damo.augmentations.box_level_augs.gaussian_maps import _merge_gaussian
The provided code snippet includes necessary dependencies for implementing the `equalize` function. Write a Python function `def equalize(image)` to solve the following problem:
Implem... | Implements Equalize function from PIL using PyTorch ops based on: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/ autoaugment.py#L352 |
15,178 | import random
import torch
import torch.nn.functional as F
from damo.augmentations.box_level_augs.gaussian_maps import _merge_gaussian
def autocontrast(image):
def scale_channel(image):
"""Scale the 2D image using the autocontrast rule."""
lo = torch.min(image)
hi = torch.max(image)
... | null |
15,179 | import random
import torch
import torch.nn.functional as F
from damo.augmentations.box_level_augs.gaussian_maps import _merge_gaussian
The provided code snippet includes necessary dependencies for implementing the `posterize` function. Write a Python function `def posterize(image, bits)` to solve the following problem... | Equivalent of PIL Posterize. |
15,180 | import random
import torch
import torch.nn.functional as F
from damo.augmentations.box_level_augs.gaussian_maps import _merge_gaussian
def _merge_gaussian(img, img_aug, boxes, scale_ratios, scale_splits):
g_maps = _gaussian_map(img, boxes, scale_splits, scale_ratios)
g_maps = g_maps.clamp(min=0, max=1.0)
o... | null |
15,181 | import torch
from .bounding_box import BoxList
The provided code snippet includes necessary dependencies for implementing the `remove_small_boxes` function. Write a Python function `def remove_small_boxes(boxlist, min_size)` to solve the following problem:
Only keep boxes with both sides >= min_size Arguments: boxlist... | Only keep boxes with both sides >= min_size Arguments: boxlist (Boxlist) min_size (int) |
15,182 | import torch
from .bounding_box import BoxList
def _cat(tensors, dim=0):
"""
Efficient version of torch.cat that avoids a copy if there is only
a single element in a list
"""
assert isinstance(tensors, (list, tuple))
if len(tensors) == 1:
return tensors[0]
return torch.cat(tensors, d... | Concatenates a list of BoxList (having the same image size) into a single BoxList Arguments: bboxes (list[BoxList]) |
15,183 | import os
import torch
from loguru import logger
from tqdm import tqdm
from damo.dataset.datasets.evaluation import evaluate
from damo.utils import all_gather, get_world_size, is_main_process, synchronize
from damo.utils.timer import Timer, get_time_str
def compute_on_dataset(model, data_loader, device, timer=None, tta... | null |
15,184 | import datetime
import math
import os
import random
import time
from copy import deepcopy
import numpy as np
import torch
import torch.nn as nn
from loguru import logger
from torch.nn.parallel import DistributedDataParallel as DDP
from damo.apis.detector_inference import inference
from damo.base_models.losses.distill_l... | null |
15,185 | import datetime
import math
import os
import random
import time
from copy import deepcopy
import numpy as np
import torch
import torch.nn as nn
from loguru import logger
from torch.nn.parallel import DistributedDataParallel as DDP
from damo.apis.detector_inference import inference
from damo.base_models.losses.distill_l... | null |
15,186 | import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..core.bbox_calculator import bbox_overlaps
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
"""Apply element-wise weight and reduce loss.
Args:
loss (Tensor): Element-wise loss.
... | Create a weighted version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated... |
15,187 | import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..core.bbox_calculator import bbox_overlaps
def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False, eps=1e-6):
"""Calculate overlap between two set of bboxes.
If ``is_aligned `` is ``False``, then calculate the o... | r"""`Generalized Intersection over Union: A Metric and A Loss for Bounding Box Regression <https://arxiv.org/abs/1902.09630>`_. Args: pred (torch.Tensor): Predicted bboxes of format (x1, y1, x2, y2), shape (n, 4). target (torch.Tensor): Corresponding gt bboxes, shape (n, 4). eps (float): Eps to avoid log(0). Return: Te... |
15,188 | import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..core.bbox_calculator import bbox_overlaps
The provided code snippet includes necessary dependencies for implementing the `distribution_focal_loss` function. Write a Python function `def distribution_focal_loss(pred, label)` to s... | r"""Distribution Focal Loss (DFL) is from `Generalized Focal Loss: Learning Qualified and Distributed Bounding Boxes for Dense Object Detection <https://arxiv.org/abs/2006.04388>`_. Args: pred (torch.Tensor): Predicted general distribution of bounding boxes (before softmax) with shape (N, n+1), n is the max value of th... |
15,189 | import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..core.bbox_calculator import bbox_overlaps
The provided code snippet includes necessary dependencies for implementing the `quality_focal_loss` function. Write a Python function `def quality_focal_loss(pred, target, beta=2.0, use_... | r"""Quality Focal Loss (QFL) is from `Generalized Focal Loss: Learning Qualified and Distributed Bounding Boxes for Dense Object Detection <https://arxiv.org/abs/2006.04388>`_. Args: pred (torch.Tensor): Predicted joint representation of classification and quality (IoU) estimation with shape (N, C), C is the number of ... |
15,190 | import torch
import torch.nn as nn
from ..core.ops import Focus, RepConv, SPPBottleneck, get_activation
class TinyNAS(nn.Module):
def __init__(self,
structure_info=None,
out_indices=[2, 4, 5],
with_spp=False,
use_focus=False,
act='... | null |
15,191 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from ..core.ops import Focus, RepConv, SPPBottleneck, get_activation, DepthwiseConv
from damo.utils import make_divisible
def depthwise_conv(i, o, kernel_size, stride=1, padding=0, bias=False):
return nn.Conv2d(i, o, kernel_size, stride... | null |
15,192 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from ..core.ops import Focus, RepConv, SPPBottleneck, get_activation, DepthwiseConv
from damo.utils import make_divisible
def channel_shuffle(x, groups):
batchsize, num_channels, height, width = x.data.size()
channels_per_group = nu... | null |
15,193 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from ..core.ops import Focus, RepConv, SPPBottleneck, get_activation, DepthwiseConv
from damo.utils import make_divisible
class TinyNAS(nn.Module):
def __init__(self,
structure_info=None,
out_indices=[2,... | null |
15,194 | import torch
import torch.nn as nn
from ..core.ops import Focus, RepConv, SPPBottleneck, get_activation
class TinyNAS(nn.Module):
def __init__(self,
structure_info=None,
out_indices=[2, 3, 4],
with_spp=False,
use_focus=False,
act='... | null |
15,195 | from functools import partial
import torch
import torch.distributed as dist
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `multi_apply` function. Write a Python function `def multi_apply(func, *args, **kwargs)` to solve the following problem:
Apply function to a l... | Apply function to a list of arguments. Note: This function applies the ``func`` to multiple inputs and map the multiple outputs of the ``func`` into different list. Each list contains the same type of outputs corresponding to different inputs. Args: func (Function): A function that will be applied to a list of argument... |
15,196 | from functools import partial
import torch
import torch.distributed as dist
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `unmap` function. Write a Python function `def unmap(data, count, inds, fill=0)` to solve the following problem:
Unmap a subset of item (data)... | Unmap a subset of item (data) back to the original set of items (of size count) |
15,197 | from functools import partial
import torch
import torch.distributed as dist
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `reduce_mean` function. Write a Python function `def reduce_mean(tensor)` to solve the following problem:
Obtain the mean of tensor on differe... | Obtain the mean of tensor on different GPUs. |
15,198 | from functools import partial
import torch
import torch.distributed as dist
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `images_to_levels` function. Write a Python function `def images_to_levels(target, num_levels)` to solve the following problem:
Convert target... | Convert targets by image to targets by feature level. [target_img0, target_img1] -> [target_level0, target_level1, ...] |
15,199 | import numpy as np
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
from .weight_init import kaiming_init, constant_init
from damo.utils import make_divisible
class SiLU(nn.Module):
def forward(x):
class Swish(nn.Module):
def __init__(self, inplace=True):
def forward(self, x... | null |
15,200 | import numpy as np
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
from .weight_init import kaiming_init, constant_init
from damo.utils import make_divisible
def get_norm(name, out_channels):
if name == 'bn':
module = nn.BatchNorm2d(out_channels)
elif name == 'gn':
... | null |
15,201 | import numpy as np
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
from .weight_init import kaiming_init, constant_init
from damo.utils import make_divisible
def depthwise_conv(i, o, kernel_size, stride=1, padding=0, bias=False):
return nn.Conv2d(i, o, kernel_size, stride, padding, b... | null |
15,202 | import numpy as np
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
from .weight_init import kaiming_init, constant_init
from damo.utils import make_divisible
The provided code snippet includes necessary dependencies for implementing the `conv_bn` function. Write a Python function `def co... | Basic cell for rep-style block, including conv and bn |
15,203 | import torch
def batched_nms(boxes, scores, idxs, nms_cfg, class_agnostic=False):
"""Performs non-maximum suppression in a batched fashion.
Modified from https://github.com/pytorch/vision/blob
/505cd6957711af790211896d32b40291bea1bc21/torchvision/ops/boxes.py#L39.
In order to perform NMS independently p... | NMS for multi-class bboxes. Args: multi_bboxes (Tensor): shape (n, #class*4) or (n, 4) multi_scores (Tensor): shape (n, #class), where the last column contains scores of the background class, but this will be ignored. score_thr (float): bbox threshold, bboxes with scores lower than it will not be considered. nms_thr (f... |
15,204 | import torch
def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False, eps=1e-6):
"""Calculate overlap between two set of bboxes.
If ``is_aligned `` is ``False``, then calculate the overlaps between each
bbox of bboxes1 and bboxes2, otherwise the overlaps between each aligned
pair of bboxes1 and... | Fast NMS in `YOLACT <https://arxiv.org/abs/1904.02689>`_. Fast NMS allows already-removed detections to suppress other detections so that every instance can be decided to be kept or discarded in parallel, which is not possible in traditional NMS. This relaxation allows us to implement Fast NMS entirely in standard GPU-... |
15,205 | import numpy as np
import torch.nn as nn
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) | null |
15,206 | import numpy as np
import torch.nn as nn
def constant_init(module, val, bias=0):
if hasattr(module, "weight") and module.weight is not None:
nn.init.constant_(module.weight, val)
if hasattr(module, "bias") and module.bias is not None:
nn.init.constant_(module.bias, bias) | null |
15,207 | import numpy as np
import torch.nn as nn
def kaiming_init(
module, a=0, mode="fan_out", nonlinearity="relu", bias=0, distribution="normal"
):
assert distribution in ["uniform", "normal"]
if distribution == "uniform":
nn.init.kaiming_uniform_(
module.weight, a=a, mode=mode, nonlinearity=... | null |
15,208 | import numpy as np
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `bias_init_with_prob` function. Write a Python function `def bias_init_with_prob(prior_prob)` to solve the following problem:
initialize conv/fc bias value according to a given probability value.
He... | initialize conv/fc bias value according to a given probability value. |
15,209 | import torch
import torch.nn as nn
import torch.nn.functional as F
from damo.utils import postprocess
from ..core.ops import ConvBNAct
from ..core.ota_assigner import AlignOTAAssigner
from ..core.utils import Scale, multi_apply, reduce_mean
from ..core.weight_init import bias_init_with_prob, normal_init
from ..losses.g... | Decode distance prediction to bounding box. |
15,210 | import torch
import torch.nn as nn
import torch.nn.functional as F
from damo.utils import postprocess
from ..core.ops import ConvBNAct
from ..core.ota_assigner import AlignOTAAssigner
from ..core.utils import Scale, multi_apply, reduce_mean
from ..core.weight_init import bias_init_with_prob, normal_init
from ..losses.g... | Decode bounding box based on distances. |
15,211 | import torch
from damo.dataset.transforms import transforms as T
from damo.structures.bounding_box import BoxList
from damo.structures.image_list import to_image_list
from damo.utils.boxes import filter_results
def im_detect_bbox(model, images, target_scale, target_max_size, device,
config):
def im_d... | null |
15,212 | from damo.augmentations.scale_aware_aug import SA_Aug
from . import transforms as T
class SA_Aug(object):
def __init__(self, iters_per_epoch, start_epoch, total_epochs,
no_aug_epochs, batch_size, num_gpus, num_workers, sada_cfg):
autoaug_list = sada_cfg.autoaug_params
num_policies... | null |
15,213 | import math
import random
import cv2
import numpy as np
import torch
from damo.structures.bounding_box import BoxList
from damo.utils import adjust_box_anns, get_rank
def xyn2xy(x, scale_w, scale_h, padw=0, padh=0):
# Convert normalized segments into pixel segments, shape (n,2)
y = x.clone() if isinstance(x, t... | null |
15,214 | import math
import random
import cv2
import numpy as np
import torch
from damo.structures.bounding_box import BoxList
from damo.utils import adjust_box_anns, get_rank
def resample_segments(segments, n=1000):
# Up-sample an (n,2) segment
for i, s in enumerate(segments):
x = np.linspace(0, len(s) - 1, n)
... | null |
15,215 | import math
import random
import cv2
import numpy as np
import torch
from damo.structures.bounding_box import BoxList
from damo.utils import adjust_box_anns, get_rank
def get_mosaic_coordinate(mosaic_image, mosaic_index, xc, yc, w, h, input_h,
input_w):
# TODO update doc
# index0 to t... | null |
15,216 | import os
import tempfile
from collections import OrderedDict
import torch
from loguru import logger
from damo.structures.bounding_box import BoxList
from damo.structures.boxlist_ops import boxlist_iou
def prepare_for_coco_detection(predictions, dataset):
# assert isinstance(dataset, COCODataset)
coco_results =... | null |
15,217 | import os
import tempfile
from collections import OrderedDict
import torch
from loguru import logger
from damo.structures.bounding_box import BoxList
from damo.structures.boxlist_ops import boxlist_iou
The provided code snippet includes necessary dependencies for implementing the `compute_thresholds_for_classes` funct... | The function is used to compute the thresholds corresponding to best f-measure. The resulting thresholds are used in fcos_demo.py. |
15,218 | import bisect
import copy
import math
import torch.utils.data
from damo.utils import get_world_size
from . import datasets as D
from .collate_batch import BatchCollator
from .datasets import MosaicWrapper
from .samplers import DistributedSampler, IterationBasedBatchSampler
from .transforms import build_transforms
def ... | null |
15,219 | import bisect
import copy
import math
import torch.utils.data
from damo.utils import get_world_size
from . import datasets as D
from .collate_batch import BatchCollator
from .datasets import MosaicWrapper
from .samplers import DistributedSampler, IterationBasedBatchSampler
from .transforms import build_transforms
def ... | null |
15,220 | import bisect
import copy
import math
import torch.utils.data
from damo.utils import get_world_size
from . import datasets as D
from .collate_batch import BatchCollator
from .datasets import MosaicWrapper
from .samplers import DistributedSampler, IterationBasedBatchSampler
from .transforms import build_transforms
def ... | null |
15,221 | import bisect
import copy
import math
import torch.utils.data
from damo.utils import get_world_size
from . import datasets as D
from .collate_batch import BatchCollator
from .datasets import MosaicWrapper
from .samplers import DistributedSampler, IterationBasedBatchSampler
from .transforms import build_transforms
def m... | null |
15,222 | import ast
import importlib
import os
import pprint
import sys
from abc import ABCMeta
from os.path import dirname, join
from easydict import EasyDict as easydict
from tabulate import tabulate
from .augmentations import test_aug, train_aug
from .paths_catalog import DatasetCatalog
def get_config_by_file(config_file):
... | get config object by file. Args: config_file (str): file path of config. |
15,223 | import torch
import torch.nn as nn
from loguru import logger
from torch.nn.parallel import DistributedDataParallel as DDP
from damo.base_models.backbones import build_backbone
from damo.base_models.heads import build_head
from damo.base_models.necks import build_neck
from damo.structures.image_list import to_image_list... | null |
15,224 | import torch
import torch.nn as nn
from loguru import logger
from torch.nn.parallel import DistributedDataParallel as DDP
from damo.base_models.backbones import build_backbone
from damo.base_models.heads import build_head
from damo.base_models.necks import build_neck
from damo.structures.image_list import to_image_list... | null |
15,225 | import cv2
import numpy as np
def debug_input_vis(imgs, targets, ids, train_loader):
std = np.array([1.0, 1.0, 1.0]).reshape(3, 1, 1)
mean = np.array([0.0, 0.0, 0.0]).reshape(3, 1, 1)
n, c, h, w = imgs.shape
for i in range(n):
img = imgs[i, :, :, :].cpu()
bboxs = targets[i].bbox.cpu()... | null |
15,226 | import cv2
import numpy as np
_COLORS = np.array([
0.000, 0.447, 0.741, 0.850, 0.325, 0.098, 0.929, 0.694, 0.125, 0.494,
0.184, 0.556, 0.466, 0.674, 0.188, 0.301, 0.745, 0.933, 0.635, 0.078,
0.184, 0.300, 0.300, 0.300, 0.600, 0.600, 0.600, 1.000, 0.000, 0.000,
1.000, 0.500, 0.000, 0.749, 0.749, 0.000, 0... | null |
15,227 | import os
import shutil
import torch
from loguru import logger
def load_ckpt(model, ckpt):
model_state_dict = model.state_dict()
load_dict = {}
for key_model, v in model_state_dict.items():
if key_model not in ckpt:
logger.warning('{} is not in the ckpt. \
Please double... | null |
15,228 | import os
import shutil
import torch
from loguru import logger
def save_checkpoint(state, is_best, save_dir, model_name=''):
if not os.path.exists(save_dir):
os.makedirs(save_dir)
filename = os.path.join(save_dir, model_name + '_ckpt.pth')
torch.save(state, filename)
if is_best:
best_fi... | null |
15,229 | import os
import numpy as np
from damo.dataset.transforms import transforms as T
from damo.structures.image_list import to_image_list
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path, exist_ok=True) | null |
15,230 | import os
import numpy as np
from damo.dataset.transforms import transforms as T
from damo.structures.image_list import to_image_list
def nms(boxes, scores, nms_thr):
"""Single class NMS implemented in Numpy."""
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
areas = (x2 - x1... | Multiclass NMS implemented in Numpy |
15,231 | import os
import numpy as np
from damo.dataset.transforms import transforms as T
from damo.structures.image_list import to_image_list
def demo_postprocess(outputs, img_size, p6=False):
grids = []
expanded_strides = []
if not p6:
strides = [8, 16, 32]
else:
strides = [8, 16, 32, 64]
... | null |
15,232 | import os
import numpy as np
from damo.dataset.transforms import transforms as T
from damo.structures.image_list import to_image_list
def to_image_list(tensors, size_divisible=0, max_size=None):
"""
tensors can be an ImageList, a torch.Tensor or
an iterable of Tensors. It can't be a numpy array.
When t... | null |
15,233 | import functools
import os
import pickle
import time
from contextlib import contextmanager
import numpy as np
import torch
from loguru import logger
from torch import distributed as dist
def get_num_devices():
gpu_list = os.getenv('CUDA_VISIBLE_DEVICES', None)
if gpu_list is not None:
return len(gpu_li... | null |
15,234 | import functools
import os
import pickle
import time
from contextlib import contextmanager
import numpy as np
import torch
from loguru import logger
from torch import distributed as dist
The provided code snippet includes necessary dependencies for implementing the `wait_for_the_master` function. Write a Python functi... | Make all processes waiting for the master to do some task. |
15,235 | import functools
import os
import pickle
import time
from contextlib import contextmanager
import numpy as np
import torch
from loguru import logger
from torch import distributed as dist
_LOCAL_PROCESS_GROUP = None
def get_rank() -> int:
if not dist.is_available():
return 0
if not dist.is_initialized():... | Returns: The rank of the current process within the local (per-machine) process group. |
15,236 | import functools
import os
import pickle
import time
from contextlib import contextmanager
import numpy as np
import torch
from loguru import logger
from torch import distributed as dist
_LOCAL_PROCESS_GROUP = None
def get_world_size() -> int:
if not dist.is_available():
return 1
if not dist.is_initiali... | Returns: The size of the per-machine process group, i.e. the number of processes per machine. |
15,237 | import functools
import os
import pickle
import time
from contextlib import contextmanager
import numpy as np
import torch
from loguru import logger
from torch import distributed as dist
def get_rank() -> int:
def is_main_process() -> bool:
return get_rank() == 0 | null |
15,238 | import functools
import os
import pickle
import time
from contextlib import contextmanager
import numpy as np
import torch
from loguru import logger
from torch import distributed as dist
def get_world_size() -> int:
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
... | Run gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object dst (int): destination rank group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: on dst, a list of data gathered from each rank. Otherwise, an empty lis... |
15,239 | import functools
import os
import pickle
import time
from contextlib import contextmanager
import numpy as np
import torch
from loguru import logger
from torch import distributed as dist
def all_gather(data, group=None):
"""
Run all_gather on arbitrary picklable data (not necessarily tensors).
Args:
... | Returns: int: a random number that is the same across all workers. If workers need a shared RNG, they can use this shared seed to create one. All workers must call this function, otherwise it will deadlock. |
15,240 | import functools
import os
import pickle
import time
from contextlib import contextmanager
import numpy as np
import torch
from loguru import logger
from torch import distributed as dist
def synchronize():
"""
Helper function to synchronize (barrier)
among all processes when using distributed training
"... | pytorch-accurate time |
15,241 | import time
from copy import deepcopy
import torch
import torch.nn as nn
from thop import profile
def make_divisible(v, divisor=8, min_value=None):
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
if new_v < 0.9 * v:
new_v += diviso... | null |
15,242 | import time
from copy import deepcopy
import torch
import torch.nn as nn
from thop import profile
def get_latency(model, inp, iters=500, warmup=2):
start = time.time()
for i in range(iters):
out = model(inp)
if torch.cuda.is_available():
torch.cuda.synchronize()
if i <= warmu... | null |
15,243 | import time
from copy import deepcopy
import torch
import torch.nn as nn
from thop import profile
def fuse_conv_and_bn(conv, bn):
# Fuse convolution and batchnorm layers
# https://tehnokv.com/posts/fusing-batchnorm-and-conv/
fusedconv = (nn.Conv2d(
conv.in_channels,
conv.out_channels,
... | null |
15,244 | import time
from copy import deepcopy
import torch
import torch.nn as nn
from thop import profile
The provided code snippet includes necessary dependencies for implementing the `replace_module` function. Write a Python function `def replace_module(module, replaced_module_type, new... | Replace given type in module to a new type. mostly used in deploy. Args: module (nn.Module): model to apply replace operation. replaced_module_type (Type): module type to be replaced. new_module_type (Type) replace_func (function): python function to describe replace logic. Defalut value None. Returns: model (nn.Module... |
15,245 | import functools
import os
from collections import defaultdict, deque
import numpy as np
import torch
def get_total_and_free_memory_in_Mb(cuda_device):
devices_info_str = os.popen(
'nvidia-smi --query-gpu=memory.total,memory.used \
--format=csv,nounits,noheader')
devices_info = devices_info_st... | null |
15,246 | import functools
import os
from collections import defaultdict, deque
import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `gpu_mem_usage` function. Write a Python function `def gpu_mem_usage()` to solve the following problem:
Compute the GPU memory usage for t... | Compute the GPU memory usage for the current device (MB). |
15,247 | import torch
import sys
if sys.version_info[0] == 3 and sys.version_info[1] >= 7:
import importlib
import importlib.util
import sys
else:
import imp
def import_file(module_name, file_path, make_importable=False):
spec = importlib.util.spec_from_file_location(module_name, file_path)
modu... | null |
15,248 | import torch
import sys
def import_file(module_name, file_path, make_importable=None):
module = imp.load_source(module_name, file_path)
return module | null |
15,249 | import inspect
import os
import sys
import datetime
from loguru import logger
The provided code snippet includes necessary dependencies for implementing the `get_caller_name` function. Write a Python function `def get_caller_name(depth=0)` to solve the following problem:
Args: depth (int): Depth of caller conext, use ... | Args: depth (int): Depth of caller conext, use 0 for caller depth. Default value: 0. Returns: str: module name of the caller |
15,250 | import inspect
import os
import sys
import datetime
from loguru import logger
def redirect_sys_output(log_level='INFO'):
redirect_logger = StreamToLoguru(log_level)
sys.stderr = redirect_logger
sys.stdout = redirect_logger
The provided code snippet includes necessary dependencies for implementing the `setu... | setup logger for training and testing. Args: save_dir(str): location to save log file distributed_rank(int): device rank when multi-gpu environment mode(str): log file write mode, `append` or `override`. default is `a`. Return: logger instance. |
15,251 | import numpy as np
import torch
import torchvision
from damo.structures.bounding_box import BoxList
The provided code snippet includes necessary dependencies for implementing the `filter_box` function. Write a Python function `def filter_box(output, scale_range)` to solve the following problem:
output: (N, 5+class) sh... | output: (N, 5+class) shape |
15,252 | import numpy as np
import torch
import torchvision
from damo.structures.bounding_box import BoxList
def multiclass_nms(multi_bboxes,
multi_scores,
score_thr,
iou_thr,
max_num=100,
score_factors=None):
"""NMS for multi-cla... | null |
15,253 | import numpy as np
import torch
import torchvision
from damo.structures.bounding_box import BoxList
def bboxes_iou(bboxes_a, bboxes_b, xyxy=True):
if bboxes_a.shape[1] != 4 or bboxes_b.shape[1] != 4:
raise IndexError
if xyxy:
tl = torch.max(bboxes_a[:, None, :2], bboxes_b[:, :2])
br = ... | null |
15,254 | import numpy as np
import torch
import torchvision
from damo.structures.bounding_box import BoxList
The provided code snippet includes necessary dependencies for implementing the `matrix_iou` function. Write a Python function `def matrix_iou(a, b)` to solve the following problem:
return iou of a and b, numpy version f... | return iou of a and b, numpy version for data augenmentation |
15,255 | import numpy as np
import torch
import torchvision
from damo.structures.bounding_box import BoxList
def adjust_box_anns(bbox, scale_ratio, padw, padh, w_max, h_max):
bbox[:, 0::2] = np.clip(bbox[:, 0::2] * scale_ratio + padw, 0, w_max)
bbox[:, 1::2] = np.clip(bbox[:, 1::2] * scale_ratio + padh, 0, h_max)
r... | null |
15,256 | import numpy as np
import torch
import torchvision
from damo.structures.bounding_box import BoxList
def xyxy2xywh(bboxes):
bboxes[:, 2] = bboxes[:, 2] - bboxes[:, 0]
bboxes[:, 3] = bboxes[:, 3] - bboxes[:, 1]
return bboxes | null |
15,257 | import numpy as np
import torch
import torchvision
from damo.structures.bounding_box import BoxList
def xyxy2cxcywh(bboxes):
bboxes[:, 2] = bboxes[:, 2] - bboxes[:, 0]
bboxes[:, 3] = bboxes[:, 3] - bboxes[:, 1]
bboxes[:, 0] = bboxes[:, 0] + bboxes[:, 2] * 0.5
bboxes[:, 1] = bboxes[:, 1] + bboxes[:, 3] ... | null |
15,258 | import argparse
import copy
import torch
from loguru import logger
from damo.apis import Trainer
from damo.config.base import parse_config
from damo.utils import synchronize
The provided code snippet includes necessary dependencies for implementing the `make_parser` function. Write a Python function `def make_parser()... | Create a parser with some common arguments used by users. Returns: argparse.ArgumentParser |
15,259 | import os
import tensorrt as trt
import pycuda.driver as cuda
import pycuda.autoinit
import numpy as np
import cv2
import glob
import ctypes
import logging
def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleup=False, stride=32, return_int=False):
# Resize and pad image while meeting stri... | Process image before image inference. |
15,260 | import argparse
import os
import torch
from loguru import logger
import tensorrt as trt
from damo.apis.detector_inference_trt import inference
from damo.config.base import parse_config
from damo.dataset import build_dataloader, build_dataset
from damo.utils import setup_logger, synchronize
def make_parser():
parse... | null |
15,261 | import argparse
import os
import torch
from loguru import logger
import tensorrt as trt
from damo.apis.detector_inference_trt import inference
from damo.config.base import parse_config
from damo.dataset import build_dataloader, build_dataset
from damo.utils import setup_logger, synchronize
def mkdir(path):
if not o... | null |
15,262 | import os
import torch
import torch.nn as nn
import copy
from pytorch_quantization import nn as quant_nn
from pytorch_quantization import tensor_quant
from pytorch_quantization import calib
from pytorch_quantization.tensor_quant import QuantDescriptor
from damo.dataset import build_dataloader, build_dataset
def collect... | null |
15,263 | import os
import torch
import torch.nn as nn
import copy
from pytorch_quantization import nn as quant_nn
from pytorch_quantization import tensor_quant
from pytorch_quantization import calib
from pytorch_quantization.tensor_quant import QuantDescriptor
from damo.dataset import build_dataloader, build_dataset
def quant_m... | null |
15,264 | import os
import torch
import torch.nn as nn
import copy
from pytorch_quantization import nn as quant_nn
from pytorch_quantization import tensor_quant
from pytorch_quantization import calib
from pytorch_quantization.tensor_quant import QuantDescriptor
from damo.dataset import build_dataloader, build_dataset
def module_... | null |
15,265 | import os
import torch
import torch.nn as nn
import copy
from pytorch_quantization import nn as quant_nn
from pytorch_quantization import tensor_quant
from pytorch_quantization import calib
from pytorch_quantization.tensor_quant import QuantDescriptor
from damo.dataset import build_dataloader, build_dataset
def init_c... | null |
15,266 | import os
import argparse
import sys
import onnx
import torch
from loguru import logger
from torch import nn
from damo.base_models.core.end2end import End2End
from damo.base_models.core.ops import RepConv, SiLU
from damo.config.base import parse_config
from damo.detectors.detector import build_local_model
from damo.uti... | null |
15,267 | import os
import argparse
import sys
import onnx
import torch
from loguru import logger
from torch import nn
from damo.base_models.core.end2end import End2End
from damo.base_models.core.ops import RepConv, SiLU
from damo.config.base import parse_config
from damo.detectors.detector import build_local_model
from damo.uti... | null |
15,268 | import os
import argparse
import sys
import onnx
import torch
from loguru import logger
from torch import nn
from damo.base_models.core.end2end import End2End
from damo.base_models.core.ops import RepConv, SiLU
from damo.config.base import parse_config
from damo.detectors.detector import build_local_model
from damo.uti... | null |
15,269 | import argparse
import os
import cv2
import numpy as np
import torch
from loguru import logger
from PIL import Image
from damo.base_models.core.ops import RepConv
from damo.config.base import parse_config
from damo.detectors.detector import build_local_model
from damo.utils import get_model_info, vis, postprocess
from ... | null |
15,270 | import argparse
import os
import torch
from loguru import logger
from damo.base_models.core.ops import RepConv
from damo.apis.detector_inference import inference
from damo.config.base import parse_config
from damo.dataset import build_dataloader, build_dataset
from damo.detectors.detector import build_ddp_model, build_... | null |
15,271 | import argparse
import os
import torch
from loguru import logger
from damo.base_models.core.ops import RepConv
from damo.apis.detector_inference import inference
from damo.config.base import parse_config
from damo.dataset import build_dataloader, build_dataset
from damo.detectors.detector import build_ddp_model, build_... | null |
15,272 | import argparse
import sys
import onnx
import torch
from loguru import logger
from torch import nn
from damo.base_models.core.end2end import End2End
from damo.base_models.core.ops import RepConv, SiLU
from damo.config.base import parse_config
from damo.detectors.detector import build_local_model
from damo.utils.model_u... | null |
15,273 | import argparse
import sys
import onnx
import torch
from loguru import logger
from torch import nn
from damo.base_models.core.end2end import End2End
from damo.base_models.core.ops import RepConv, SiLU
from damo.config.base import parse_config
from damo.detectors.detector import build_local_model
from damo.utils.model_u... | null |
15,274 | import logging
import math
from . import pulse_counter
from . import force_move
import toolhead
import copy
class Ercf:
def __init__(self, config):
def handle_connect(self):
def get_status(self, eventtime):
def _sample_stats(self, values):
def _gear_stepper_move_wait(self, dist, wait=True, spee... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.