id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
26,606 | 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 _... | null |
26,609 | import warnings
from mmcv.utils import Registry, build_from_cfg
def build_prior_generator(cfg, default_args=None):
def build_anchor_generator(cfg, default_args=None):
warnings.warn(
'``build_anchor_generator`` would be deprecated soon, please use '
'``build_prior_generator`` ')
return build_pri... | null |
26,610 | from mmcv.utils import Registry, build_from_cfg
BBOX_SAMPLERS = Registry('bbox_sampler')
The provided code snippet includes necessary dependencies for implementing the `build_sampler` function. Write a Python function `def build_sampler(cfg, **default_args)` to solve the following problem:
Builder of box sampler.
Her... | Builder of box sampler. |
26,611 | from mmcv.utils import Registry, build_from_cfg
BBOX_CODERS = Registry('bbox_coder')
The provided code snippet includes necessary dependencies for implementing the `build_bbox_coder` function. Write a Python function `def build_bbox_coder(cfg, **default_args)` to solve the following problem:
Builder of box coder.
Her... | Builder of box coder. |
26,612 | import mmcv
import numpy as np
import pycocotools.mask as mask_util
import torch
The provided code snippet includes necessary dependencies for implementing the `split_combined_polys` function. Write a Python function `def split_combined_polys(polys, poly_lens, polys_per_mask)` to solve the following problem:
Split the... | Split the combined 1-D polys into masks. A mask is represented as a list of polys, and a poly is represented as a 1-D array. In dataset, all masks are concatenated into a single 1-D tensor. Here we need to split the tensor into original representations. Args: polys (list): a list (length = image num) of 1-D tensors pol... |
26,613 | import mmcv
import numpy as np
import pycocotools.mask as mask_util
import torch
The provided code snippet includes necessary dependencies for implementing the `encode_mask_results` function. Write a Python function `def encode_mask_results(mask_results)` to solve the following problem:
Encode bitmap mask to RLE code.... | Encode bitmap mask to RLE code. Args: mask_results (list | tuple[list]): bitmap mask results. In mask scoring rcnn, mask_results is a tuple of (segm_results, segm_cls_score). Returns: list | tuple: RLE encoded mask. |
26,614 | import mmcv
import numpy as np
import pycocotools.mask as mask_util
import torch
The provided code snippet includes necessary dependencies for implementing the `mask2bbox` function. Write a Python function `def mask2bbox(masks)` to solve the following problem:
Obtain tight bounding boxes of binary masks. Args: masks (... | Obtain tight bounding boxes of binary masks. Args: masks (Tensor): Binary mask of shape (n, h, w). Returns: Tensor: Bboxe with shape (n, 4) of \ positive region in binary mask. |
26,615 | import functools
import pickle
import warnings
from collections import OrderedDict
import torch
import torch.distributed as dist
from mmcv.runner import OptimizerHook, get_dist_info
from torch._utils import (_flatten_dense_tensors, _take_tensors,
_unflatten_dense_tensors)
def _allreduce_coales... | Allreduce gradients. Args: params (list[torch.Parameters]): List of parameters of a model coalesce (bool, optional): Whether allreduce parameters as a whole. Defaults to True. bucket_size_mb (int, optional): Size of bucket, the unit is MB. Defaults to -1. |
26,616 | import functools
import pickle
import warnings
from collections import OrderedDict
import torch
import torch.distributed as dist
from mmcv.runner import OptimizerHook, get_dist_info
from torch._utils import (_flatten_dense_tensors, _take_tensors,
_unflatten_dense_tensors)
The provided code sn... | Obtain the mean of tensor on different GPUs. |
26,617 | import functools
import pickle
import warnings
from collections import OrderedDict
import torch
import torch.distributed as dist
from mmcv.runner import OptimizerHook, get_dist_info
from torch._utils import (_flatten_dense_tensors, _take_tensors,
_unflatten_dense_tensors)
def obj2tensor(pyobj,... | Apply all reduce function for python dict object. The code is modified from https://github.com/Megvii- BaseDetection/YOLOX/blob/main/yolox/utils/allreduce_norm.py. NOTE: make sure that py_dict in different ranks has the same keys and the values should be in the same shape. Args: py_dict (dict): Dict to be applied all r... |
26,618 |
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 list of arguments. Note: This function applies the ``func`` to multiple inputs and map the multipl... | 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... |
26,620 | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.ops import sigmoid_focal_loss as _sigmoid_focal_loss
from mmseg.models.builder import LOSSES
from mmseg.models.losses.utils import weight_reduce_loss
The provided code snippet includes necessary dependencies for implementing the `py_sigmoid_f... | PyTorch version of `Focal Loss <https://arxiv.org/abs/1708.02002>`_. Args: pred (torch.Tensor): The prediction with shape (N, C), C is the number of classes target (torch.Tensor): The learning label of the prediction. weight (torch.Tensor, optional): Sample-wise loss weight. gamma (float, optional): The gamma for calcu... |
26,621 | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.ops import sigmoid_focal_loss as _sigmoid_focal_loss
from mmseg.models.builder import LOSSES
from mmseg.models.losses.utils import weight_reduce_loss
The provided code snippet includes necessary dependencies for implementing the `sigmoid_foca... | r"""A warpper of cuda version `Focal Loss <https://arxiv.org/abs/1708.02002>`_. Args: pred (torch.Tensor): The prediction with shape (N, C), C is the number of classes. target (torch.Tensor): The learning label of the prediction. weight (torch.Tensor, optional): Sample-wise loss weight. gamma (float, optional): The gam... |
26,622 | import torch
import torch.nn as nn
from mmseg.models.builder import LOSSES
from mmseg.models.losses.utils import weight_reduce_loss
The provided code snippet includes necessary dependencies for implementing the `dice_loss` function. Write a Python function `def dice_loss(pred, target, weigh... | Calculate dice loss, which is proposed in `V-Net: Fully Convolutional Neural Networks for Volumetric Medical Image Segmentation <https://arxiv.org/abs/1606.04797>`_. Args: pred (torch.Tensor): The prediction, has a shape (n, *) target (torch.Tensor): The learning label of the prediction, shape (n, *), same shape of pre... |
26,623 | import torch
import torch.nn as nn
from mmseg.models.builder import LOSSES
from mmseg.models.losses.utils import weight_reduce_loss
The provided code snippet includes necessary dependencies for implementing the `naive_dice_loss` function. Write a Python function `def naive_dice_loss(pred, target, ... | Calculate naive dice loss, the coefficient in the denominator is the first power instead of the second power. Args: pred (torch.Tensor): The prediction, has a shape (n, *) target (torch.Tensor): The learning label of the prediction, shape (n, *), same shape of pred. weight (torch.Tensor, optional): The weight of loss f... |
26,624 | import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmseg.models.builder import LOSSES
from mmseg.models.losses.utils import get_class_weight, weight_reduce_loss
The provided code snippet includes necessary dependencies for implementing the `cross_entropy` function. Write a Python f... | cross_entropy. The wrapper function for :func:`F.cross_entropy` Args: pred (torch.Tensor): The prediction with shape (N, 1). label (torch.Tensor): The learning label of the prediction. weight (torch.Tensor, optional): Sample-wise loss weight. Default: None. class_weight (list[float], optional): The weight for each clas... |
26,625 | import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmseg.models.builder import LOSSES
from mmseg.models.losses.utils import get_class_weight, weight_reduce_loss
def _expand_onehot_labels(labels, label_weights, target_shape, ignore_index):
"""Expand onehot labels to match the siz... | Calculate the binary CrossEntropy loss. Args: pred (torch.Tensor): The prediction with shape (N, 1). label (torch.Tensor): The learning label of the prediction. Note: In bce loss, label < 0 is invalid. weight (torch.Tensor, optional): Sample-wise loss weight. reduction (str, optional): The method used to reduce the los... |
26,626 | import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmseg.models.builder import LOSSES
from mmseg.models.losses.utils import get_class_weight, weight_reduce_loss
The provided code snippet includes necessary dependencies for implementing the `mask_cross_entropy` function. Write a Pyt... | Calculate the CrossEntropy loss for masks. Args: pred (torch.Tensor): The prediction with shape (N, C), C is the number of classes. target (torch.Tensor): The learning label of the prediction. label (torch.Tensor): ``label`` indicates the class label of the mask' corresponding object. This will be used to select the ma... |
26,627 | 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 mmseg.mode... | null |
26,628 | 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 mmseg.mode... | null |
26,629 | import warnings
from mmcv.utils import Registry
MATCH_COST = Registry('match_cost')
The provided code snippet includes necessary dependencies for implementing the `build_match_cost` function. Write a Python function `def build_match_cost(cfg)` to solve the following problem:
Build Match Cost.
Here is the function:
... | Build Match Cost. |
26,630 | import warnings
from mmcv.utils import Registry
MASK_ASSIGNERS = Registry('mask_assigner')
The provided code snippet includes necessary dependencies for implementing the `build_assigner` function. Write a Python function `def build_assigner(cfg)` to solve the following problem:
Build Assigner.
Here is the function:... | Build Assigner. |
26,631 | import warnings
from mmcv.utils import Registry
TRANSFORMER = Registry('Transformer')
The provided code snippet includes necessary dependencies for implementing the `build_transformer` function. Write a Python function `def build_transformer(cfg)` to solve the following problem:
Build Transformer.
Here is the funct... | Build Transformer. |
26,632 | import math
import warnings
from typing import Sequence
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from mmcv.cnn import (Linear, build_activation_layer, build_conv_layer,
build_norm_layer, xavier_init)
from mmcv.cnn.bricks.registry import... | 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,633 | import torch
from mmcv.ops import point_sample
def get_uncertainty(mask_pred, labels):
"""Estimate uncertainty based on pred logits.
We estimate uncertainty as L1 distance between 0.0 and the logits
prediction in 'mask_pred' for the foreground class in `classes`.
Args:
mask_pred (Tensor): mask p... | Get ``num_points`` most uncertain points with random points during train. Sample points in [0, 1] x [0, 1] coordinate space based on their uncertainty. The uncertainties are calculated for each point using 'get_uncertainty()' function that takes point's logit prediction as input. Args: mask_pred (Tensor): A tensor of s... |
26,634 | import json
from mmcv.runner import OPTIMIZER_BUILDERS, DefaultOptimizerConstructor
from mmcv.runner import get_dist_info
from mmseg.utils import get_root_logger
def get_num_layer_for_swin(var_name, num_max_layer, depths):
if var_name.startswith("backbone.patch_embed"):
return 0
elif var_name.startswit... | null |
26,635 | 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 import Config, DictAction
from mmcv.runner import get_dist_info, init_dist
from mmcv.utils import get_git_hash
from mmdet import __version__
from mmdet.apis import ... | null |
26,636 | import asyncio
from argparse import ArgumentParser
from mmdet.apis import (async_inference_detector, inference_detector,
init_detector, show_result_pyplot)
import mmcv
import mmcv_custom
import mmdet_custom
import os.path as osp
def parse_args():
parser = ArgumentParser()
parser.add_a... | null |
26,637 | import argparse
import numpy as np
import torch
from mmcv import Config, DictAction
from mmdet.models import build_detector
import mmcv_custom
import mmdet_custom
def parse_args():
parser = argparse.ArgumentParser(description='Train a detector')
parser.add_argument('config', help='train config file path')
... | null |
26,638 | import argparse
import numpy as np
import torch
from mmcv import Config, DictAction
from mmdet.models import build_detector
import mmcv_custom
import mmdet_custom
def dcnv3_flops(n, k, c):
if __name__ == '__main__':
args = parse_args()
if len(args.shape) == 1:
h = w = args.shape[0]
elif len(args.s... | null |
26,639 | 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,640 | 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,641 | 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,642 | 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,647 | 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 mmdet.utils import get_root_logger
from mmdet.mode... | null |
26,648 | 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 mmdet.utils import get_root_logger
from mmdet.mode... | null |
26,649 | import math
import torch
import torch.nn as nn
from mmdet.models.utils.builder import TRANSFORMER
from mmcv.cnn.bricks.registry import (
TRANSFORMER_LAYER_SEQUENCE, FEEDFORWARD_NETWORK, DROPOUT_LAYERS)
from mmdet.models.utils.transformer import (inverse_sigmoid,
Deformabl... | null |
26,650 | import torch
from mmcv.runner import BaseModule
from mmdet.core import bbox_xyxy_to_cxcywh
from mmdet.models.utils.transformer import inverse_sigmoid
class DnQueryGenerator(BaseModule):
def __init__(self,
num_queries,
hidden_dim,
num_classes,
noise... | Args: dn_args (dict): Returns: |
26,651 | import argparse
import os
import pickle as pkl
import numpy as np
import random
from PIL import Image
import concurrent.futures
import json
import mmcv
def parse_args():
parser = argparse.ArgumentParser(description='Generate MMDetection Annotations for Crowdhuman-like dataset')
parser.add_argument('--dataset',... | null |
26,652 | import argparse
import os
import pickle as pkl
import numpy as np
import random
from PIL import Image
import concurrent.futures
import json
import mmcv
def load_func(fpath):
assert os.path.exists(fpath)
with open(fpath, 'r') as fid:
lines = fid.readlines()
records = [json.loads(line.strip('\n')) fo... | null |
26,653 | import argparse
import os
import pickle as pkl
import numpy as np
import random
from PIL import Image
import concurrent.futures
import json
import mmcv
def decode_annotations(records, dataset_path):
rec_ids = list(range(len(records)))
img_list = []
ann_list = []
ann_id = 1
for idx, rec_id in enumer... | null |
26,654 | 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("backbone.patch_embed"):
return 0
elif "level_embeds" in ... | null |
26,655 | import argparse
import os
import os.path as osp
import time
import warnings
import mmcv
import torch
from mmcv import Config, DictAction
from mmcv.cnn import fuse_conv_bn
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (get_dist_info, init_dist, load_checkpoint,
... | null |
26,656 | import os.path as osp
import pickle
import shutil
import tempfile
import time
import numpy as np
import torch
import torch.distributed as dist
import torch.nn.functional as F
import mmcv
from mmcv.image import tensor2imgs
from mmcv.runner import get_dist_info
from mmdet.core import encode_mask_results
def prompt_sam_wi... | null |
26,657 | import os
import time
import argparse
import torch
from tqdm import tqdm
from config import get_config
from models import build_model
def get_config(args):
"""Get a yacs CfgNode object with default values."""
# Return a clone so that the defaults will not be altered
# This is for the "local variable" use p... | null |
26,658 | import os
import time
import argparse
import torch
from tqdm import tqdm
from config import get_config
from models import build_model
def get_model(args, cfg):
model = build_model(cfg)
ckpt = torch.load(args.ckpt, map_location='cpu')['model']
model.load_state_dict(ckpt)
return model
def torch2onnx(args... | null |
26,659 | import os
import time
import argparse
import torch
from tqdm import tqdm
from config import get_config
from models import build_model
def onnx2trt(args):
from mmdeploy.backend.tensorrt import from_onnx
onnx_name = f'{args.model_name}.onnx'
from_onnx(
onnx_name,
args.model_name,
dic... | null |
26,660 | import os
import time
import argparse
import torch
from tqdm import tqdm
from config import get_config
from models import build_model
def get_model(args, cfg):
model = build_model(cfg)
ckpt = torch.load(args.ckpt, map_location='cpu')['model']
model.load_state_dict(ckpt)
return model
def speed_test(model... | null |
26,661 | import functools
from collections import OrderedDict
def rgetattr(obj, attr, *args):
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return functools.reduce(_getattr, [obj] + attr.split('.')) | null |
26,662 | import os
import math
import torch
import numpy as np
import torch.distributed as dist
from collections import OrderedDict
from timm.utils import get_state_dict
def load_ema_checkpoint(config, model_ema, logger):
logger.info(
f'==============> Resuming form {config.MODEL.RESUME}....................'
)
... | null |
26,663 | import os
import math
import torch
import numpy as np
import torch.distributed as dist
from collections import OrderedDict
from timm.utils import get_state_dict
def convert_22k_head_to_1k(model, logger):
head_weight = model.module.head.weight
head_bias = model.module.head.bias
Nc1 = head_bias.shape[0]
... | null |
26,664 | import os
import math
import torch
import numpy as np
import torch.distributed as dist
from collections import OrderedDict
from timm.utils import get_state_dict
def auto_resume_helper(output_dir):
checkpoints = os.listdir(output_dir)
checkpoints = [ckpt for ckpt in checkpoints if ckpt.endswith('pth')]
prin... | null |
26,665 | import os
import time
import random
import argparse
import datetime
import numpy as np
import subprocess
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
from timm.utils import ModelEma, ApexScaler
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils... | null |
26,666 | import os
import time
import random
import argparse
import datetime
import numpy as np
import subprocess
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
from timm.utils import ModelEma, ApexScaler
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils... | null |
26,667 | import os
import time
import random
import argparse
import datetime
import numpy as np
import subprocess
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
from timm.utils import ModelEma, ApexScaler
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils... | null |
26,668 | import os
import time
import random
import argparse
import datetime
import numpy as np
import subprocess
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
from timm.utils import ModelEma, ApexScaler
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils... | null |
26,669 | from typing import Any, Callable
import torch
import torch.distributed as dist
def _allreduce_fut(process_group: dist.ProcessGroup,
tensor: torch.Tensor) -> torch.futures.Future[torch.Tensor]:
"Averages the input gradient tensor by allreduce and returns a future."
group_to_use = process_group... | This DDP communication hook just calls ``allreduce`` using ``GradBucket`` tensors. Once gradient tensors are aggregated across all workers, its ``then`` callback takes the mean and returns the result. If user registers this hook, DDP results is expected to be same as the case where no hook was registered. Hence, this w... |
26,670 | from typing import Any, Callable
import torch
import torch.distributed as dist
The provided code snippet includes necessary dependencies for implementing the `bf16_compress_hook` function. Write a Python function `def bf16_compress_hook( process_group: dist.ProcessGroup, bucket: dist.GradBucket) -> tor... | Warning: This API is experimental, and it requires NCCL version later than 2.9.6. This DDP communication hook implements a simple gradient compression approach that casts ``GradBucket`` tensor to half-precision `Brain floating point format <https://en.wikipedia.org/wiki/Bfloat16_floating-point_format>`_ (``torch.bfloat... |
26,671 | from typing import Any, Callable
import torch
import torch.distributed as dist
The provided code snippet includes necessary dependencies for implementing the `fp16_compress_wrapper` function. Write a Python function `def fp16_compress_wrapper( hook: Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tenso... | This wrapper casts the input gradient tensor of a given DDP communication hook to half-precision floating point format (``torch.float16``), and casts the resulting tensor of the given hook back to the input data type, such as ``float32``. Therefore, ``fp16_compress_hook`` is equivalent to ``fp16_compress_wrapper(allred... |
26,672 | from typing import Any, Callable
import torch
import torch.distributed as dist
The provided code snippet includes necessary dependencies for implementing the `bf16_compress_wrapper` function. Write a Python function `def bf16_compress_wrapper( hook: Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tenso... | Warning: This API is experimental, and it requires NCCL version later than 2.9.6. This wrapper casts the input gradient tensor of a given DDP communication hook to half-precision `Brain floating point format <https://en.wikipedia.org/wiki/Bfloat16_floating-point_format> `_ (``torch.bfloat16``), and casts the resulting ... |
26,673 | import datetime
import argparse
import os
import time
import logging
import random
import torch
import torch.backends.cudnn as cudnn
import numpy as np
from accelerate import Accelerator
from accelerate import GradScalerKwargs
from accelerate.logging import get_logger
from timm.loss import LabelSmoothingCrossEntropy, S... | null |
26,674 | import datetime
import argparse
import os
import time
import logging
import random
import torch
import torch.backends.cudnn as cudnn
import numpy as np
from accelerate import Accelerator
from accelerate import GradScalerKwargs
from accelerate.logging import get_logger
from timm.loss import LabelSmoothingCrossEntropy, S... | null |
26,675 | import datetime
import argparse
import os
import time
import logging
import random
import torch
import torch.backends.cudnn as cudnn
import numpy as np
from accelerate import Accelerator
from accelerate import GradScalerKwargs
from accelerate.logging import get_logger
from timm.loss import LabelSmoothingCrossEntropy, S... | null |
26,676 | import datetime
import argparse
import os
import time
import logging
import random
import torch
import torch.backends.cudnn as cudnn
import numpy as np
from accelerate import Accelerator
from accelerate import GradScalerKwargs
from accelerate.logging import get_logger
from timm.loss import LabelSmoothingCrossEntropy, S... | null |
26,677 | import io
import os
import re
import time
import json
import math
import mmcv
import torch
import logging
import os.path as osp
from PIL import Image
from tqdm import tqdm, trange
from abc import abstractmethod
import torch.utils.data as data
import torch.distributed as dist
from mmcv.fileio import FileClient
from .zip... | null |
26,678 | import io
import os
import re
import time
import json
import math
import mmcv
import torch
import logging
import os.path as osp
from PIL import Image
from tqdm import tqdm, trange
from abc import abstractmethod
import torch.utils.data as data
import torch.distributed as dist
from mmcv.fileio import FileClient
from .zip... | null |
26,679 | import io
import os
import re
import time
import json
import math
import mmcv
import torch
import logging
import os.path as osp
from PIL import Image
from tqdm import tqdm, trange
from abc import abstractmethod
import torch.utils.data as data
import torch.distributed as dist
from mmcv.fileio import FileClient
from .zip... | null |
26,680 | import io
import os
import re
import time
import json
import math
import mmcv
import torch
import logging
import os.path as osp
from PIL import Image
from tqdm import tqdm, trange
from abc import abstractmethod
import torch.utils.data as data
import torch.distributed as dist
from mmcv.fileio import FileClient
from .zip... | null |
26,681 | import io
import os
import re
import time
import json
import math
import mmcv
import torch
import logging
import os.path as osp
from PIL import Image
from tqdm import tqdm, trange
from abc import abstractmethod
import torch.utils.data as data
import torch.distributed as dist
from mmcv.fileio import FileClient
from .zip... | null |
26,682 | import io
import os
import re
import time
import json
import math
import mmcv
import torch
import logging
import os.path as osp
from PIL import Image
from tqdm import tqdm, trange
from abc import abstractmethod
import torch.utils.data as data
import torch.distributed as dist
from mmcv.fileio import FileClient
from .zip... | null |
26,683 | import os
import torch
import numpy as np
import torch.distributed as dist
from torchvision import transforms
from timm.data import Mixup
from timm.data import create_transform
from .cached_image_folder import ImageCephDataset
from .samplers import SubsetRandomSampler, NodeDistributedSampler
def build_dataset(split, co... | null |
26,684 | import os
import torch
import numpy as np
import torch.distributed as dist
from torchvision import transforms
from timm.data import Mixup
from timm.data import create_transform
from .cached_image_folder import ImageCephDataset
from .samplers import SubsetRandomSampler, NodeDistributedSampler
def build_dataset(split, co... | null |
26,685 | import os
import time
import random
import argparse
import datetime
import numpy as np
import subprocess
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import deepspeed
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils import accuracy, AverageMe... | null |
26,686 | import os
import time
import random
import argparse
import datetime
import numpy as np
import subprocess
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import deepspeed
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils import accuracy, AverageMe... | null |
26,687 | import os
import time
import random
import argparse
import datetime
import numpy as np
import subprocess
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import deepspeed
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils import accuracy, AverageMe... | null |
26,688 | import os
import time
import random
import argparse
import datetime
import numpy as np
import subprocess
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import deepspeed
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils import accuracy, AverageMe... | null |
26,689 | import os
import time
import random
import argparse
import datetime
import numpy as np
import subprocess
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import deepspeed
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils import accuracy, AverageMe... | null |
26,694 | 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
import pkg_... | null |
26,695 | import os
import sys
import logging
import functools
from termcolor import colored
def create_logger(output_dir, dist_rank=0, name=''):
# create logger
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
logger.propagate = False
# create formatter
fmt = '[%(asctime)s %(name)s] (%(f... | null |
26,696 | import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from timm.models.layers import trunc_normal_, DropPath
from ops_dcnv3 import modules as opsm
import torch.nn.functional as F
class to_channels_first(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
... | null |
26,697 | import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from timm.models.layers import trunc_normal_, DropPath
from ops_dcnv3 import modules as opsm
import torch.nn.functional as F
def build_act_layer(act_layer):
if act_layer == 'ReLU':
return nn.ReLU(inplace=True)
elif act_layer... | null |
26,698 | from .intern_image import InternImage
class InternImage(nn.Module):
r""" InternImage
A PyTorch impl of : `InternImage: Exploring Large-Scale Vision Foundation Models with Deformable Convolutions` -
https://arxiv.org/pdf/2103.14030
Args:
core_op (str): Core operator. Default: 'DCNv3'
... | null |
26,699 |
The provided code snippet includes necessary dependencies for implementing the `get_requires` function. Write a Python function `def get_requires()` to solve the following problem:
Read requirements.txt.
Here is the function:
def get_requires():
"""Read requirements.txt."""
requirements = open("requirements... | Read requirements.txt. |
26,700 | MINIMAL_DESCRIPTION = '''Samila is a generative art generator written in Python, Samila lets you create images based on many thousand points. The position of every single point is calculated by a
formula, which has random parameters. Because of the random numbers, every image looks different.'''
The provided code snip... | Read README.md and CHANGELOG.md. |
26,701 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Generate random equation. :return: equation as str |
26,702 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Generate float range. :param start: start point :type start: float :param stop: stop point :type step: float :param step: step :type step: float :return: yield result |
26,703 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Set background for figure and axis. :param bgcolor: given background color :type bgcolor: any format :param fig: figure :type fig: matplotlib.figure.Figure :param ax: axis :type ax: matplotlib.axes._subplots.AxesSubplot :return: None |
26,704 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Rotate the given figure and return axis. :param fig: figure containing the image :type fig: Figure :param ax: axis on which rotated image is ploted :type ax: Axis :param rotation: desired rotation (in degrees) :type rotation: float :return: axis containing rotated image |
26,705 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Filter plot method parameters. :param g: generative image instance :type g: GenerativeImage :param color: point colors :type color: str :param bgcolor: background color :type bgcolor: str :param cmap: color map :type cmap: matplotlib.colors.Colormap or list of colors :param spot_size: point spot size :type spot_size: f... |
26,706 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Filter generate method parameters. :param g: generative image instance :type g: GenerativeImage :param seed: random seed :type seed: int :param start: range start point :type start: float :param step: range step size :type step: float :param stop: range stop point :type stop: float :return: None |
26,707 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Filter save_image method parameters. :param depth: depth of image :type depth: float :return: None |
26,708 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Initialize the generative image. :param g: generative image instance :type g: GenerativeImage :param function1: function 1 :type function1: python or lambda function :param function2: function 2 :type function2: python or lambda function :return: None |
26,709 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Upload file to nft.storage. :param api_key: API key :type api_key: str :param data: image data :type data: binary :param timeout: upload timeout (in seconds) :type timeout: int :return: result as dict |
26,710 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Save data as file. :param g: generative image instance :type g: GenerativeImage :param file_adr: file address :type file_adr: str :return: result as dict |
26,711 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Save config as file. :param g: generative image instance :type g: GenerativeImage :param file_adr: file address :type file_adr: str :return: result as dict |
26,712 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Save figure as file. :param figure: matplotlib figure :type figure: matplotlib.figure.Figure :param file_adr: file address :type file_adr: str :param depth: image depth :type depth: float :return: result as dict |
26,713 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Save figure as buffer. :param figure: matplotlib figure :type figure: matplotlib.figure.Figure :param depth: image depth :type depth: float :return: result as dict |
26,714 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Print samila details. :return: None |
26,715 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Compare two data to be the same. :param data1: given data1 :type data1: list :param data2: given data2 :type data2: list :param precision: comparing precision :type precision: float :return: True if they are the same |
26,716 | import sys
import requests
import io
import os
import re
import json
import random
import matplotlib
from matplotlib import cm
from matplotlib.colors import ListedColormap
from PIL import Image
from .params import SAMILA_VERSION
from .params import DEFAULT_MARKER, DEFAULT_START, DEFAULT_STOP, DEFAULT_STEP, DEFAULT_COLO... | Load data file. :param g: generative image instance :type g: GenerativeImage :param data: prior generated data :type data: (io.IOBase & file) :return: None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.