repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
Pedestron | Pedestron-master/mmdet/ops/roi_pool/functions/roi_pool.py | import torch
from torch.autograd import Function
from .. import roi_pool_cuda
class RoIPoolFunction(Function):
@staticmethod
def forward(ctx, features, rois, out_size, spatial_scale):
if isinstance(out_size, int):
out_h = out_size
out_w = out_size
elif isinstance(out_... | 1,815 | 31.428571 | 74 | py |
Pedestron | Pedestron-master/mmdet/ops/roi_pool/modules/roi_pool.py | from torch.nn.modules.module import Module
from ..functions.roi_pool import roi_pool
class RoIPool(Module):
def __init__(self, out_size, spatial_scale):
super(RoIPool, self).__init__()
self.out_size = out_size
self.spatial_scale = float(spatial_scale)
def forward(self, features, roi... | 399 | 25.666667 | 74 | py |
Pedestron | Pedestron-master/mmdet/ops/nms/nms_wrapper.py | import numpy as np
import torch
from . import nms_cuda, nms_cpu
from .soft_nms_cpu import soft_nms_cpu
def nms(dets, iou_thr, device_id=None):
"""Dispatch to either CPU or GPU NMS implementations.
The input can be either a torch tensor or numpy array. GPU NMS will be used
if the input is a gpu tensor or... | 2,580 | 31.670886 | 79 | py |
RIB | RIB-main/run_sample.py | import argparse
import os
import numpy as np
from misc import pyutils
import torch
torch.set_num_threads(2)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# Environment
parser.add_argument("--num_workers", default=os.cpu_count()//2, type=int)
parser.add_argument("--voc12_root", defaul... | 6,117 | 38.470968 | 108 | py |
RIB | RIB-main/run_sample_coco.py | import argparse
import os
import numpy as np
from misc import pyutils
import torch
torch.set_num_threads(4)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# Environment
parser.add_argument("--num_workers", default=os.cpu_count()//2, type=int)
parser.add_argument("--voc12_root", def... | 6,257 | 39.374194 | 108 | py |
RIB | RIB-main/obtain_RIB_CAM_coco.py | import torch
from torch import multiprocessing, cuda
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.backends import cudnn
import numpy as np
import importlib
import argparse
import os
from numpy.linalg import lstsq
from scipy.linalg import orth
import voc12.dataloader
from misc impo... | 9,669 | 39.974576 | 164 | py |
RIB | RIB-main/obtain_RIB_CAM.py | import torch
from torch import multiprocessing, cuda
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.backends import cudnn
import numpy as np
import importlib
import argparse
import os
from numpy.linalg import lstsq
from scipy.linalg import orth
import voc12.dataloader
from misc impo... | 9,478 | 41.506726 | 162 | py |
RIB | RIB-main/voc12/dataloader.py |
import numpy as np
import torch
from torch.utils.data import Dataset
import os.path
import imageio
from misc import imutils
import random
IMG_FOLDER_NAME = "JPEGImages"
ANNOT_FOLDER_NAME = "Annotations"
IGNORE = 255
CAT_LIST = ['aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat', 'chair',
... | 13,505 | 34.171875 | 143 | py |
RIB | RIB-main/voc12/meta_dataloader.py |
import numpy as np
import torch
from torch.utils.data import Dataset
import os.path
import imageio
from misc import imutils
IMG_FOLDER_NAME = "JPEGImages"
ANNOT_FOLDER_NAME = "Annotations"
IGNORE = 255
CAT_LIST = ['aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat', 'chair',
'cow', ... | 6,388 | 31.267677 | 143 | py |
RIB | RIB-main/step/train_irn.py |
import torch
from torch.backends import cudnn
cudnn.enabled = True
from torch.utils.data import DataLoader
import voc12.dataloader
from misc import pyutils, torchutils, indexing
import importlib
def run(args):
path_index = indexing.PathIndex(radius=10, default_size=(args.irn_crop_size // 4, args.irn_crop_size //... | 5,306 | 46.383929 | 120 | py |
RIB | RIB-main/step/make_sem_seg_labels_coco.py | import torch
from torch import multiprocessing, cuda
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.backends import cudnn
import numpy as np
import importlib
import os
import imageio
import coco14.dataloader
from misc import torchutils, indexing
from PIL import Image
cudnn.enabled... | 5,146 | 45.790909 | 137 | py |
RIB | RIB-main/step/train_irn_coco.py |
import torch
from torch.backends import cudnn
cudnn.enabled = True
from torch.utils.data import DataLoader
import coco14.dataloader
from misc import pyutils, torchutils, indexing
import importlib
def run(args):
path_index = indexing.PathIndex(radius=10, default_size=(args.irn_crop_size // 4, args.irn_crop_size /... | 5,314 | 46.455357 | 120 | py |
RIB | RIB-main/step/train_cam_coco.py | import cv2
import torch
from torch.backends import cudnn
cudnn.enabled = True
from torch.utils.data import DataLoader
import torch.nn.functional as F
import importlib
import coco14.dataloader
from misc import pyutils, torchutils
from torch import autograd
import os
def validate(model, data_loader):
print('valid... | 4,074 | 34.745614 | 111 | py |
RIB | RIB-main/step/eval_cam.py |
import numpy as np
import os
from chainercv.datasets import VOCSemanticSegmentationDataset
from chainercv.evaluations import calc_semantic_segmentation_confusion
import torch
def run(args):
dataset = VOCSemanticSegmentationDataset(split=args.chainer_eval_set, data_dir=args.voc12_root)
# labels = [dataset.get_... | 1,843 | 37.416667 | 107 | py |
RIB | RIB-main/step/make_ins_seg_labels.py | import torch
from torch import multiprocessing, cuda
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.backends import cudnn
import numpy as np
import importlib
import os
import skimage
import voc12.dataloader
from misc import torchutils, imutils, pyutils, indexing
cudnn.enabled = Tr... | 6,400 | 36 | 117 | py |
RIB | RIB-main/step/train_cam.py |
import torch
from torch.backends import cudnn
cudnn.enabled = True
from torch.utils.data import DataLoader
import torch.nn.functional as F
import importlib
import voc12.dataloader
from misc import pyutils, torchutils
def validate(model, data_loader):
print('validating ... ', flush=True, end='')
val_loss_m... | 3,541 | 34.069307 | 111 | py |
RIB | RIB-main/step/make_sem_seg_labels.py | import torch
from torch import multiprocessing, cuda
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.backends import cudnn
import numpy as np
import importlib
import os
import imageio
import voc12.dataloader
from misc import torchutils, indexing
from PIL import Image
cudnn.enabled ... | 3,258 | 39.234568 | 137 | py |
RIB | RIB-main/step/make_cocoann.py | import numpy as np
import voc12.dataloader
from torch.utils.data import DataLoader
from pycococreatortools import pycococreatortools
import os
import json
VOC2012_JSON_FOLDER = ""
def run(args):
infer_dataset = voc12.dataloader.VOC12ImageDataset(args.infer_list, voc12_root=args.voc12_root)
infer_data_loader... | 1,774 | 33.134615 | 111 | py |
RIB | RIB-main/step/cam_to_ir_label_coco.py |
import os
import numpy as np
import imageio
from torch import multiprocessing
from torch.utils.data import DataLoader
import coco14.dataloader
from misc import torchutils, imutils
from PIL import Image
import torch
palette = [(0.0, 0.0, 0.0), (0.0, 0.0, 0.5), (0.0, 0.0, 1.0), (0.0, 0.25, 0.0), (0.0, 0.25, 0.5), (0.... | 4,850 | 47.51 | 129 | py |
RIB | RIB-main/step/cam_to_ir_label.py |
import os
import numpy as np
import imageio
from torch import multiprocessing
from torch.utils.data import DataLoader
import voc12.dataloader
from misc import torchutils, imutils
def _work(process_id, infer_dataset, args):
databin = infer_dataset[process_id]
infer_data_loader = DataLoader(databin, shuffle... | 2,108 | 36.660714 | 126 | py |
RIB | RIB-main/step/make_cam.py | import torch
from torch import multiprocessing, cuda
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.backends import cudnn
import numpy as np
import importlib
import os
import voc12.dataloader
from misc import torchutils, imutils
cudnn.enabled = True
def _work(process_id, model, d... | 2,760 | 34.857143 | 114 | py |
RIB | RIB-main/misc/indexing.py | import torch
import torch.nn.functional as F
import numpy as np
class PathIndex:
def __init__(self, radius, default_size):
self.radius = radius
self.radius_floor = int(np.ceil(radius) - 1)
self.search_paths, self.search_dst = self.get_search_paths_dst(self.radius)
self.path_indi... | 5,703 | 33.155689 | 129 | py |
RIB | RIB-main/misc/torchutils.py |
import torch
from torch.utils.data import Subset
import numpy as np
import math
class PolyOptimizer(torch.optim.SGD):
def __init__(self, params, lr, weight_decay, max_step, momentum=0.9):
super().__init__(params, lr, weight_decay)
self.global_step = 0
self.max_step = max_step
s... | 2,688 | 25.89 | 104 | py |
RIB | RIB-main/net/resnet50_cam.py | import torch.nn as nn
import torch.nn.functional as F
from misc import torchutils
from net import resnet50
import torch
class Net(nn.Module):
def __init__(self, coco=False):
super(Net, self).__init__()
self.resnet50 = resnet50.resnet50(pretrained=True, strides=(2, 2, 2, 1))
self.n_cls = 8... | 2,290 | 27.6375 | 118 | py |
RIB | RIB-main/net/resnet50_irn.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from net import resnet50
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# backbone
self.resnet50 = resnet50.resnet50(pretrained=True, strides=[2, 2, 2, 1])
self.stage1 = nn.Sequential(self.... | 8,641 | 35.931624 | 132 | py |
RIB | RIB-main/net/resnet50.py | import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth'
}
class FixedBatchNorm(nn.BatchNorm2d):
def forward(self, input):
return F.batch_norm(input, self.running_mean, self.r... | 3,912 | 31.882353 | 103 | py |
RIB | RIB-main/coco14/dataloader.py |
import numpy as np
import torch
from torch.utils.data import Dataset
import os.path
import imageio
from misc import imutils
import random
IMG_FOLDER_NAME = "JPEGImages"
ANNOT_FOLDER_NAME = "Annotations"
IGNORE = 255
# CAT_LIST = ['aeroplane', 'bicycle', 'bird', 'boat',
# 'bottle', 'bus', 'car', 'cat', 'chair... | 13,900 | 35.390052 | 135 | py |
pytorch | pytorch-main/setup.py | # Welcome to the PyTorch setup.py.
#
# Environment variables you are probably interested in:
#
# DEBUG
# build with -O0 and -g (debug symbols)
#
# REL_WITH_DEB_INFO
# build with optimizations and -g (debug symbols)
#
# MAX_JOBS
# maximum number of compile jobs we should use to compile your code
#
# ... | 48,866 | 36.59 | 126 | py |
pytorch | pytorch-main/tools/gen_vulkan_spv.py | #!/usr/bin/env python3
import argparse
import array
import copy
import glob
import os
import re
import sys
import subprocess
import textwrap
import yaml
from collections import OrderedDict
from torchgen.code_template import CodeTemplate
from dataclasses import dataclass
from typing import Any, Dict, List, Tuple, Optio... | 17,122 | 34.822176 | 118 | py |
pytorch | pytorch-main/tools/nightly.py | #!/usr/bin/env python3
# Much of the logging code here was forked from https://github.com/ezyang/ghstack
# Copyright (c) Edward Z. Yang <ezyang@mit.edu>
"""Checks out the nightly development version of PyTorch and installs pre-built
binaries into the repo.
You can use this script to check out a new nightly branch with... | 22,535 | 31.011364 | 119 | py |
pytorch | pytorch-main/tools/update_masked_docs.py | """This script updates the file torch/masked/_docs.py that contains
the generated doc-strings for various masked operations. The update
should be triggered whenever a new masked operation is introduced to
torch.masked package. Running the script requires that torch package
is functional.
"""
import os
def main() -> ... | 1,605 | 25.327869 | 74 | py |
pytorch | pytorch-main/tools/generate_torch_version.py | import argparse
import os
import re
import subprocess
from pathlib import Path
from typing import Optional, Union
from setuptools import distutils # type: ignore[import]
UNKNOWN = "Unknown"
RELEASE_PATTERN = re.compile(r"/v[0-9]+(\.[0-9]+)*(-rc[0-9]+)?/")
def get_sha(pytorch_root: Union[str, Path]) -> str:
tr... | 3,187 | 31.865979 | 84 | py |
pytorch | pytorch-main/tools/build_libtorch.py | import argparse
import sys
from os.path import abspath, dirname
# By appending pytorch_root to sys.path, this module can import other torch
# modules even when run as a standalone script. i.e., it's okay either you
# do `python build_libtorch.py` or `python -m tools.build_libtorch`.
pytorch_root = dirname(dirname(absp... | 1,128 | 33.212121 | 88 | py |
pytorch | pytorch-main/tools/build_pytorch_libs.py | import os
import platform
import shutil
from glob import glob
from typing import Dict, Optional
from setuptools import distutils # type: ignore[import]
from .setup_helpers.cmake import CMake, USE_NINJA
from .setup_helpers.env import check_negative_env_flag, IS_64BIT, IS_WINDOWS
def _overlay_windows_vcvars(env: Di... | 3,409 | 34.894737 | 84 | py |
pytorch | pytorch-main/tools/pyi/gen_pyi.py | import argparse
import collections
from pprint import pformat
from typing import Dict, List, Sequence
from torchgen.api.python import (
PythonSignatureGroup,
PythonSignatureNativeFunctionPair,
returns_named_tuple_pyi,
)
from torchgen.gen import parse_native_yaml
from torchgen.model import DispatchKey, Var... | 48,357 | 35.551776 | 127 | py |
pytorch | pytorch-main/tools/code_analyzer/gen_operators_yaml.py | #!/usr/bin/env python3
import argparse
import json
import sys
from typing import Any, Dict, List, Optional
import yaml
from gen_op_registration_allowlist import (
canonical_name,
gen_transitive_closure,
load_op_dep_graph,
)
from torchgen.selective_build.operator import (
merge_operator_dicts,
Selec... | 21,824 | 35.07438 | 128 | py |
pytorch | pytorch-main/tools/code_analyzer/gen_oplist.py | #!/usr/bin/env python3
import argparse
import json
import os
import sys
from functools import reduce
from typing import Any, List, Set
import yaml
from tools.lite_interpreter.gen_selected_mobile_ops_header import (
write_selected_mobile_ops,
)
from torchgen.selective_build.selector import (
combine_selective_b... | 6,444 | 33.465241 | 108 | py |
pytorch | pytorch-main/tools/lldb/pytorch_lldb.py | from typing import Any
import lldb # type: ignore[import]
def get_target() -> Any:
target = lldb.debugger.GetSelectedTarget()
if not target:
print("[-] error: no target available. please add a target to lldb.")
return None
return target
class DisableBreakpoints:
"""
Context-man... | 3,443 | 34.142857 | 101 | py |
pytorch | pytorch-main/tools/lldb/deploy_debugger.py | import lldb # type: ignore[import]
# load into lldb instance with:
# command script import tools/lldb/deploy_debugger.py
target = lldb.debugger.GetSelectedTarget()
bp = target.BreakpointCreateByRegex("__deploy_register_code")
bp.SetScriptCallbackBody(
"""\
process = frame.thread.GetProcess()
target = process.t... | 1,335 | 34.157895 | 79 | py |
pytorch | pytorch-main/tools/testing/explicit_ci_jobs.py | #!/usr/bin/env python3
import argparse
import fnmatch
import pathlib
import subprocess
import textwrap
from typing import Any, Dict, List
import yaml
REPO_ROOT = pathlib.Path(__file__).parent.parent.parent
CONFIG_YML = REPO_ROOT / ".circleci" / "config.yml"
WORKFLOWS_DIR = REPO_ROOT / ".github" / "workflows"
WOR... | 4,985 | 30.1625 | 132 | py |
pytorch | pytorch-main/tools/testing/test_selections.py | import heapq
import json
import math
import os
import subprocess
from pathlib import Path
from typing import Callable, Dict, List, NamedTuple, Optional, Set, Tuple
from warnings import warn
from tools.shared.logging_utils import duration_to_str, pluralize
from tools.stats.import_test_stats import get_disabled_tests,... | 12,124 | 33.74212 | 119 | py |
pytorch | pytorch-main/tools/testing/modulefinder_determinator.py | import modulefinder
import os
import pathlib
import sys
import warnings
from typing import Any, Dict, List, Set
REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent.parent
# These tests are slow enough that it's worth calculating whether the patch
# touched any related files first. This list was manually genera... | 6,168 | 30.798969 | 100 | py |
pytorch | pytorch-main/tools/coverage_plugins_package/setup.py | import setuptools # type: ignore[import]
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="coverage-plugins",
version="0.0.1",
author="PyTorch Team",
author_email="packages@pytorch.org",
description="plug-in to coverage for PyTorch JIT",... | 831 | 29.814815 | 67 | py |
pytorch | pytorch-main/tools/coverage_plugins_package/src/coverage_plugins/jit_plugin.py | """
This coverage plug-in attempts to cover JIT'd functions and methods that were previously missed in code coverage. Any
function and method that was passed through/decorated with torch.jit.script or torch.jit.script_method should now be
marked covered when coverage is run with this plug-in.
DISCLAIMER: note that thi... | 3,714 | 44.864198 | 120 | py |
pytorch | pytorch-main/tools/autograd/context.py | import functools
from typing import Callable
from torchgen.api.autograd import NativeFunctionWithDifferentiabilityInfo as NFWDI
from torchgen.context import native_function_manager
from torchgen.utils import T
# Like tools.api.context.with_native_function, but for
# NativeFunctionWithDifferentiabilityInfo.
def with_... | 943 | 28.5 | 82 | py |
pytorch | pytorch-main/tools/autograd/gen_annotated_fn_args.py | """
For procedural tests needed for __torch_function__, we use this function
to export method names and signatures as needed by the tests in
test/test_overrides.py.
python -m tools.autograd.gen_annotated_fn_args \
aten/src/ATen/native/native_functions.yaml \
aten/src/ATen/native/tags.yaml \
$OUTPU... | 4,383 | 32.723077 | 88 | py |
pytorch | pytorch-main/tools/autograd/gen_variable_factories.py | # Generates C++ functions that wrap ATen tensor factory methods to turn them into Variables.
#
# This writes one file: variable_factories.h
import re
from typing import List, Optional
import torchgen.api.python as python
from torchgen.api import cpp
from torchgen.api.types import CppSignatureGroup
from torchgen.cont... | 4,478 | 37.612069 | 106 | py |
pytorch | pytorch-main/tools/autograd/load_derivatives.py | # Parses derivatives.yaml into autograd functions
#
# Each autograd function is represented by `DifferentiabilityInfo` containing
# a list of `Derivative`. See `torchgen.api.autograd` for the data models.
import re
from collections import defaultdict
from typing import Any, Counter, Dict, List, Match, Optional, Sequenc... | 40,059 | 38.900398 | 132 | py |
pytorch | pytorch-main/tools/autograd/gen_autograd_functions.py | # Generates C++ autograd functions for the derivatives of ATen operations
#
# This writes two files:
# Functions.h/cpp: subclasses of autograd::Node
# python_functions.h/cpp: Python bindings for the above classes
#
from typing import Dict, List, Sequence, Tuple
from torchgen.api.autograd import (
Derivative,
... | 29,863 | 33.524855 | 123 | py |
pytorch | pytorch-main/tools/autograd/gen_python_functions.py | # Generates Python bindings for ATen functions
#
# The bindings are generated as methods on python_variable or functions on the
# torch._C._nn. torch._C._fft, torch._C._linalg, torch._C._nested, torch._C._sparse
# or torch._C._special objects.
#
# Code tries to stick to the following rules:
#
# - templates should be c... | 43,233 | 31.852584 | 130 | py |
pytorch | pytorch-main/tools/autograd/gen_trace_type.py | import itertools
from typing import Dict, List, Sequence, Union
from torchgen.api import cpp
from torchgen.api.types import DispatcherSignature
from torchgen.code_template import CodeTemplate
from torchgen.context import with_native_function
from torchgen.model import Argument, NativeFunction, SchemaKind, TensorOptio... | 19,391 | 34.386861 | 127 | py |
pytorch | pytorch-main/tools/autograd/gen_inplace_or_view_type.py | # Generates ADInplaceOrViewType.h/cpp
#
# NOTE: If any changes are being made to the ADInplaceOrView codegen please also check
# if updates are needed in torch/csrc/autograd/autograd_not_implemented_fallback.cpp
# The fallback is expected to mimick this codegen, so we should keep the two in sync.
from typing import Di... | 21,041 | 33.270358 | 127 | py |
pytorch | pytorch-main/tools/autograd/gen_variable_type.py | # Generates VariableType.h/cpp
#
# **If any changes are being made to the VariableType codegen please also check
# if updates are needed in torch/csrc/autograd/autograd_not_implemented_fallback.cpp
#
# VariableType is a subclass of at::Type that provides the binding code
# necessary to provide a differentiable version ... | 80,468 | 37.336827 | 123 | py |
pytorch | pytorch-main/tools/autograd/gen_autograd.py | """
To run this file by hand from the root of the PyTorch
repository, run:
python -m tools.autograd.gen_autograd \
aten/src/ATen/native/native_functions.yaml \
aten/src/ATen/native/tags.yaml \
$OUTPUT_DIR \
tools/autograd
Where $OUTPUT_DIR is where you would like the files to be
generated.... | 4,468 | 30.251748 | 88 | py |
pytorch | pytorch-main/tools/test/test_gen_backend_stubs.py | # Owner(s): ["module: codegen"]
import os
import tempfile
import unittest
from typing import Optional
import expecttest
from torchgen.gen import _GLOBAL_PARSE_NATIVE_YAML_CACHE # noqa: F401
from torchgen.gen_backend_stubs import run
path = os.path.dirname(os.path.realpath(__file__))
gen_backend_stubs_path = os.pat... | 11,187 | 34.744409 | 307 | py |
pytorch | pytorch-main/tools/test/test_executorch_signatures.py | import unittest
from torchgen.executorch.api.types import ExecutorchCppSignature
from torchgen.local import parametrize
from torchgen.model import Location, NativeFunction
DEFAULT_NATIVE_FUNCTION, _ = NativeFunction.from_yaml(
{"func": "foo.out(Tensor input, *, Tensor(a!) out) -> Tensor(a!)"},
loc=Location(__... | 2,392 | 39.559322 | 88 | py |
pytorch | pytorch-main/tools/test/test_codegen.py | import dataclasses
import typing
import unittest
from collections import defaultdict
from typing import Dict, List
import torchgen.model
import yaml
from tools.autograd import gen_autograd_functions, load_derivatives
from torchgen import dest
from torchgen.api.types import CppSignatureGroup, DispatcherSignature
from... | 19,375 | 36.84375 | 88 | py |
pytorch | pytorch-main/tools/test/test_executorch_custom_ops.py | import tempfile
import unittest
from typing import Any, Dict
from unittest.mock import ANY, Mock, patch
import expecttest
import torchgen
from torchgen.executorch.api.custom_ops import ComputeNativeFunctionStub
from torchgen.executorch.model import ETKernelIndex
from torchgen.gen_executorch import gen_headers
from to... | 4,404 | 34.813008 | 87 | py |
pytorch | pytorch-main/tools/test/test_executorch_types.py | import unittest
from torchgen import local
from torchgen.api.types import (
BaseCType,
ConstRefCType,
CType,
longT,
MutRefCType,
NamedCType,
OptionalCType,
TupleCType,
VectorCType,
voidT,
)
from torchgen.executorch.api.et_cpp import argument_type, return_type, returns_type
from ... | 3,943 | 34.854545 | 98 | py |
pytorch | pytorch-main/tools/test/test_create_alerts.py | from typing import Any, List
from unittest import main, TestCase
from tools.alerts.create_alerts import filter_job_names, JobStatus
JOB_NAME = "periodic / linux-xenial-cuda10.2-py3-gcc7-slow-gradcheck / test (default, 2, 2, linux.4xlarge.nvidia.gpu)"
MOCK_TEST_DATA = [
{
"sha": "f02f3046571d21b48af3067e3... | 2,710 | 35.635135 | 118 | py |
pytorch | pytorch-main/tools/test/test_executorch_unboxing.py | import unittest
from types import ModuleType
from torchgen import local
from torchgen.api import cpp as aten_cpp, types as aten_types
from torchgen.api.types import (
ArgName,
BaseCType,
ConstRefCType,
MutRefCType,
NamedCType,
)
from torchgen.executorch.api import et_cpp as et_cpp, types as et_type... | 7,371 | 40.649718 | 98 | py |
pytorch | pytorch-main/tools/test/test_executorch_gen.py | import os
import tempfile
import unittest
from typing import Dict
import yaml
from torchgen.executorch.model import ETKernelIndex, ETKernelKey
from torchgen.gen import LineLoader
from torchgen.gen_executorch import (
ComputeCodegenUnboxedKernels,
gen_functions_declarations,
parse_yaml_files,
translat... | 18,631 | 30.105175 | 132 | py |
pytorch | pytorch-main/tools/test/test_selective_build.py | import unittest
from torchgen.selective_build.operator import * # noqa: F403
from torchgen.model import Location, NativeFunction
from torchgen.selective_build.selector import (
combine_selective_builders,
SelectiveBuilder,
)
class TestSelectiveBuild(unittest.TestCase):
def test_selective_build_operator(... | 11,522 | 32.594752 | 87 | py |
pytorch | pytorch-main/tools/test/test_codegen_model.py | # Owner(s): ["module: codegen"]
import textwrap
import unittest
from typing import cast
import expecttest
import torchgen.dest as dest
import torchgen.gen as gen
import yaml
from torchgen.gen import LineLoader, parse_native_yaml_struct
from torchgen.model import (
Annotation,
CustomClassType,
DispatchKey... | 6,825 | 31.975845 | 93 | py |
pytorch | pytorch-main/tools/test/test_utils.py | import unittest
from torchgen.utils import NamespaceHelper
class TestNamespaceHelper(unittest.TestCase):
def test_create_from_namespaced_tuple(self) -> None:
helper = NamespaceHelper.from_namespaced_entity("aten::add")
self.assertEqual(helper.entity_name, "add")
self.assertEqual(helper.ge... | 870 | 36.869565 | 79 | py |
pytorch | pytorch-main/tools/alerts/create_alerts.py | #!/usr/bin/env python3
import argparse
import json
import os
import re
from collections import defaultdict
from difflib import SequenceMatcher
from typing import Any, Dict, List, Set, Tuple
import requests
from setuptools import distutils # type: ignore[import]
ALL_SKIPPED_THRESHOLD = 100
SIMILARITY_THRESHOLD = 0.7... | 10,027 | 30.534591 | 101 | py |
pytorch | pytorch-main/tools/code_coverage/package/util/utils.py | import os
import shutil
import sys
import time
from typing import Any, NoReturn, Optional
from .setting import (
CompilerType,
LOG_DIR,
PROFILE_DIR,
TestList,
TestPlatform,
TestType,
)
def convert_time(seconds: float) -> str:
seconds = int(round(seconds))
seconds = seconds % (24 * 360... | 4,229 | 27.389262 | 103 | py |
pytorch | pytorch-main/tools/code_coverage/package/tool/print_report.py | import os
import subprocess
from typing import Dict, IO, List, Set, Tuple
from ..oss.utils import get_pytorch_folder
from ..util.setting import SUMMARY_FOLDER_DIR, TestList, TestStatusType
CoverageItem = Tuple[str, float, int, int]
def key_by_percentage(x: CoverageItem) -> float:
return x[1]
def key_by_name(x... | 7,192 | 29.739316 | 119 | py |
pytorch | pytorch-main/tools/code_coverage/package/tool/utils.py | import subprocess
from ..util.setting import TestPlatform
from ..util.utils import print_error
def run_cpp_test(binary_file: str) -> None:
# cpp test binary
try:
subprocess.check_call(binary_file)
except subprocess.CalledProcessError:
print_error(f"Binary failed to run: {binary_file}")
... | 783 | 29.153846 | 95 | py |
pytorch | pytorch-main/tools/code_coverage/package/tool/summarize_jsons.py | import json
import os
import time
from typing import Any, Dict, List, Set, Tuple
from ..util.setting import (
CompilerType,
JSON_FOLDER_BASE_DIR,
TestList,
TestPlatform,
TestStatusType,
)
from ..util.utils import (
detect_compiler_type,
print_error,
print_time,
related_to_test_list,... | 7,481 | 33.479263 | 118 | py |
pytorch | pytorch-main/tools/code_coverage/package/tool/clang_coverage.py | import os
import subprocess
import time
from typing import List
from ..util.setting import (
JSON_FOLDER_BASE_DIR,
MERGED_FOLDER_BASE_DIR,
TestList,
TestPlatform,
TestType,
)
from ..util.utils import (
check_platform_type,
convert_to_relative_path,
create_folder,
get_raw_profiles_fo... | 6,647 | 36.348315 | 123 | py |
pytorch | pytorch-main/tools/code_coverage/package/oss/utils.py | import os
import subprocess
from typing import List, Optional
from ..util.setting import CompilerType, TestType, TOOLS_FOLDER
from ..util.utils import print_error, remove_file
def get_oss_binary_folder(test_type: TestType) -> str:
assert test_type in {TestType.CPP, TestType.PY}
# TODO: change the way we get ... | 3,217 | 31.836735 | 99 | py |
pytorch | pytorch-main/tools/code_coverage/package/oss/init.py | import argparse
import os
from typing import cast, List, Optional, Tuple
from ..util.setting import (
CompilerType,
JSON_FOLDER_BASE_DIR,
LOG_DIR,
Option,
Test,
TestList,
TestType,
)
from ..util.utils import (
clean_up,
create_folder,
print_log,
raise_no_test_found_exception... | 5,155 | 29.508876 | 126 | py |
pytorch | pytorch-main/tools/jit/gen_unboxing.py | # Generates RegisterCodegenUnboxedKernels.cpp, UnboxingFunctions.h and UnboxingFunctions.cpp.
import argparse
import os
import pathlib
import sys
from dataclasses import dataclass
from typing import List, Literal, Sequence, Union
import yaml
from torchgen.api import cpp, unboxing
from torchgen.api.translate import tr... | 10,544 | 36 | 115 | py |
pytorch | pytorch-main/tools/lite_interpreter/gen_selected_mobile_ops_header.py | #!/usr/bin/env python3
import argparse
import os
from typing import Set
import yaml
from torchgen.code_template import CodeTemplate
from torchgen.selective_build.selector import SelectiveBuilder
# Safely load fast C Yaml loader/dumper if they are available
try:
from yaml import CSafeLoader as Loader
except Import... | 6,074 | 32.563536 | 132 | py |
pytorch | pytorch-main/tools/gdb/pytorch-gdb.py | import textwrap
from typing import Any
import gdb # type: ignore[import]
class DisableBreakpoints:
"""
Context-manager to temporarily disable all gdb breakpoints, useful if
there is a risk to hit one during the evaluation of one of our custom
commands
"""
def __enter__(self) -> None:
... | 1,843 | 30.254237 | 80 | py |
pytorch | pytorch-main/tools/onnx/update_default_opset_version.py | #!/usr/bin/env python3
"""Updates the default value of opset_version.
The current policy is that the default should be set to the
latest released version as of 18 months ago.
Usage:
Run with no arguments.
"""
import argparse
import datetime
import os
import pathlib
import re
import subprocess
import sys
from subpro... | 3,345 | 27.844828 | 108 | py |
pytorch | pytorch-main/tools/onnx/gen_diagnostics.py | #!/usr/bin/env python3
""" Generates PyTorch ONNX Export Diagnostic rules for C++, Python and documentations.
The rules are defined in torch/onnx/_internal/diagnostics/rules.yaml.
Usage:
python -m tools.onnx.gen_diagnostics \
torch/onnx/_internal/diagnostics/rules.yaml \
torch/onnx/_internal/diagnostics \
... | 7,702 | 28.972763 | 95 | py |
pytorch | pytorch-main/tools/setup_helpers/cmake_utils.py | """
This is refactored from cmake.py to avoid circular imports issue with env.py,
which calls get_cmake_cache_variables_from_file
"""
import re
from typing import Dict, IO, Optional, Union
CMakeValue = Optional[Union[bool, str]]
def convert_cmake_value_to_python_value(
cmake_value: str, cmake_type: str
) -> CM... | 2,895 | 32.674419 | 120 | py |
pytorch | pytorch-main/tools/setup_helpers/gen.py | # Little stub file to get BUILD.bazel to play along
import os.path
import sys
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, root)
import torchgen.gen
torchgen.gen.main()
| 231 | 18.333333 | 83 | py |
pytorch | pytorch-main/tools/setup_helpers/generate_code.py | import argparse
import os
import pathlib
import sys
from typing import Any, cast, Optional
import yaml
try:
# use faster C loader if available
from yaml import CSafeLoader as YamlLoader
except ImportError:
from yaml import SafeLoader as YamlLoader # type: ignore[assignment, misc]
NATIVE_FUNCTIONS_PATH =... | 8,265 | 33.877637 | 115 | py |
pytorch | pytorch-main/tools/setup_helpers/cmake.py | "Manages CMake."
import multiprocessing
import os
import platform
import sys
import sysconfig
from distutils.version import LooseVersion
from subprocess import CalledProcessError, check_call, check_output
from typing import Any, cast, Dict, List, Optional
from . import which
from .cmake_utils import CMakeValue, get_... | 16,776 | 40.630273 | 123 | py |
pytorch | pytorch-main/tools/dynamo/verify_dynamo.py | import os
import re
import subprocess
import sys
import traceback
import warnings
from pkg_resources import packaging
MIN_CUDA_VERSION = packaging.version.parse("11.6")
MIN_ROCM_VERSION = packaging.version.parse("5.4")
MIN_PYTHON_VERSION = (3, 8)
class VerifyDynamoError(BaseException):
pass
def check_python()... | 6,704 | 28.537445 | 96 | py |
pytorch | pytorch-main/tools/amd_build/build_amd.py | #!/usr/bin/env python3
import argparse
import os
import sys
sys.path.append(
os.path.realpath(
os.path.join(
__file__, os.path.pardir, os.path.pardir, os.path.pardir, "torch", "utils"
)
)
)
from hipify import hipify_python # type: ignore[import]
parser = argparse.ArgumentParser... | 6,172 | 29.711443 | 87 | py |
pytorch | pytorch-main/tools/stats/upload_test_stats.py | import argparse
import os
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Any, Dict, List, Tuple
from tools.stats.upload_stats_lib import (
download_gha_artifacts,
download_s3_artifacts,
unzip,
upload_workflow_stats_to_s3... | 11,899 | 31.336957 | 94 | py |
pytorch | pytorch-main/tools/stats/upload_stats_lib.py | import datetime
import gzip
import inspect
import io
import json
import os
import time
import uuid
import zipfile
from decimal import Decimal
from pathlib import Path
from typing import Any, Dict, List
from warnings import warn
import boto3 # type: ignore[import]
import requests
import rockset # type: ignore[import... | 11,091 | 31.244186 | 114 | py |
pytorch | pytorch-main/tools/stats/upload_external_contrib_stats.py | import argparse
import datetime
import json
import os
import time
import urllib.parse
from typing import Any, Callable, cast, Dict, List, Optional, Set
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from tools.stats.upload_stats_lib import upload_to_s3
FILTER_OUT_USERS = {
"pytorc... | 4,993 | 31.012821 | 124 | py |
pytorch | pytorch-main/tools/stats/upload_test_stat_aggregates.py | import argparse
import ast
import datetime
import json
import os
import re
from typing import Any, List, Union
import rockset # type: ignore[import]
from tools.stats.upload_stats_lib import upload_to_s3
def get_oncall_from_testfile(testfile: str) -> Union[List[str], None]:
path = f"test/{testfile}"
if not ... | 2,962 | 33.858824 | 97 | py |
pytorch | pytorch-main/tools/stats/upload_artifacts.py | import argparse
import os
import re
from tempfile import TemporaryDirectory
from tools.stats.upload_stats_lib import download_gha_artifacts, upload_file_to_s3
ARTIFACTS = [
"sccache-stats",
"test-jsons",
"test-reports",
"usage-log",
]
BUCKET_NAME = "gha-artifacts"
FILENAME_REGEX = r"-runattempt\d+"
... | 2,063 | 32.290323 | 103 | py |
pytorch | pytorch-main/tools/stats/export_test_times.py | import pathlib
import sys
REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent.parent
sys.path.append(str(REPO_ROOT))
from tools.stats.import_test_stats import get_test_times
TEST_TIMES_FILE = ".pytorch-test-times.json"
def main() -> None:
print(f"Exporting test times from test-infra to {TEST_TIMES_FILE}"... | 423 | 22.555556 | 71 | py |
pytorch | pytorch-main/tools/stats/import_test_stats.py | #!/usr/bin/env python3
import datetime
import json
import os
import pathlib
from typing import Any, Callable, cast, Dict, List, Optional
from urllib.request import urlopen
def get_disabled_issues() -> List[str]:
reenabled_issues = os.getenv("REENABLED_ISSUES", "")
issue_numbers = reenabled_issues.split(",")
... | 4,309 | 35.218487 | 102 | py |
pytorch | pytorch-main/tools/stats/upload_dynamo_perf_stats.py | import argparse
import csv
import os
import re
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Any, Dict, List
from tools.stats.upload_stats_lib import download_s3_artifacts, unzip, upload_to_rockset
ARTIFACTS = [
"test-reports",
]
ARTIFACT_REGEX = re.compile(
r"test-repor... | 3,821 | 31.117647 | 99 | py |
pytorch | pytorch-main/tools/linter/adapters/clangformat_linter.py | import argparse
import concurrent.futures
import json
import logging
import os
import subprocess
import sys
import time
from enum import Enum
from pathlib import Path
from typing import Any, List, NamedTuple, Optional
IS_WINDOWS: bool = os.name == "nt"
def eprint(*args: Any, **kwargs: Any) -> None:
print(*args,... | 6,922 | 26.803213 | 118 | py |
pytorch | pytorch-main/tools/linter/adapters/testowners_linter.py | #!/usr/bin/env python3
"""
Test ownership was introduced in https://github.com/pytorch/pytorch/issues/66232.
This lint verifies that every Python test file (file that matches test_*.py or *_test.py in the test folder)
has valid ownership information in a comment header. Valid means:
- The format of the header follow... | 4,708 | 28.248447 | 108 | py |
pytorch | pytorch-main/tools/linter/adapters/black_linter.py | import argparse
import concurrent.futures
import json
import logging
import os
import subprocess
import sys
import time
from enum import Enum
from typing import Any, BinaryIO, List, NamedTuple, Optional
IS_WINDOWS: bool = os.name == "nt"
def eprint(*args: Any, **kwargs: Any) -> None:
print(*args, file=sys.stder... | 6,244 | 26.390351 | 79 | py |
pytorch | pytorch-main/tools/linter/clang_tidy/generate_build_files.py | import os
import subprocess
import sys
from typing import List
def run_cmd(cmd: List[str]) -> None:
print(f"Running: {cmd}")
result = subprocess.run(
cmd,
capture_output=True,
)
stdout, stderr = (
result.stdout.decode("utf-8").strip(),
result.stderr.decode("utf-8").stri... | 1,529 | 20.857143 | 68 | py |
pytorch | pytorch-main/modules/detectron/upsample_nearest_op_test.py |
import unittest
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
from caffe2.python import core, dyndep
from hypothesis import given, settings
dyndep.InitOpsLibrary("@/caffe2/modules/detectron:detectron_ops")
class TestUpsampleNearestOp(hu.HypothesisTestCase):
... | 1,273 | 27.954545 | 86 | py |
pytorch | pytorch-main/benchmarks/upload_scribe.py | """Scribe Uploader for Pytorch Benchmark Data
Currently supports data in pytest-benchmark format but can be extended.
New fields can be added just by modifying the schema in this file, schema
checking is only here to encourage reusing existing fields and avoiding typos.
"""
import argparse
import time
import json
im... | 5,415 | 37.964029 | 98 | py |
pytorch | pytorch-main/benchmarks/profiler_benchmark/profiler_bench.py | import argparse
import sys
import timeit
import torch
from torch.utils.benchmark import Timer
PARALLEL_TASKS_NUM = 4
INTERNAL_ITER = None
def loop_workload(x):
for i in range(INTERNAL_ITER):
x = torch.mm(x, x)
return x
def parallel_workload(x):
def parallel_task(x):
for i in range(int(INT... | 3,469 | 33.356436 | 118 | py |
pytorch | pytorch-main/benchmarks/profiler_benchmark/resnet_memory_profiler.py | import torch
import torchvision.models as models
import torch.autograd.profiler as profiler
for with_cuda in [False, True]:
model = models.resnet18()
inputs = torch.randn(5, 3, 224, 224)
sort_key = "self_cpu_memory_usage"
if with_cuda and torch.cuda.is_available():
model = model.cuda()
... | 732 | 30.869565 | 93 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.