id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
1,213 | from __future__ import print_function
import torch
import pickle
import numpy as np
import math
import cv2
from PIL import Image, JpegImagePlugin
from scipy import ndimage
import hashlib
import sys, os
from zipfile import ZipFile
from .imgproc import loadImage
def printProgressBar(prefix='', suffix='', decimals=1, leng... | null |
1,214 | from __future__ import print_function
import torch
import pickle
import numpy as np
import math
import cv2
from PIL import Image, JpegImagePlugin
from scipy import ndimage
import hashlib
import sys, os
from zipfile import ZipFile
from .imgproc import loadImage
def calculate_md5(fname):
hash_md5 = hashlib.md5()
... | null |
1,215 | from __future__ import print_function
import torch
import pickle
import numpy as np
import math
import cv2
from PIL import Image, JpegImagePlugin
from scipy import ndimage
import hashlib
import sys, os
from zipfile import ZipFile
from .imgproc import loadImage
def get_paragraph(raw_result, x_ths=1, y_ths=0.5, mode = '... | null |
1,216 | from __future__ import print_function
import torch
import pickle
import numpy as np
import math
import cv2
from PIL import Image, JpegImagePlugin
from scipy import ndimage
import hashlib
import sys, os
from zipfile import ZipFile
from .imgproc import loadImage
def reformat_input(image):
if type(image) == str:
... | reformats an image or list of images or a 4D numpy image array & returns a list of corresponding img, img_cv_grey nd.arrays image: [file path, numpy-array, byte stream object, list of file paths, list of numpy-array, 4D numpy array, list of byte stream objects] |
1,217 | from __future__ import print_function
import torch
import pickle
import numpy as np
import math
import cv2
from PIL import Image, JpegImagePlugin
from scipy import ndimage
import hashlib
import sys, os
from zipfile import ZipFile
from .imgproc import loadImage
def calculate_ratio(width,height):
def make_rotated_img_li... | null |
1,218 | from __future__ import print_function
import torch
import pickle
import numpy as np
import math
import cv2
from PIL import Image, JpegImagePlugin
from scipy import ndimage
import hashlib
import sys, os
from zipfile import ZipFile
from .imgproc import loadImage
The provided code snippet includes necessary dependencies ... | Select highest confidence augmentation for TTA Given a list of lists of results (outer list has one list per augmentation, inner lists index the images being recognized), choose the best result according to confidence level. Each "result" is of the form (box coords, text, confidence) A final_result is returned which co... |
1,219 | import torch
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from PIL import Image
from collections import OrderedDict
import cv2
import numpy as np
from .craft_utils import getDetBoxes, adjustResultCoordinates
from .imgproc import resize_aspect_ratio, normalizeMeanVariance
from .craft import C... | null |
1,220 | import torch
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from PIL import Image
from collections import OrderedDict
import cv2
import numpy as np
from .craft_utils import getDetBoxes, adjustResultCoordinates
from .imgproc import resize_aspect_ratio, normalizeMeanVariance
from .craft import C... | null |
1,221 | from PIL import Image
import torch
import torch.backends.cudnn as cudnn
import torch.utils.data
import torch.nn.functional as F
import torchvision.transforms as transforms
import numpy as np
from collections import OrderedDict
import importlib
from .utils import CTCLabelConverter
import math
def contrast_grey(img):
de... | null |
1,222 | from PIL import Image
import torch
import torch.backends.cudnn as cudnn
import torch.utils.data
import torch.nn.functional as F
import torchvision.transforms as transforms
import numpy as np
from collections import OrderedDict
import importlib
from .utils import CTCLabelConverter
import math
class CTCLabelConverter(ob... | null |
1,223 | from PIL import Image
import torch
import torch.backends.cudnn as cudnn
import torch.utils.data
import torch.nn.functional as F
import torchvision.transforms as transforms
import numpy as np
from collections import OrderedDict
import importlib
from .utils import CTCLabelConverter
import math
class ListDataset(torch.uti... | null |
1,224 | import os
import glob
from datetime import datetime
import subprocess
def print_error(errors, log_path):
if not isinstance(errors, list):
errors = [errors]
errors = [error if isinstance(error, bytes) else error.encode('utf-8') for error in errors]
url = "https://github.com/JaidedAI/EasyOCR/tree/ma... | null |
1,225 | import os
import glob
from datetime import datetime
import subprocess
def print_success(text, log_path):
with open(log_path, "wb") as fid:
fid.write((datetime.now().strftime("%H:%M:%S - %d %b %Y") + "\n").encode('utf-8'))
fid.write((text + "\n").encode('utf-8'))
print(text)
def validate_compila... | null |
1,226 | import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_bn(inp, oup, stride, conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, nlin_layer=nn.ReLU):
return nn.Sequential(
conv_layer(inp, oup, 3, stride, 1, bias=False),
norm_layer(oup),
nlin_layer(inplace=True)
) | null |
1,227 | import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_1x1_bn(inp, oup, conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, nlin_layer=nn.ReLU):
return nn.Sequential(
conv_layer(inp, oup, 1, 1, 0, bias=False),
norm_layer(oup),
nlin_layer(inplace=True)
) | null |
1,228 | import torch
import torch.nn as nn
import torch.nn.functional as F
def make_divisible(x, divisible_by=8):
import numpy as np
return int(np.ceil(x * 1. / divisible_by) * divisible_by) | null |
1,229 | import torch
import torch.nn as nn
import torch.nn.functional as F
class MobileNetV3(nn.Module):
def __init__(self, n_class=1000, input_size=224, dropout=0.8, mode='small', width_mult=1.0):
super(MobileNetV3, self).__init__()
input_channel = 16
last_channel = 1280
if mode == 'large':... | null |
1,230 | import torch
import torch.nn as nn
import torch.nn.functional as F
class MobileNetV3(nn.Module):
def __init__(self, n_class=1000, input_size=224, dropout=0.8, mode='small', width_mult=1.0):
super(MobileNetV3, self).__init__()
input_channel = 16
last_channel = 1280
if mode == 'large':... | null |
1,231 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
def constant_init(module, constant, bias=0):
nn.init.constant_(module.weight, constant)
if hasattr(module, 'bias'):
nn.init.constant_(module.bias, bias) | null |
1,232 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1)` to solve the following problem:
3x3 convolution with padding
Here is the... | 3x3 convolution with padding |
1,233 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth'... | Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,234 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth'... | Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,235 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth'... | Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,236 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth'... | Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,237 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth'... | Constructs a ResNet-50 model with deformable conv. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,238 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth'... | Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,239 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth'... | Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,240 | import os
import torch
import warnings
from torch.autograd import Function
from torch.nn.modules.utils import _pair
from torch.utils import cpp_extension
def custom_formatwarning(msg, *args, **kwargs):
# ignore everything except the message
return str(msg) + '\n' | null |
1,241 | import os
import warnings
import torch
from torch.autograd import Function
from torch.utils import cpp_extension
def custom_formatwarning(msg, *args, **kwargs):
# ignore everything except the message
return str(msg) + '\n' | null |
1,242 | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from .. import backbones
from .. import decoders
def parallelize(model, distributed, local_rank):
if distributed:
return nn.parallel.DistributedDataParallel(
model,
device_ids=[local_rank],
outp... | null |
1,243 | import torch
import torch.nn as nn
import torch.nn.init as init
import torchvision
from torchvision import models
from collections import namedtuple
from packaging import version
def init_weights(modules):
for m in modules:
if isinstance(m, nn.Conv2d):
init.xavier_uniform_(m.weight.data)
... | null |
1,244 | import os
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from .DBNet.DBNet import DBNet
class DBNet:
def __init__(self,
backbone = "resnet18",
weight_dir = None,
weight_name = 'pretrained',
initialize_model = True,
... | A wrapper to initialize DBNet text detection model Parameters ---------- trained_model : str Path to trained weight to use. backbone : str Backbone to use. Options are 'resnet18' or 'resnet50'. The default is 'resnet18'. device : str, optional Device to use. Options are "cpu" and "cuda". The default is 'cpu'. quantize ... |
1,245 | import os
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from .DBNet.DBNet import DBNet
def test_net(image,
detector,
threshold = 0.2,
bbox_min_score = 0.2,
bbox_min_size = 3,
max_candidates = 0,
canvas_size = None... | A compatibility wrapper to allow supporting calling this method while providing argument for other detector classes and reformat output accordingly. Parameters ---------- detector : obj DBNet text detection object. image : np.ndarray or list of np.ndarray OpenCV BGR image array or list of it. canvas_size : int, optiona... |
1,246 | import setuptools
import os
import os
requires = """torch>=1.8.0
transformers>=4.10.0
datasets>=1.17.0
sentencepiece>=0.1.96
tqdm>=4.62.2
decorator
rich
web.py
gitpython
scipy # need?
scikit-learn # need?
delta_center_client==0.0.4
bigmodelvis
"""
def get_requirements():
ret = [x for x in requires.split("\n") if l... | null |
1,247 | import sys
import datetime
import sphinx_rtd_theme
import doctest
import opendelta
rst_context = {'opendelta': opendelta}
def skip(app, what, name, obj, skip, options):
skip = include_only_tagged(app, what, name, obj, skip, options) or\
skip2(app, what, name, obj, skip, options)
return skip
def set... | null |
1,248 | import torch
import math
def glorot_normal(tensor: torch.Tensor):
return torch.nn.init.xavier_normal_(tensor, gain=math.sqrt(2)) | null |
1,249 | import torch
import math
def glorot_uniform(tensor: torch.Tensor):
return torch.nn.init.xavier_uniform_(tensor, gain=math.sqrt(2)) | null |
1,250 | import torch
import torch.nn as nn
from typing import Union, Optional
import torch.nn.functional as F
import torch
import math
from opendelta.delta_models.layers.init import glorot_uniform, glorot_normal
def kronecker_product(a, b):
"""
Kronecker product of matrices a and b with leading batch dimensions.
Ba... | Functional method to compute the generalized matrix-vector product based on the paper "Parameterization of Hypercomplex Multiplications (2020)" https://openreview.net/forum?id=rcQdycl0zyk y = Hx + b , where W is generated through the sum of kronecker products from the Parameterlist W, i.e. W is a an order-3 tensor of s... |
1,251 | from collections import OrderedDict
from multiprocessing.sharedctypes import Value
import os
from opendelta.delta_configs import BaseDeltaConfig
from opendelta.utils.inspect import inspect_module_statistics
from opendelta.utils.model_md5 import gen_model_hash
from opendelta.utils.signature import get_arg_names, signatu... | r"""Whether the module is a leaf module |
1,252 | from collections import OrderedDict
from multiprocessing.sharedctypes import Value
import os
from opendelta.delta_configs import BaseDeltaConfig
from opendelta.utils.inspect import inspect_module_statistics
from opendelta.utils.model_md5 import gen_model_hash
from opendelta.utils.signature import get_arg_names, signatu... | null |
1,253 |
The provided code snippet includes necessary dependencies for implementing the `create_hub_repo_name` function. Write a Python function `def create_hub_repo_name(root = "DeltaHub", dataset = None, delta_type = None, model_name_or_path = None, ... | r"""Currently, it's only a simple concatenation of the arguments. |
1,254 | from typing import List, Union
import re
The provided code snippet includes necessary dependencies for implementing the `superstring_in` function. Write a Python function `def superstring_in(str_a: str , list_b: List[str])` to solve the following problem:
r"""check whether there is any string in list b containing str_... | r"""check whether there is any string in list b containing str_a. Args: Returns: |
1,255 | from typing import List, Union
import re
The provided code snippet includes necessary dependencies for implementing the `is_child_key` function. Write a Python function `def is_child_key(str_a: str , list_b: List[str])` to solve the following problem:
r"""check whether a string in ``list_b`` is the child key in ``str_... | r"""check whether a string in ``list_b`` is the child key in ``str_a`` Args: Returns: |
1,256 | from typing import List, Union
import re
def endswith_in_normal(str_a: str , list_b: List[str]):
r"""check whether ``str_a`` has a substring that is in list_b.
Args:
Returns:
"""
return any(str_a.endswith(str_b) and (str_a==str_b or str_a[-len(str_b)-1] == ".") for str_b in list_b)
def endswith_in_... | null |
1,257 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
_lock = threading.L... | null |
1,258 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
log_levels = {
... | null |
1,259 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_ro... | Return the current level for the 🤗 Transformers's root logger as an int. Returns: :obj:`int`: The logging level. <Tip> 🤗 Transformers has following logging levels: - 50: ``transformers.logging.CRITICAL`` or ``transformers.logging.FATAL`` - 40: ``transformers.logging.ERROR`` - 30: ``transformers.logging.WARNING`` or `... |
1,260 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def set_verbosity(v... | Set the verbosity to the ``INFO`` level. |
1,261 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def set_verbosity(v... | Set the verbosity to the ``WARNING`` level. |
1,262 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def set_verbosity(v... | Set the verbosity to the ``DEBUG`` level. |
1,263 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def set_verbosity(v... | Set the verbosity to the ``ERROR`` level. |
1,264 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
_default_handler: O... | Disable the default handler of the HuggingFace Transformers's root logger. |
1,265 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
_default_handler: O... | Enable the default handler of the HuggingFace Transformers's root logger. |
1,266 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_ro... | adds a handler to the HuggingFace Transformers's root logger. |
1,267 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_ro... | removes given handler from the HuggingFace Transformers's root logger. |
1,268 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_ro... | Disable propagation of the library log outputs. Note that log propagation is disabled by default. |
1,269 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_ro... | Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to prevent double logging if the root logger has been configured. |
1,270 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_ro... | Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows: ``` [LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE ``` All handlers currently bound to the root logger are affected by this method. |
1,271 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_ro... | Resets the formatting for HuggingFace Transformers's loggers. All handlers currently bound to the root logger are affected by this method. |
1,272 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
The provided code ... | This method is identical to ``logger.warning()``, but if env var TRANSFORMERS_NO_ADVISORY_WARNINGS=1 is set, this warning will not be printed |
1,273 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
log_levels = {
... | Return a logger with the specified name. This function is not supposed to be directly accessed unless you are writing a custom transformers module. |
1,274 | from DeltaCenter import OssClient
from .file_utils import default_cache_path
default_cache_path = "{}/.cache/delta_center/".format(os.path.expanduser('~'))
def download(finetuned_delta_path, cache_dir=None, force_download=False):
if cache_dir is None:
cache_dir = default_cache_path
path_to_unzip_file ... | null |
1,275 | from bigmodelvis import Visualization
import web
import re, os
def dfs(o, depth, last, old_name):
html = ""
module_names = expand_part(o.module_name)
if depth > 0:
old_last_1 = last[-1]
if len(module_names) > 1:
module_names = [o.module_name] + module_names
for ith, module_name in en... | null |
1,276 | from typing import OrderedDict
import copy
import opendelta.utils.logging as logging
from bigmodelvis import Visualization
from opendelta.utils.common_structures import CoreMappings
def transform(org_key, mapping, strict=True, warning=False, verbose=False):
chain = org_key.split(".")
query = ""
node = mapp... | null |
1,277 | from opendelta.utils.decorate import decorate
from collections import OrderedDict
def sequential_caller(_org_func, org_module, delta_name, *args, **kwargs):
args = args[1:] # the first argument here is ``self``
delta_module = getattr(org_module, delta_name)
if hasattr(delta_module, "pre_forward"):
... | null |
1,278 | from opendelta.utils.decorate import decorate
from collections import OrderedDict
def before_caller(_org_func, org_module, delta_name, *args, **kwargs):
args = args[1:] # the first argument here is ``self``
delta_module = getattr(org_module, delta_name)
if hasattr(delta_module, "pre_forward"):
arg... | null |
1,279 | from opendelta.utils.decorate import decorate
from collections import OrderedDict
def after_caller(_org_func, org_module, delta_name, *args, **kwargs):
args = args[1:] # the first argument here is ``self``
delta_module = getattr(org_module, delta_name)
ret = _org_func(*args, **kwargs)
if hasattr(delta... | null |
1,280 | from opendelta.utils.decorate import decorate
from collections import OrderedDict
def parallel_caller(_org_func, org_module, delta_name, *args, **kwargs):
args = args[1:] # the first argument here is ``self``
delta_module = getattr(org_module, delta_name)
ret_1 = _org_func(*args, **kwargs)
ret_2 = delt... | null |
1,281 | from opendelta.utils.decorate import decorate
from collections import OrderedDict
caller_map = {
"sequential": sequential_caller,
"parallel": parallel_caller,
"before": before_caller,
"after": after_caller,
}
def decorate(func, caller, extras=(), kwsyntax=False):
"""
Decorates a function/genera... | r""" self is the parent module. |
1,282 | import inspect
from collections import namedtuple
def signature(f):
r"""Get the function f 's input arguments. A useful gadget
when some function slot might be instantiated into multiple functions.
Args:
f (:obj:`function`) : the function to get the input arguments.
Returns:
namedtuple :... | r""" Get a functions argument name, remove the ``self`` argument |
1,283 | import inspect
from collections import namedtuple
The provided code snippet includes necessary dependencies for implementing the `get_arg_names_inside_func` function. Write a Python function `def get_arg_names_inside_func(func)` to solve the following problem:
r""" Get the functions argument name inside the function i... | r""" Get the functions argument name inside the function itself. Remove ``self`` argument. |
1,284 | import hashlib
def gen_parameter_hash(generator, md5=None):
r"""Get parameter hash. From https://zhuanlan.zhihu.com/p/392942816
"""
if md5 is None:
md5 = hashlib.md5()
for arg in generator:
x = arg.data
if hasattr(x, "cpu"):
md5.update(x.cpu().numpy().data.tobytes()... | r"""Get model hash (structure and parameter) |
1,285 | import torch
import torch.nn as nn
from typing import Optional
import opendelta.utils.logging as logging
logger = logging.get_logger(__name__)
def num_trainable_parameters(module: Optional[nn.Module]=None):
r"""[NODOC] A small sugar function to get the number of trainable parameter in the backbone model. Often used... | r"""Get the statistics of the parameters in the delta modules. Args: module (:obj:`nn.Module`, *optional*): The module to compute the statistics. Returns: :obj:`dict`: The statistics of the parameters in the delta modules. |
1,286 | from typing import Union
import torch.nn as nn
import torch
def get_device(module : Union[nn.Module, nn.Parameter]):
if not (isinstance(module, nn.Module) \
or isinstance(module, nn.Parameter)):
raise RuntimeError("module is not a instance of torch.nn.Module")
if hasattr(module, 'device'):
... | null |
1,287 | from typing import Union
import torch.nn as nn
import torch
def get_dtype(module : Union[nn.Module, nn.Parameter]):
if not (isinstance(module, nn.Module) \
or isinstance(module, nn.Parameter)):
raise RuntimeError("module is not a instance of torch.nn.Module")
if hasattr(module, 'dtype'):
... | null |
1,288 | from typing import Union
import torch.nn as nn
import torch
def move_dict_to_cuda(dict_of_tensor, device):
for key in dict_of_tensor:
if isinstance(dict_of_tensor[key], torch.Tensor):
dict_of_tensor[key] = dict_of_tensor[key].to(device)
return dict_of_tensor | null |
1,289 | from copy import deepcopy
from typing import Any, Dict, OrderedDict
from bigmodelvis import Visualization
import torch.nn as nn
from opendelta.utils.logging import get_logger
import importlib
from opendelta.delta_configs import BaseDeltaConfig
from opendelta.basemodel import DeltaBase
def get_values(model_mapping):
... | null |
1,290 | from copy import deepcopy
from typing import Any, Dict, OrderedDict
from bigmodelvis import Visualization
import torch.nn as nn
from opendelta.utils.logging import get_logger
import importlib
from opendelta.delta_configs import BaseDeltaConfig
from opendelta.basemodel import DeltaBase
def getattribute_from_module(modu... | null |
1,291 | from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import f1_score, matthews_corrcoef
import datasets
def simple_accuracy(preds, labels):
return float((preds == labels).mean())
def acc_and_f1(preds, labels):
acc = simple_accuracy(preds, labels)
f1 = float(f1_score(y_true=labels, y_pred=preds)... | null |
1,292 | from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import f1_score, matthews_corrcoef
import datasets
def pearson_and_spearman(preds, labels):
pearson_corr = float(pearsonr(preds, labels)[0])
spearman_corr = float(spearmanr(preds, labels)[0])
return {
"pearson": pearson_corr,
... | null |
1,293 | import argparse
import dataclasses
import json
import logging
import os
from pathlib import Path
import random
import re
import sys
from dataclasses import dataclass, field
from typing import Optional
import datasets
import numpy as np
from datasets import load_dataset, load_metric
import transformers
from transformers... | null |
1,294 | import collections
import string
import regex as re
import numpy as np
def _normalize_answer(text, punc_chars, punc_repl):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(s):
return re.sub(r"\b(a|an|the)\b", " ", s)
def replace_punctuation(s):
to_replace = set(p... | Normalization used in official TriviaQA evaluation script. |
1,295 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
The provided code snippet includes necessary dependencies for implementing the `accuracy` function. Write a Python function `def accuracy(... | Computes the average accuracy. |
1,296 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
def string_to_float(string, default=-1., **unused_kwargs):
"""Converts string to float, using default when conversion not possible."""
... | Computes Pearson correlation coefficient. |
1,297 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
def string_to_float(string, default=-1., **unused_kwargs):
"""Converts string to float, using default when conversion not possible."""
... | Computes Spearman correlation coefficient. |
1,298 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
The provided code snippet includes necessary dependencies for implementing the `matthews_corrcoef` function. Write a Python function `def ... | Computes the Matthews correlation coefficient. |
1,299 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
f normalize_squad(answer):
"""Normalization used in official SQuAD evaluation script."""
return _normalize_answer(answer, punc_chars=s... | Computes SQuAD metrics, maximizing over answers per question. Args: targets: list of lists of strings predictions: list of strings Returns: dict with score_key: squad score across all targets and predictions |
1,300 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
The provided code snippet includes necessary dependencies for implementing the `exact_match` function. Write a Python function `def exact_... | Computes whether the targets match predictions exactly. |
1,301 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
def sklearn_metrics_wrapper(metric_str,
metric_dict_str=None,
metric_post_process_f... | Computes the unweighted average of the F1 per class. |
1,302 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
def f1_score_with_invalid(predictions, targets) -> dict:
"""Computes F1 score, with any prediction != 0 or 1 is counted as incorrect.
... | Special metric for MultiRC which computes F1 score over all examples. This is necessary because the targets/predictions for MultiRC are dicts and the f1_score_with_invalid expects a list of True/False labels, not dicts. As a result we just need to key in the "value" for each of the example dicts before feeding into f1_... |
1,303 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
The provided code snippet includes necessary dependencies for implementing the `mean_group_metric` function. Write a Python function `def ... | Returns a metric that averages `metric_fn` on sub-groups of results. The sub-groups are defined by aggregating results (targets and predictions) by accessing the feature specified by `group_key` in the target dicts. **WARNING**: Using this function can produce unreliable results if you do not pass in full groups. For e... |
1,304 | import functools
import logging
import torch
import os
import sys
import subprocess
from typing import Optional, List
from datasets import load_dataset, load_metric, concatenate_datasets
import transformers
from transformers import (
AutoConfig,
AutoModelForSeq2SeqLM,
AutoTokenizer,
HfArgumentParser,
... | null |
1,305 | import numpy as np
from typing import Union, NamedTuple, Tuple, Dict, Any
import os
import regex as re
import logging
from dataclasses import fields
import torch.nn as nn
import json
The provided code snippet includes necessary dependencies for implementing the `create_dir` function. Write a Python function `def ... | Checks whether to the output_dir already exists and creates it if not. Args: output_dir: path to the output_dir |
1,306 | import numpy as np
from typing import Union, NamedTuple, Tuple, Dict, Any
import os
import regex as re
import logging
from dataclasses import fields
import torch.nn as nn
import json
def get_last_checkpoint(output_dir):
if os.path.exists(os.path.join(output_dir, 'pytorch_model.bin')):
return output_di... | null |
1,307 | import numpy as np
from typing import Union, NamedTuple, Tuple, Dict, Any
import os
import regex as re
import logging
from dataclasses import fields
import torch.nn as nn
import json
The provided code snippet includes necessary dependencies for implementing the `pad_punctuation` function. Write a Python function ... | Re-implementation of _pad_punctuation in t5. This function adds spaces around punctuation. While this pads punctuation as expected, it has the unexpected effected of padding certain unicode characters with accents, with spaces as well. For instance: "François" becomes "Fran ç ois |
1,308 | import numpy as np
from typing import Union, NamedTuple, Tuple, Dict, Any
import os
import regex as re
import logging
from dataclasses import fields
import torch.nn as nn
import json
def save_json(filepath, dictionary):
with open(filepath, "w") as outfile:
json.dump(dictionary, outfile)
def read_json(file... | null |
1,309 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `round_stsb_target` function. Write a Python function `def round_stsb_target(label)` to solve the following problem:
STSB maps two sentences to a floating point number between 1 and 5 representing their semantic similarit... | STSB maps two sentences to a floating point number between 1 and 5 representing their semantic similarity. Since we are treating all tasks as text-to-text tasks we need to convert this floating point number to a string. The vast majority of the similarity score labels in STSB are in the set [0, 0.2, 0.4, ..., 4.8, 5.0]... |
1,310 | import os
import setuptools
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
def setup_package():
long_description = "examples_seq2seq"
setuptools.setup(
name='examples_seq2seq',
version='0.0.1',
description='seq2seq example',
long_description=long_description,
long... | null |
1,311 | import itertools
import torch
import tqdm
import multiprocessing
import numpy as np
import scipy.spatial as spatial
import scipy.special as special
import scipy.stats as stats
import logging
logger = logging.getLogger(__name__)
def select_likely_words(train_logits, train_labels, k_likely=1000, vocab=None, is_regression... | null |
1,312 | import collections
import inspect
import math
import os
import re
import shutil
import warnings
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
from packaging import version
from torch import nn
from torch.utils.data.dataloader import DataLoa... | Objective used for picking the best model on development sets |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.