id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
188,533
import os from pkg_resources import parse_version from setuptools import find_packages, setup The provided code snippet includes necessary dependencies for implementing the `parse_requirements` function. Write a Python function `def parse_requirements(fname='requirements.txt', with_version=True)` to solve the followin...
Parse the package dependencies listed in a file but strips specific versioning information. Args: fname (str): path to the file with_version (bool, default=False): if True include version specs Returns: List[str]: list of requirements items CommandLine: python -c "import setup; print(setup.parse_requirements())"
188,534
import os from pkg_resources import parse_version from setuptools import find_packages, setup EXT_TYPE = '' try: import torch from torch.utils.cpp_extension import BuildExtension cmd_class = {'build_ext': BuildExtension} EXT_TYPE = 'torch' except ModuleNotFoundError: cmd_class = {} print('Skip b...
null
188,535
import os import subprocess import sys import pytorch_sphinx_theme from m2r import MdInclude from recommonmark.transform import AutoStructify from sphinx.builders.html import StandaloneHTMLBuilder def generate_doxygen_xml(app): try: folder = '../cppapi' retcode = subprocess.call('cd %s; doxygen' % f...
null
188,537
from typing import Tuple version_info = parse_version_info(__version__) The provided code snippet includes necessary dependencies for implementing the `parse_version_info` function. Write a Python function `def parse_version_info(version_str: str) -> Tuple` to solve the following problem: Parse version from a string. ...
Parse version from a string. Args: version_str (str): A string represents a version info. Returns: tuple: A sequence of integer and string represents version.
188,538
from typing import Dict, Iterable, Optional, Union import onnx from .core import PIPELINE_MANAGER The provided code snippet includes necessary dependencies for implementing the `extract_model` function. Write a Python function `def extract_model(model: Union[str, onnx.ModelProto], start_marker: Union...
Extract partition-model from an ONNX model. The partition-model is defined by the names of the input and output tensors exactly. Examples: >>> from mmdeploy.apis import extract_model >>> model = 'work_dir/fastrcnn.onnx' >>> start_marker = 'detector:input' >>> end_marker = ['extract_feat:output', 'multiclass_nms[0]:inpu...
188,539
from copy import deepcopy from typing import Optional, Union from mmengine import Config from .core import PIPELINE_MANAGER, no_mp The provided code snippet includes necessary dependencies for implementing the `create_calib_input_data` function. Write a Python function `def create_calib_input_data(calib_file: str, ...
Create dataset for post-training quantization. Args: calib_file (str): The output calibration data file. deploy_cfg (str | Config): Deployment config file or Config object. model_cfg (str | Config): Model config file or Config object. model_checkpoint (str): A checkpoint path of PyTorch model, defaults to `None`. datas...
188,540
import os.path as osp from typing import Any, Optional, Union import mmengine from mmdeploy.apis.core.pipeline_manager import PIPELINE_MANAGER, no_mp class no_mp: """The context manager used to disable multiprocess.""" def __init__(self, manager: PipelineManager = PIPELINE_MANAGER) -> None: self._mana...
Convert PyTorch model to torchscript model. Args: img (str | np.ndarray | torch.Tensor): Input image used to assist converting model. work_dir (str): A working directory to save files. save_file (str): Filename to save torchscript model. deploy_cfg (str | mmengine.Config): Deployment config file or Config object. model...
188,541
from typing import Optional, Sequence, Union import mmengine import numpy as np import torch from mmdeploy.utils import Backend, get_backend, get_input_shape, load_config The provided code snippet includes necessary dependencies for implementing the `visualize_model` function. Write a Python function `def visualize_mo...
Run inference with PyTorch or backend model and show results. Examples: >>> from mmdeploy.apis import visualize_model >>> model_cfg = ('mmdetection/configs/fcos/' 'fcos_r50_caffe_fpn_gn-head_1x_coco.py') >>> deploy_cfg = ('configs/mmdet/detection/' 'detection_onnxruntime_dynamic.py') >>> model = 'work_dir/fcos.onnx' >>...
188,542
from typing import Any, Sequence, Union import mmengine import numpy as np The provided code snippet includes necessary dependencies for implementing the `inference_model` function. Write a Python function `def inference_model(model_cfg: Union[str, mmengine.Config], deploy_cfg: Union[str, mmengine....
Run inference with PyTorch or backend model and show results. Examples: >>> from mmdeploy.apis import inference_model >>> model_cfg = ('mmdetection/configs/fcos/' 'fcos_r50_caffe_fpn_gn-head_1x_coco.py') >>> deploy_cfg = ('configs/mmdet/detection/' 'detection_onnxruntime_dynamic.py') >>> backend_files = ['work_dir/fcos...
188,543
import os.path as osp from typing import Any, Optional, Union import mmengine from .core import PIPELINE_MANAGER class no_mp: """The context manager used to disable multiprocess.""" def __init__(self, manager: PipelineManager = PIPELINE_MANAGER) -> None: self._manager = manager self._old_enabl...
Convert PyTorch model to ONNX model. Examples: >>> from mmdeploy.apis import torch2onnx >>> img = 'demo.jpg' >>> work_dir = 'work_dir' >>> save_file = 'fcos.onnx' >>> deploy_cfg = ('configs/mmdet/detection/' 'detection_onnxruntime_dynamic.py') >>> model_cfg = ('mmdetection/configs/fcos/' 'fcos_r50_caffe_fpn_gn-head_1x_...
188,544
import importlib import inspect import logging from functools import wraps from typing import Any, Callable, Dict, List, Optional, Sequence, Union from mmdeploy.utils import get_root_logger The provided code snippet includes necessary dependencies for implementing the `_get_func_name` function. Write a Python function...
get function name.
188,545
from typing import Dict, Iterable, Optional, Union import onnx import onnx.helper import onnx.utils from mmdeploy.apis.core import PIPELINE_MANAGER from mmdeploy.core.optimizers import (attribute_to_dict, create_extractor, get_new_name, parse_extractor_io_string, ...
Extract partition-model from an ONNX model. The partition-model is defined by the names of the input and output tensors exactly. Examples: >>> from mmdeploy.apis import extract_model >>> model = 'work_dir/fastrcnn.onnx' >>> start_marker = 'detector:input' >>> end_marker = ['extract_feat:output', 'multiclass_nms[0]:inpu...
188,546
from typing import Callable import torch from mmdeploy.core import FUNCTION_REWRITER def update_squeeze_unsqueeze_opset13_pass(graph, params_dict, torch_out): """Update Squeeze/Unsqueeze axes for opset13.""" for node in graph.nodes(): if node.kind() in ['onnx::Squeeze', 'onnx::Unsqueeze'] and \ ...
Rewriter of _model_to_graph, add custom passes.
188,547
from typing import Callable import torch from mmdeploy.core import FUNCTION_REWRITER The provided code snippet includes necessary dependencies for implementing the `jit_pass_onnx_deduplicate_initializers__disable` function. Write a Python function `def jit_pass_onnx_deduplicate_initializers__disable(graph, param_dict,...
This pass will disable TensorRT topk export. disable for TensorRT.
188,548
from typing import Callable import torch from mmdeploy.core import FUNCTION_REWRITER The provided code snippet includes necessary dependencies for implementing the `jit_pass_onnx_autograd_function_process__disable` function. Write a Python function `def jit_pass_onnx_autograd_function_process__disable(graph)` to solve...
Disable process autograph function.
188,549
from typing import Dict, List import mmengine from mmdeploy.backend.openvino import ModelOptimizerOptions from mmdeploy.utils import get_model_inputs from mmdeploy.utils.config_utils import get_backend_config, get_ir_config def update_input_names(input_info: Dict[str, List], input_names: List[str...
Get the input names and shapes from the configs for OpenVINO Model Optimizer. Args: deploy_cfg (mmengine.Config): Deployment config. Returns: Dict[str, List]: A dict that stores the names and shapes of input.
188,550
from typing import Dict, List import mmengine from mmdeploy.backend.openvino import ModelOptimizerOptions from mmdeploy.utils import get_model_inputs from mmdeploy.utils.config_utils import get_backend_config, get_ir_config def get_backend_config(deploy_cfg: Union[str, mmengine.Config]) -> Dict: """Get the backend...
Get additional parameters for the Model Optimizer from the deploy config. Args: deploy_cfg (mmengine.Config): Deployment config. Returns: ModelOptimizerOptions: A class that will contain additional arguments.
188,551
from copy import deepcopy from typing import Callable, Dict, Optional import torch from torch.utils.data import DataLoader from ..core import PIPELINE_MANAGER The provided code snippet includes necessary dependencies for implementing the `create_calib_input_data` function. Write a Python function `def create_calib_inp...
Create calibration table. Examples: >>> from mmdeploy.apis.utils import create_calib_input_data >>> from mmdeploy.utils import get_calib_filename, load_config >>> deploy_cfg = 'configs/mmdet/detection/' 'detection_tensorrt-int8_dynamic-320x320-1344x1344.py' >>> deploy_cfg = load_config(deploy_cfg)[0] >>> calib_file = g...
188,552
import logging from typing import Any, Optional, Sequence import mmengine from mmdeploy.codebase import BaseTask, get_codebase_class, import_codebase from mmdeploy.utils import (get_backend, get_codebase, get_task_type, parse_device_id) from mmdeploy.utils.config_utils import get_codebase_ex...
Build a task processor to manage the deployment pipeline. Args: model_cfg (str | mmengine.Config): Model config file. deploy_cfg (str | mmengine.Config): Deployment config file. device (str): A string specifying device type. Returns: BaseTask: A task processor.
188,553
import logging from typing import Any, Optional, Sequence import mmengine from mmdeploy.codebase import BaseTask, get_codebase_class, import_codebase from mmdeploy.utils import (get_backend, get_codebase, get_task_type, parse_device_id) from mmdeploy.utils.config_utils import get_codebase_ex...
Get the predefined partition config. Notes: Currently only support mmdet codebase. Args: deploy_cfg (mmengine.Config): use deploy config to get the codebase and task type. partition_type (str): A string specifying partition type. Returns: dict: A dictionary of partition config.
188,554
import logging from typing import Any, Optional, Sequence import mmengine from mmdeploy.codebase import BaseTask, get_codebase_class, import_codebase from mmdeploy.utils import (get_backend, get_codebase, get_task_type, parse_device_id) from mmdeploy.utils.config_utils import get_codebase_ex...
Convert intermediate representation to given backend. Args: backend_name (str): The name of the backend. ir_files (Sequence[str]): The intermediate representation files. work_dir (str): The work directory, backend files and logs should be save in this directory. deploy_cfg (Any): The deploy config. log_level (int, opti...
188,555
import re import onnx from packaging import version The provided code snippet includes necessary dependencies for implementing the `parse_extractor_io_string` function. Write a Python function `def parse_extractor_io_string(io_str) -> tuple` to solve the following problem: Parse IO string for extractor. Here is the f...
Parse IO string for extractor.
188,556
import re import onnx from packaging import version def _dfs_search_reachable_nodes_fast(self, node_output_name, graph_input_nodes, reachable_nodes): """Using DFS to search reachable nodes.""" outputs = {} for index, node in enumerate(self.graph.node): for name i...
Create Extractor for ONNX. Args: model (onnx.ModelProto): An input onnx model. Returns: onnx.utils.Extractor: Extractor for the onnx.
188,557
import inspect from typing import Any, Callable, Dict, Optional, Sequence import torch from mmdeploy.core.rewriters import FUNCTION_REWRITER from mmdeploy.utils import IR, cfg_apply_marks, get_partition_config MARK_FUNCTION_COUNT = dict() The provided code snippet includes necessary dependencies for implementing the `...
Reset counter of mark function.
188,558
import inspect from typing import Any, Callable, Dict, Optional, Sequence import torch from mmdeploy.core.rewriters import FUNCTION_REWRITER from mmdeploy.utils import IR, cfg_apply_marks, get_partition_config The provided code snippet includes necessary dependencies for implementing the `mark_symbolic` function. Writ...
Rewrite symbolic of mark op.
188,559
import inspect from typing import Any, Callable, Dict, Optional, Sequence import torch from mmdeploy.core.rewriters import FUNCTION_REWRITER from mmdeploy.utils import IR, cfg_apply_marks, get_partition_config The provided code snippet includes necessary dependencies for implementing the `forward_of_mark` function. Wr...
Rewrite forward of mark op.
188,560
import inspect from typing import Any, Callable, Dict, Optional, Sequence import torch from mmdeploy.core.rewriters import FUNCTION_REWRITER from mmdeploy.utils import IR, cfg_apply_marks, get_partition_config The provided code snippet includes necessary dependencies for implementing the `remove_mark__torchscript` fun...
Disable all marks for TorchScript backend. As the Node `mark` is not able to be traced, we just return original input for the function `mark_tensors`. Args: xs (Any): Input structure which contains tensor.
188,561
import inspect from typing import Any, Callable, Dict, Optional, Sequence import torch from mmdeploy.core.rewriters import FUNCTION_REWRITER from mmdeploy.utils import IR, cfg_apply_marks, get_partition_config MARK_FUNCTION_COUNT = dict() def mark_tensors(xs: Any, func: str, func_id: int, io_type: str, ctx: Any, ...
The decorator used to add mark node. Mark node can be used to support model partition. Args: func_name (str): The name of the function where marks come from. inputs (Sequence[str]): The input names of the marks. The final name \ might have suffix if inputs is list or dictionary. outputs (Sequence[str]): The output name...
188,562
from typing import Callable, Dict, Iterable, Optional import onnx from onnx.helper import get_attribute_value from mmdeploy.utils import get_root_logger def attribute_to_dict(attr: onnx.AttributeProto) -> Dict: """Convert onnx op attribute to dict. Args: attr (onnx.AttributeProto): Input onnx op attribu...
Check whether a mark is unused. Args: marks (Iterable[onnx.NodeProto]): A list of onnx NodeProto. Returns: Callable: The function to check if a mark node is in `marks`.
188,563
from typing import Callable, Dict, Iterable, Optional import onnx from onnx.helper import get_attribute_value from mmdeploy.utils import get_root_logger The provided code snippet includes necessary dependencies for implementing the `get_new_name` function. Write a Python function `def get_new_name(attrs: Dict[str, str...
Get new name for a node. Args: attrs (Dict[str, str]): A dict contains attributes of an ONNX node. mark_name (str): The input mark op name. Default is ''. name_map (Dict[str, str]): A mapping of node names, defaults to `None`. Returns: str: The new node name.
188,564
from typing import Callable, Dict, Iterable, Optional import onnx from onnx.helper import get_attribute_value from mmdeploy.utils import get_root_logger The provided code snippet includes necessary dependencies for implementing the `rename_value` function. Write a Python function `def rename_value(model: onnx.ModelPro...
Rename a node in an ONNX model. Args: model (onnx.ModelProto): Input onnx model. old_name (str): Original node name in the model. new_name (str): New node name in the model.
188,565
from typing import Callable, Dict, Iterable, Optional import onnx from onnx.helper import get_attribute_value from mmdeploy.utils import get_root_logger def remove_nodes(model: onnx.ModelProto, predicate: Callable) -> onnx.ModelProto: """Remove nodes from ONNX model. Args: model (onnx.M...
Remove identity node from an ONNX model. Args: model (onnx.ModelProto): Input onnx model.
188,566
from typing import Callable, Dict, Iterable, Optional import onnx from onnx.helper import get_attribute_value from mmdeploy.utils import get_root_logger The provided code snippet includes necessary dependencies for implementing the `remove_imports` function. Write a Python function `def remove_imports(model: onnx.Mode...
Remove useless imports from an ONNX model. The domain like `mmdeploy` might influence model conversion for some backends. Args: model (onnx.ModelProto): Input onnx model.
188,567
from typing import Dict import mmengine import torch.nn as nn from mmdeploy.utils.constants import IR, Backend from .function_rewriter import FunctionRewriter from .module_rewriter import ModuleRewriter from .rewriter_utils import collect_env from .symbolic_rewriter import SymbolicRewriter MODULE_REWRITER = REWRITER_MA...
Patch the model, replace the modules that can be rewritten. Note that the original model will be modified permanently. Args: model (torch.nn.Module): The model to patch. cfg (Dict): Config dictionary of deployment. backend (str): The inference engine name. ir (IR): The intermeditate representation name. recursive (bool...
188,568
import functools import inspect import types import warnings from abc import ABCMeta, abstractmethod from functools import wraps from typing import Any, Callable, Dict, List, Optional, Tuple, Union import mmdeploy from mmdeploy.utils.constants import IR, Backend The provided code snippet includes necessary dependencie...
Evaluate the string as Python script. Args: path (str): The path to evaluate. Returns: Any: The result of evaluation.
188,569
import functools import inspect import types import warnings from abc import ABCMeta, abstractmethod from functools import wraps from typing import Any, Callable, Dict, List, Optional, Tuple, Union import mmdeploy from mmdeploy.utils.constants import IR, Backend The provided code snippet includes necessary dependencie...
Import and evaluate a function. If the function is defined in a class, evaluate the class additionally. Args: path (str): The path to evaluate. Returns: Callable: The function of evaluation. type: The class of evaluation if the function is defined in a class, or None.
188,570
import functools import inspect import types import warnings from abc import ABCMeta, abstractmethod from functools import wraps from typing import Any, Callable, Dict, List, Optional, Tuple, Union import mmdeploy from mmdeploy.utils.constants import IR, Backend class IR(AdvancedEnum): """Define intermediate repre...
Collect current environment information, including backend, ir, codebase version, etc. Rewriters will be checked according to env infos. Args: backend (Backend): Current backend. ir (IR): Current IR. Returns: Dict: Record the value of Backend and IR as well as the versions of libraries.
188,571
import functools import inspect import types import warnings from abc import ABCMeta, abstractmethod from functools import wraps from typing import Any, Callable, Dict, List, Optional, Tuple, Union import mmdeploy from mmdeploy.utils.constants import IR, Backend The provided code snippet includes necessary dependencie...
get function name.
188,572
import functools import inspect import types import warnings from abc import ABCMeta, abstractmethod from functools import wraps from typing import Any, Callable, Dict, List, Optional, Tuple, Union import mmdeploy from mmdeploy.utils.constants import IR, Backend The provided code snippet includes necessary dependencie...
get func of frame.
188,573
import functools import inspect import types import warnings from abc import ABCMeta, abstractmethod from functools import wraps from typing import Any, Callable, Dict, List, Optional, Tuple, Union import mmdeploy from mmdeploy.utils.constants import IR, Backend The provided code snippet includes necessary dependencie...
get frame name.
188,574
import functools import inspect import types import warnings from abc import ABCMeta, abstractmethod from functools import wraps from typing import Any, Callable, Dict, List, Optional, Tuple, Union import mmdeploy from mmdeploy.utils.constants import IR, Backend The provided code snippet includes necessary dependencie...
Copy the function.
188,575
import types from collections import defaultdict from typing import (Any, Callable, Dict, List, MutableSequence, Optional, Tuple, Union) from mmdeploy.utils import IR, Backend, get_root_logger from .rewriter_utils import (Checker, ContextCaller, RewriterRegistry, copy_fu...
Rewrite a function by executing a python statement. Args: origin_func_path (str): The path to origin function. rewrite_func (Callable): The new function instance. ignore_refs (Tuple[Any]): These refs will be ignored. ignore_keys (Tuple[str]): object with these keys will be ignored.
188,576
import types from collections import defaultdict from typing import (Any, Callable, Dict, List, MutableSequence, Optional, Tuple, Union) from mmdeploy.utils import IR, Backend, get_root_logger from .rewriter_utils import (Checker, ContextCaller, RewriterRegistry, copy_fu...
Delete a function that is denoted by a path. Args: path (str): The path to evaluate.
188,577
import types from collections import defaultdict from typing import (Any, Callable, Dict, List, MutableSequence, Optional, Tuple, Union) from mmdeploy.utils import IR, Backend, get_root_logger from .rewriter_utils import (Checker, ContextCaller, RewriterRegistry, copy_fu...
If a function is wrapped by torch.fx.wrap, its copy also needs to be wrapped by torch.fx.wrap.
188,578
from torch.onnx.symbolic_helper import parse_args from mmdeploy.core import SYMBOLIC_REWRITER from mmdeploy.utils import Backend, get_backend def grid_sampler(g, input, grid, interpolation_mode, padding_mode, align_corners=False): ...
Register default symbolic function for `grid_sampler`. Add support to grid_sample to ONNX.
188,579
from torch.onnx import symbolic_helper from mmdeploy.core import SYMBOLIC_REWRITER from mmdeploy.utils import Backend def gelu__ncnn_pt111(g, self): """gelu for torch<=1.12.""" return g.op('mmdeploy::Gelu', self) 'gelu', is_pytorch=True, backend=Backend.NCNN.value) The provided code snippet includes necess...
Support export GELU with ncnn backend.
188,580
The provided code snippet includes necessary dependencies for implementing the `hardsigmoid__default` function. Write a Python function `def hardsigmoid__default(g, self)` to solve the following problem: Support export hardsigmoid This rewrite enable export hardsigmoid in torch<=1.8.2. Here is the function: def har...
Support export hardsigmoid This rewrite enable export hardsigmoid in torch<=1.8.2.
188,581
import sys from torch.onnx.symbolic_helper import _slice_helper, parse_args from mmdeploy.core import SYMBOLIC_REWRITER def roll(g, self, shifts, dims): """Symbolic function for `roll`.""" assert len(shifts) == len(dims) result = self for i in range(len(shifts)): shapes = [] shape = _sli...
Support export roll to ONNX with PyTorch version 1.10-.
188,582
from torch.onnx.symbolic_helper import parse_args from mmdeploy.core import SYMBOLIC_REWRITER from mmdeploy.utils import Backend The provided code snippet includes necessary dependencies for implementing the `layer_norm__default` function. Write a Python function `def layer_norm__default(g, input, normalized_shape, we...
Symbolic function for `layer_norm` Layer norm with torch<=1.12 might lead to wrong output shapes. Add keepdims=1 to each ReduceMean node to correct the shape.
188,583
from torch.onnx.symbolic_helper import parse_args from mmdeploy.core import SYMBOLIC_REWRITER from mmdeploy.utils import Backend def _layer_norm_ncnn(g, input, normalized_shape, weight, bias, eps, cudnn_enable): """Symbolic function for `layer_norm`. PyTorch does not support export layer_no...
Register default symbolic function for `layer_norm`. Add support to layer_norm to ONNX.
188,584
import torch import torch.onnx.symbolic_helper as sym_help from mmdeploy.core import SYMBOLIC_REWRITER from mmdeploy.utils import get_ir_config The provided code snippet includes necessary dependencies for implementing the `squeeze__default` function. Write a Python function `def squeeze__default(g, self, dim=None)` t...
Register default symbolic function for `squeeze`. squeeze might be exported with IF node in ONNX, which is not supported in lots of backend.
188,585
import torch from torch.onnx.symbolic_helper import (_get_tensor_dim_size, _get_tensor_rank, _unimplemented, _unsqueeze_helper, parse_args) from mmdeploy.core import SYMBOLIC_REWRITER def instance_norm(g, input, num_groups, weight, bias, ep...
Register symbolic function for TensorRT backend. Notes: Instance normalization is implemented in group norm in pytorch.
188,586
import warnings import torch import torch.onnx.symbolic_helper as sym_help from torch.onnx.symbolic_helper import _unimplemented from torch.onnx.symbolic_opset9 import unused from mmdeploy.core import FUNCTION_REWRITER warnings.warn( 'Exporting a model to ONNX with a batch_size other than 1, ' + 'wi...
rewrite of _generic_rnn for ncnn. `g.op` will add some nodes for h0 and c0 in LSTM. which is not supported in ncnn. So we add a custom domain to avoid it.
188,587
The provided code snippet includes necessary dependencies for implementing the `adaptive_avg_pool2d__ncnn` function. Write a Python function `def adaptive_avg_pool2d__ncnn(g, x, output_size)` to solve the following problem: Register ncnn symbolic function for `adaptive_avg_pool2d`. Align symbolic of adaptive_avg_pool...
Register ncnn symbolic function for `adaptive_avg_pool2d`. Align symbolic of adaptive_avg_pool2d in ncnn.
188,588
from torch.onnx.symbolic_helper import parse_args from mmdeploy.core import SYMBOLIC_REWRITER from mmdeploy.utils import Backend def linear_no_bias(g, input, weight): """Symbolic function for `linear` without bias. PyTorch `nn.Linear` will be exported as ONNX node 'Gemm'. """ return g.op( 'Gemm'...
Support export linear This rewrite enable export Gemm.
188,589
import math from typing import Optional, Tuple import torch from torch import Tensor from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils.constants import Backend class ScaledDotProductAttentionTRT(torch.autograd.Function): """Caller of scale dot product attention.""" def forward(ctx, ...
Rewrite for custom ops.
188,590
import math from typing import Optional, Tuple import torch from torch import Tensor from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils.constants import Backend The provided code snippet includes necessary dependencies for implementing the `scaled_dot_product_attention__default` function. Write a Python f...
Rewrite to export to onnx on torch>=2.0.0.
188,591
The provided code snippet includes necessary dependencies for implementing the `group_norm__ncnn` function. Write a Python function `def group_norm__ncnn( input: torch.Tensor, num_groups: int, weight: Union[torch.Tensor, torch.NoneType] = None, bias: Union[torch.Tensor, torch.NoneType] = None, eps...
Rewrite `group_norm` for ncnn backend. InstanceNorm in ncnn require input with shape [C, H, W]. So we have to reshape the input tensor before it.
188,592
import torch import torch.onnx.symbolic_helper as sym_help from packaging.version import parse as version_parse from mmdeploy.core import FUNCTION_REWRITER The provided code snippet includes necessary dependencies for implementing the `_prepare_onnx_paddings__tensorrt` function. Write a Python function `def _prepare_o...
Rewrite `_prepare_onnx_paddings` for TensorRT backend. For codes like `x = torch.nn.ZeroPad2d((0, a, 0, b))(x)`, where a and b are variables of torch.tensor, onnx2tensorrt raises errors like `INVALID_NODE: Invalid Node - Pad_`. Generate paddings in ONNX order based on pad in pytorch. Args: input: the input tensor. pad:...
188,593
import torch from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import IR func_name='torch.Tensor.chunk', backend='ncnn') def chunk__ncnn(self, num_chunks: int, dim: int = 0) -> torch.Tensor: """Rewrite `chunk` for NCNN backend. Chunk in ncnn are not supported, so it should be rewritten. ""...
Rewrite `chunk` for NCNN backend. Chunk in ncnn are not supported, so it should be rewritten.
188,594
import torch from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import IR func_name='torch.Tensor.chunk', backend='ncnn') def chunk__ncnn(self, num_chunks: int, dim: int = 0) -> torch.Tensor: """Rewrite `chunk` for NCNN backend. Chunk in ncnn are not supported, so it should be rewritten. ""...
Rewrite `chunk` for Torchscript. Replace chunk op with split op
188,595
import torch from mmdeploy.core import FUNCTION_REWRITER func_name='torch.Tensor.size', backend='ncnn') def tensor__size__ncnn(self, *args): """Rewrite `size` for ncnn backend. ONNX Shape node is not supported in ncnn. This function return integer instead of Torch.Size to avoid ONNX Shape node. """ ...
Rewrite `size` for ncnn backend. ONNX Shape node is not supported in ncnn. This function return integer instead of Torch.Size to avoid ONNX Shape node.
188,596
The provided code snippet includes necessary dependencies for implementing the `tensor__size__ascend` function. Write a Python function `def tensor__size__ascend(self, *args)` to solve the following problem: Rewrite `size` for ascens backend. Support negative index. Here is the function: def tensor__size__ascend(se...
Rewrite `size` for ascens backend. Support negative index.
188,597
The provided code snippet includes necessary dependencies for implementing the `normalize__ncnn` function. Write a Python function `def normalize__ncnn(input: torch.Tensor, p: int = 2, dim: int = 1, eps: float = 1e-12, *args, ...
Rewrite `normalize` for ncnn backend. Make sure L2 norm on channel dim and be exported to ncnn correctly.
188,598
The provided code snippet includes necessary dependencies for implementing the `norm__ncnn` function. Write a Python function `def norm__ncnn(input: torch.Tensor, p: Optional[Union[int, str]] = 'fro', dim: Optional[Union[int, Sequence]] = None, keepdim: Optional[bool] = Fa...
Rewrite `torch.norm` for ncnn backend. Rewrite torch.norm when p is Frobenius norm to avoid FP16 exceed in ncnn Android platform.
188,599
from typing import Iterable import torch from mmdeploy.core import FUNCTION_REWRITER func_name='torch.Tensor.__getitem__', backend='ascend') def tensor__getitem__ascend(self, key) -> torch.Tensor: """Rewrite `getitem` for ascend backend. Ascend does not support negative select """ ctx = FUNCTION_REW...
Rewrite `getitem` for ascend backend. Ascend does not support negative select
188,600
import torch from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import Backend func_name='torch.Tensor.clip', backend=Backend.COREML.value) func_name='torch.clip', backend=Backend.COREML.value) func_name='torch.Tensor.clamp', backend=Backend.COREML.value) func_name='torch.clamp', backend=Ba...
Rewrite `clip` for coreml backend. Cast data type.
188,601
from typing import Optional, Tuple, Union import torch from torch.autograd import Function from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import Backend, get_root_logger ctx = FUNCTION_REWRITER.get_context() input_size = input.shape return ctx.origin_func( input, None, ...
Rewrite `interpolate` for ncnn backend. ncnn require `size` should be constant in ONNX Node. We use `scale_factor` instead of `size` to avoid dynamic size.
188,602
from typing import Optional, Tuple, Union import torch from torch.autograd import Function from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import Backend, get_root_logger ctx = FUNCTION_REWRITER.get_context() input_size = input.shape return ctx.origin_func( input, None, ...
Rewrite `interpolate` for rknn backend. rknn require `size` should be constant in ONNX Node. We use `scale_factor` instead of `size` to avoid dynamic size.
188,603
from typing import Optional, Tuple, Union import torch from torch.autograd import Function from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import Backend, get_root_logger ctx = FUNCTION_REWRITER.get_context() input_size = input.shape return ctx.origin_func( input, None, ...
Register default symbolic function for `interpolate`.
188,604
The provided code snippet includes necessary dependencies for implementing the `mod__tensorrt` function. Write a Python function `def mod__tensorrt(input: torch.Tensor, other: Union[torch.Tensor, torch.NumberType], *args, **kwargs) -> torch.Tensor`...
Rewrite `mod` when exporting model to ONNX for TensorRT backend.
188,605
from typing import Sequence import torch from packaging.version import parse from mmdeploy.core import FUNCTION_REWRITER, SYMBOLIC_REWRITER if parse(torch.__version__) >= parse('1.12.0'): The provided code snippet includes necessary dependencies for implementing the `tensor__setitem__default` function. Write a Python ...
Rewrite `setitem` to ease the index put.
188,606
from typing import Sequence import torch from packaging.version import parse from mmdeploy.core import FUNCTION_REWRITER, SYMBOLIC_REWRITER def copy__default(g, x, y, non_blocking): return x
null
188,607
import torch from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import Backend func_name='torch.Tensor.flatten', backend=Backend.NCNN.value) func_name='torch.flatten', backend=Backend.NCNN.value) func_name='torch.Tensor.flatten', backend=Backend.COREML.value) func_name='torch.flatten', back...
Rewrite `flatten` for coreml backend. Use reshape instead of flatten
188,608
from typing import Optional import torch from mmdeploy.core import FUNCTION_REWRITER The provided code snippet includes necessary dependencies for implementing the `any__default` function. Write a Python function `def any__default(input: torch.Tensor, dim: Optional[str] = None, keepdi...
Rewrite `any` for ONNX.
188,609
The provided code snippet includes necessary dependencies for implementing the `topk__dynamic` function. Write a Python function `def topk__dynamic(input: torch.Tensor, k: int, dim: Optional[int] = None, largest: bool = True, sorted: bool = True)...
Rewrite `topk` for default backend. Cast k to tensor and make sure k is smaller than input.shape[dim].
188,610
TENSORRT_MAX_TOPK = 3840 The provided code snippet includes necessary dependencies for implementing the `topk__tensorrt` function. Write a Python function `def topk__tensorrt(input: torch.Tensor, k: int, dim: Optional[int] = None, largest: bool = True, ...
Rewrite `topk` for TensorRT backend. TensorRT does not support topk with dynamic k. This function cast k to constant integer.
188,611
The provided code snippet includes necessary dependencies for implementing the `topk__coreml` function. Write a Python function `def topk__coreml(input: torch.Tensor, k: int, dim: Optional[int] = None, largest: bool = True, sorted: bool = True)` to s...
Rewrite `topk` for coreml. Cast k to tensor and make sure k is smaller than input.shape[dim].
188,612
from torch import Tensor from mmdeploy.core import FUNCTION_REWRITER The provided code snippet includes necessary dependencies for implementing the `copy__default` function. Write a Python function `def copy__default(tensor: Tensor, *args, **kwargs) -> Tensor` to solve the following problem: Rewrite `copy.deepcopy` fo...
Rewrite `copy.deepcopy` for default backend. Replace it with tensor.clone(), or may raise `NYI: Named tensors are not supported with the tracer`
188,613
The provided code snippet includes necessary dependencies for implementing the `masked_fill__onnxruntime` function. Write a Python function `def masked_fill__onnxruntime( input, mask: torch.Tensor, value: Union[torch.Tensor, Number]) -> torch.Tensor` to solve th...
Rewrite `masked_fill` for onnxruntime backend. SATRN model as example, when value is set to `float('-inf')`, the results of ORT inferencing turns out to be NAN.
188,614
The provided code snippet includes necessary dependencies for implementing the `tensor__repeat__tensorrt` function. Write a Python function `def tensor__repeat__tensorrt(input: torch.Tensor, *size: Union[torch.Size, Sequence[int]])` to solve the following...
Rewrite `repeat` for TensorRT backend. Some layers in TensorRT can not be applied on batch axis. add extra axis before operation and remove it afterward.
188,615
import torch from mmdeploy.core import FUNCTION_REWRITER func_name='torch.Tensor.expand', backend='ncnn') def expand__ncnn(self, *sizes) -> torch.Tensor: """Rewrite `expand` for NCNN backend. Do not expand on batch dim for tensor with ndim >= 3 """ ctx = FUNCTION_REWRITER.get_context() if self.n...
Rewrite `expand` for NCNN backend. Do not expand on batch dim for tensor with ndim >= 3
188,616
import torch from torch.types import Number from mmdeploy.core import FUNCTION_REWRITER The provided code snippet includes necessary dependencies for implementing the `linspace__default` function. Write a Python function `def linspace__default(start: Number, end: Number, steps: int = None, **kwargs)` to solve the foll...
Rewrite `linspace` for onnxruntime.
188,617
from typing import Sequence import torch from torch import Tensor from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import get_dynamic_axes The provided code snippet includes necessary dependencies for implementing the `cat__tensorrt` function. Write a Python function `def cat__tensorrt(tensors: Sequence...
Rewrite `cat` for TensorRT backend. cat in TensorRT does not support bool or uint8 type when input is dynamic.
188,618
import torch from mmdeploy.core import FUNCTION_REWRITER func_name='torch.Tensor.__getattribute__', backend='ncnn') def tensor__getattribute__ncnn(self: torch.Tensor, name: str): """Rewrite `__getattribute__` of `torch.Tensor` for ncnn backend. Shape node is not supported by ncnn. This function transform dy...
Rewrite `__getattribute__` of `torch.Tensor` for ncnn backend. Shape node is not supported by ncnn. This function transform dynamic shape to constant shape.
188,619
import torch.nn.functional as F from torch.nn.modules.utils import _pair from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import Backend, get_root_logger, is_dynamic_shape The provided code snippet includes necessary dependencies for implementing the `adaptive_avg_pool2d__default` function. Write a Pyth...
Rewrite `adaptive_avg_pool2d` for default backend.
188,620
import torch.nn.functional as F from torch.nn.modules.utils import _pair from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import Backend, get_root_logger, is_dynamic_shape The provided code snippet includes necessary dependencies for implementing the `adaptive_avg_pool2d__ncnn` function. Write a Python ...
Rewrite `adaptive_avg_pool2d` for ncnn and torchscript backend.
188,621
import torch from mmdeploy.core import FUNCTION_REWRITER The provided code snippet includes necessary dependencies for implementing the `atan2__default` function. Write a Python function `def atan2__default( input1: torch.Tensor, input2: torch.Tensor, )` to solve the following problem: Rewrite `atan2` for defa...
Rewrite `atan2` for default backend.
188,622
import torch from mmdeploy.core import FUNCTION_REWRITER The provided code snippet includes necessary dependencies for implementing the `triu__default` function. Write a Python function `def triu__default(input: torch.Tensor, diagonal: int = 0, *args, **kwargs) -> ...
Rewrite `triu` for exporting model to ONNX.
188,623
from typing import Optional, Union import torch from mmdeploy.core import FUNCTION_REWRITER class GemmOp(torch.autograd.Function): """Create onnx::Gemm op.""" def forward(ctx, input, weight, bias=None): out = input @ weight.transpose(0, 1) if bias is not None: out += bias ret...
Rewrite `linear` for ncnn backend. The broadcast rules are different between ncnn and PyTorch. This function add extra reshape and transpose to support linear operation of different input shape.
188,624
import torch from torch import Tensor from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import Backend class MultiHeadAttentionop(torch.autograd.Function): """Create onnx::MultiHeadAttention op.""" def forward(ctx, q: Tensor, k: Tensor, v: Tensor, q_weight: Tensor, q_bias: Tensor, ...
Rewrite `forward` of MultiheadAttention used in vision_transformer for ncnn backend. Args: query (Tensor): The input query with shape [num_queries, bs, embed_dims] if self.batch_first is False, else [bs, num_queries embed_dims]. key (Tensor): The key tensor with shape [num_keys, bs, embed_dims] if self.batch_first is F...
188,625
from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import Backend The provided code snippet includes necessary dependencies for implementing the `patch_embed__forward__ncnn` function. Write a Python function `def patch_embed__forward__ncnn(self, x)` to solve the following problem: Rewrite `forward` of Pat...
Rewrite `forward` of PatchEmbed for ncnn backend. Args: x (Tensor): Has shape (B, C, H, W). In most case, C is 3. Returns: tuple: Contains merged results and its spatial shape. - x (Tensor): Has shape (B, out_h * out_w, embed_dims) - out_size (tuple[int]): Spatial shape of x, arrange as (out_h, out_w).
188,626
The provided code snippet includes necessary dependencies for implementing the `roi_align_rotated_default` function. Write a Python function `def roi_align_rotated_default(g, input: Tensor, rois: Tensor, output_size: List[int], spatial_scale: float, sampling...
Rewrite symbolic function for default backend. Replace onnx::RoIAlignRotated with mmdeploy::MMCVRoIAlignRotated. Args: ctx (ContextCaller): The context with additional information. g (Graph): The traced onnx graph. input (Tensor): Input tensor, 4-D feature map of shape (N, C, H, W). rois (Tensor): Bx5 boxes. First colu...
188,627
The provided code snippet includes necessary dependencies for implementing the `roi_align_default` function. Write a Python function `def roi_align_default(g, input: Tensor, rois: Tensor, output_size: List[int], spatial_scale: float, sampling_ratio: int, pool_mode: str, ali...
Rewrite symbolic function for default backend. Replace onnx::RoiAlign with mmcv::MMCVRoiAlign for PPLNN. For ONNXRuntime, align operation get done outside the inference engine for opset versions lower than 16. By default, onnx::RoiAlign get replaced to mmdeploy::MMCVRoiAlign. Args: ctx (ContextCaller): The context with...
188,628
import torch from packaging import version from torch import Tensor from torch.onnx import symbolic_helper as sym_help from mmdeploy.core import FUNCTION_REWRITER, mark from mmdeploy.utils import IR, is_dynamic_batch from mmdeploy.utils.constants import Backend from .nms_match import multiclass_nms_match from .nms_rota...
Create a dummy onnx::NonMaxSuppression op while exporting to ONNX. This function helps exporting to onnx with batch and multiclass NMS op. It only supports class-agnostic detection results. That is, the scores is of shape (N, num_bboxes, num_classes) and the boxes is of shape (N, num_boxes, 4). Args: boxes (Tensor): Th...
188,629
import torch from packaging import version from torch import Tensor from torch.onnx import symbolic_helper as sym_help from mmdeploy.core import FUNCTION_REWRITER, mark from mmdeploy.utils import IR, is_dynamic_batch from mmdeploy.utils.constants import Backend from .nms_match import multiclass_nms_match from .nms_rota...
Wrapper for `multiclass_nms` with TensorRT. Args: ctx (ContextCaller): The context with additional information. boxes (Tensor): The bounding boxes of shape [N, num_boxes, 4]. scores (Tensor): The detection scores of shape [N, num_boxes, num_classes]. max_output_boxes_per_class (int): Maximum number of output boxes per ...
188,630
import torch from packaging import version from torch import Tensor from torch.onnx import symbolic_helper as sym_help from mmdeploy.core import FUNCTION_REWRITER, mark from mmdeploy.utils import IR, is_dynamic_batch from mmdeploy.utils.constants import Backend from .nms_match import multiclass_nms_match from .nms_rota...
rewrite for coreml batched nms. Use coreml_nms from custom ops.
188,631
import torch from packaging import version from torch import Tensor from torch.onnx import symbolic_helper as sym_help from mmdeploy.core import FUNCTION_REWRITER, mark from mmdeploy.utils import IR, is_dynamic_batch from mmdeploy.utils.constants import Backend from .nms_match import multiclass_nms_match from .nms_rota...
rewrite for torchscript batched nms. Use batched_nms from torchvision instead of custom nms.
188,632
import torch from packaging import version from torch import Tensor from torch.onnx import symbolic_helper as sym_help from mmdeploy.core import FUNCTION_REWRITER, mark from mmdeploy.utils import IR, is_dynamic_batch from mmdeploy.utils.constants import Backend from .nms_match import multiclass_nms_match from .nms_rota...
Wrapper for `multiclass_nms` with Ascend. Args: ctx (ContextCaller): The context with additional information. boxes (Tensor): The bounding boxes of shape [N, num_boxes, 4]. scores (Tensor): The detection scores of shape [N, num_boxes, num_classes]. max_output_boxes_per_class (int): Maximum number of output boxes per cl...
188,633
import torch from torch import Tensor import mmdeploy from mmdeploy.core import FUNCTION_REWRITER, mark class TRTBatchedRotatedNMSop(torch.autograd.Function): """Create mmdeploy::TRTBatchedRotatedNMSop op for TensorRT backend. NMS in ONNX supports dynamic outputs. This class helps replace onnx::NonMaxSuppre...
Wrapper for `multiclass_nms` with TensorRT. Args: ctx (ContextCaller): The context with additional information. boxes (Tensor): The bounding boxes of shape [N, num_boxes, 5]. scores (Tensor): The detection scores of shape [N, num_boxes, num_classes]. max_output_boxes_per_class (int): Maximum number of output boxes per ...