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 |
|---|---|---|---|---|---|---|
pytorch | pytorch-main/.github/scripts/trymerge_explainer.py | import os
import re
from typing import List, Optional, Pattern, Tuple
BOT_COMMANDS_WIKI = "https://github.com/pytorch/pytorch/wiki/Bot-commands"
CIFLOW_LABEL = re.compile(r"^ciflow/.+")
CIFLOW_TRUNK_LABEL = re.compile(r"^ciflow/trunk")
OFFICE_HOURS_LINK = "https://github.com/pytorch/pytorch/wiki/Dev-Infra-Office-Ho... | 2,994 | 29.561224 | 114 | py |
pytorch | pytorch-main/.github/scripts/comment_on_pr.py | import os
from typing import Any
from github_utils import gh_post_pr_comment
from gitutils import get_git_remote_name, get_git_repo_dir, GitRepo
from trymerge_explainer import BOT_COMMANDS_WIKI
def parse_args() -> Any:
from argparse import ArgumentParser
parser = ArgumentParser("Comment on a PR")
parser... | 1,034 | 27.75 | 87 | py |
pytorch | pytorch-main/.github/scripts/test_fetch_latest_green_commit.py | from typing import Any, Dict, List
from unittest import main, mock, TestCase
from fetch_latest_green_commit import isGreen, WorkflowCheck
workflowNames = [
"pull",
"trunk",
"Lint",
"linux-binary-libtorch-pre-cxx11",
"android-tests",
"windows-binary-wheel",
"periodic",
"docker-release-b... | 5,380 | 35.114094 | 85 | py |
pytorch | pytorch-main/.github/scripts/tryrebase.py | #!/usr/bin/env python3
import contextlib
import os
import re
import subprocess
import sys
from typing import Any, Generator
from github_utils import gh_post_pr_comment as gh_post_comment
from gitutils import get_git_remote_name, get_git_repo_dir, GitRepo
from trymerge import GitHubPR
SAME_SHA_ERROR = (
"\n```\nA... | 8,287 | 35.350877 | 106 | py |
pytorch | pytorch-main/.github/scripts/update_commit_hashes.py | import json
import os
import subprocess
from argparse import ArgumentParser
from typing import Any, Dict
import requests
UPDATEBOT_TOKEN = os.environ["UPDATEBOT_TOKEN"]
PYTORCHBOT_TOKEN = os.environ["PYTORCHBOT_TOKEN"]
OWNER, REPO = "pytorch", "pytorch"
def git_api(
url: str, params: Dict[str, str], type: str =... | 5,419 | 30.695906 | 128 | py |
pytorch | pytorch-main/.github/scripts/test_tryrebase.py | from typing import Any
from unittest import main, mock, TestCase
from gitutils import get_git_remote_name, get_git_repo_dir, GitRepo
from test_trymerge import mocked_gh_graphql
from trymerge import GitHubPR
from tryrebase import rebase_ghstack_onto, rebase_onto
def mocked_rev_parse(branch: str) -> str:
return br... | 5,909 | 36.405063 | 109 | py |
pytorch | pytorch-main/.github/scripts/trymerge.py | #!/usr/bin/env python3
# NB: the following functions are used in Meta-internal workflows
# (github_first_try_merge/my_handler.py) and thus have functionality limitations
# (no `git` command access, no network access besides the strict allow list):
#
# find_matching_merge_rule
# read_merge_rules
#
# Also any signature ... | 71,735 | 33.405755 | 130 | py |
pytorch | pytorch-main/.github/scripts/collect_ciflow_labels.py | #!/usr/bin/env python3
import sys
from pathlib import Path
from typing import Any, cast, Dict, List, Set
import yaml
GITHUB_DIR = Path(__file__).parent.parent
def get_workflows_push_tags() -> Set[str]:
"Extract all known push tags from workflows"
rc: Set[str] = set()
for fname in (GITHUB_DIR / "workflow... | 2,525 | 33.60274 | 85 | py |
pytorch | pytorch-main/.github/scripts/get_workflow_job_id.py | # Helper to get the id of the currently running job in a GitHub Actions
# workflow. GitHub does not provide this information to workflow runs, so we
# need to figure it out based on what they *do* provide.
import argparse
import json
import os
import re
import sys
import time
import urllib
import urllib.parse
from ty... | 5,047 | 32.879195 | 96 | py |
pytorch | pytorch-main/.github/scripts/test_label_utils.py | from typing import Any
from unittest import main, mock, TestCase
from label_utils import (
get_last_page_num_from_header,
gh_get_labels,
has_required_labels,
)
from test_trymerge import mocked_gh_graphql
from trymerge import GitHubPR
release_notes_labels = [
"release notes: nn",
]
class TestLabelUt... | 3,360 | 34.010417 | 90 | py |
pytorch | pytorch-main/.github/scripts/gitutils.py | #!/usr/bin/env python3
import os
import re
import tempfile
from collections import defaultdict
from datetime import datetime
from functools import wraps
from typing import (
Any,
Callable,
cast,
Dict,
Iterator,
List,
Optional,
Tuple,
TypeVar,
Union,
)
T = TypeVar("T")
RE_GITHU... | 14,831 | 34.568345 | 110 | py |
pytorch | pytorch-main/.github/scripts/test_check_labels.py | """test_check_labels.py"""
from typing import Any, List
from unittest import main, mock, TestCase
from check_labels import (
add_label_err_comment,
delete_all_label_err_comments,
main as check_labels_main,
)
from github_utils import GitHubComment
from label_utils import BOT_AUTHORS, LABEL_ERR_MSG_TITLE
fr... | 5,158 | 35.076923 | 88 | py |
pytorch | pytorch-main/.github/scripts/generate_binary_build_matrix.py | #!/usr/bin/env python3
"""Generates a matrix to be utilized through github actions
Will output a condensed version of the matrix if on a pull request that only
includes the latest version of python we support built on three different
architectures:
* CPU
* Latest CUDA
* Latest ROCM
"""
from typing import... | 10,733 | 37.473118 | 174 | py |
pytorch | pytorch-main/.github/scripts/generate_ci_workflows.py | #!/usr/bin/env python3
import os
import sys
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Dict, Iterable, List, Literal, Set
import generate_binary_build_matrix # type: ignore[import]
import jinja2
from typing_extensions import TypedDict # Python 3.11+
Arch = Literal... | 13,339 | 32.602015 | 130 | py |
pytorch | pytorch-main/.github/scripts/filter_test_configs.py | #!/usr/bin/env python3
import json
import os
import re
import subprocess
import sys
import warnings
from enum import Enum
from functools import lru_cache
from typing import Any, Callable, Dict, List, Optional, Set
from urllib.request import Request, urlopen
import yaml
REENABLE_TEST_REGEX = "(?i)(Close(d|s)?|Resolve... | 20,607 | 33.752108 | 122 | py |
pytorch | pytorch-main/.github/scripts/build_triton_wheel.py | #!/usr/bin/env python3
import os
import shutil
import sys
from pathlib import Path
from subprocess import check_call
from tempfile import TemporaryDirectory
from typing import Optional
SCRIPT_DIR = Path(__file__).parent
REPO_DIR = SCRIPT_DIR.parent.parent
def read_triton_pin(rocm_hash: bool = False) -> str:
trit... | 6,043 | 32.955056 | 104 | py |
pytorch | pytorch-main/.github/scripts/label_utils.py | """GitHub Label Utilities."""
import json
from functools import lru_cache
from typing import Any, List, Tuple, TYPE_CHECKING, Union
from github_utils import gh_fetch_url_and_headers, GitHubComment
# TODO: this is a temp workaround to avoid circular dependencies,
# and should be removed once GitHubPR is refact... | 3,815 | 32.182609 | 126 | py |
pytorch | pytorch-main/.github/scripts/test_filter_test_configs.py | #!/usr/bin/env python3
import json
import os
import tempfile
from typing import Any, Dict, List
from unittest import main, mock, TestCase
import yaml
from filter_test_configs import (
filter,
get_labels,
mark_unstable_jobs,
parse_reenabled_issues,
perform_misc_tasks,
PREFIX,
remove_disable... | 30,466 | 42.154391 | 128 | py |
pytorch | pytorch-main/.github/scripts/generate_pytorch_version.py | #!/usr/bin/env python3
import argparse
import os
import re
import subprocess
from datetime import datetime
from distutils.util import strtobool
from pathlib import Path
LEADING_V_PATTERN = re.compile("^v")
TRAILING_RC_PATTERN = re.compile("-rc[0-9]*$")
LEGACY_BASE_VERSION_SUFFIX_PATTERN = re.compile("a0$")
class N... | 3,607 | 28.096774 | 87 | py |
pytorch | pytorch-main/.github/scripts/test_trymerge.py | #!/usr/bin/env python3
# Tests implemented in this file are relying on GitHub GraphQL APIs
# In order to avoid test flakiness, results of the queries
# are cached in gql_mocks.json
# PyTorch Lint workflow does not have GITHUB_TOKEN defined to avoid
# flakiness, so if you are making changes to merge_rules or
# GraphQL q... | 30,883 | 37.081381 | 117 | py |
pytorch | pytorch-main/.github/scripts/export_pytorch_labels.py | #!/usr/bin/env python3
"""
Test ownership was introduced in https://github.com/pytorch/pytorch/issues/66232.
As a part of enforcing test ownership, we want to maintain a list of existing PyTorch labels
to verify the owners' existence. This script outputs a file containing a list of existing
pytorch/pytorch labels so t... | 1,114 | 26.195122 | 92 | py |
pytorch | pytorch-main/third_party/build_bundled.py | #!/usr/bin/env python3
import argparse
import os
mydir = os.path.dirname(__file__)
licenses = {'LICENSE', 'LICENSE.txt', 'LICENSE.rst', 'COPYING.BSD'}
def collect_license(current):
collected = {}
for root, dirs, files in os.walk(current):
license = list(licenses & set(files))
if license:
... | 7,637 | 38.169231 | 83 | py |
pytorch | pytorch-main/third_party/nvfuser/examples/sinh_extension/test.py | import torch
import nvfuser_extension # noqa: F401
t = torch.randn((5, 5), device='cuda')
expected = torch.sinh(t)
output = torch.ops.myop.sinh_nvfuser(t)
print("Expected:", expected)
print("Output:", output)
assert torch.allclose(output, expected)
print("They match!")
| 274 | 20.153846 | 39 | py |
pytorch | pytorch-main/third_party/nvfuser/examples/sinh_extension/setup.py | from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(
name='nvfuser_extension',
ext_modules=[
CUDAExtension(
name='nvfuser_extension',
pkg='nvfuser_extension',
sources=['main.cpp'])
],
cmdclass={
'buil... | 350 | 22.4 | 67 | py |
pytorch | pytorch-main/third_party/nvfuser/python_tests/test_python_frontend.py | # Owner(s): ["module: nvfuser"]
import unittest
from typing import List
import torch
from torch.testing._internal.common_utils import run_tests, TEST_WITH_ROCM, TestCase
from torch.testing._internal.jit_utils import RUN_CUDA
import torch._refs as refs
import torch._prims as prims
# Will only create the nvfuser modul... | 14,440 | 38.135501 | 119 | py |
pytorch | pytorch-main/third_party/nvfuser/python_tests/test_torchscript.py | # Owner(s): ["oncall: jit"]
import contextlib
import unittest
import os
import random
import enum
import copy
from functools import reduce
import operator
import warnings
import torch
from torch.nn import functional
from torch.profiler import profile, ProfilerActivity
from torch.testing._internal.codegen.random_topo... | 220,669 | 40.580931 | 124 | py |
pytorch | pytorch-main/third_party/nvfuser/python_tests/test_dynamo.py | # Owner(s): ["module: nvfuser"]
import unittest
import warnings
from functools import partial
import torch
import torch._dynamo as torchdynamo
from torch.testing import make_tensor
from torch.testing._internal.common_utils import (
IS_WINDOWS,
run_tests,
skipIfTorchDynamo,
TEST_WITH_ROCM,
TestCase... | 5,272 | 34.389262 | 106 | py |
pytorch | pytorch-main/torch/_utils_internal.py | import logging
import os
import tempfile
from typing import Any, Dict
import torch
log = logging.getLogger(__name__)
# this arbitrary-looking assortment of functionality is provided here
# to have a central place for overrideable behavior. The motivating
# use is the FB build environment, where this source file is ... | 2,621 | 33.96 | 115 | py |
pytorch | pytorch-main/torch/_namedtensor_internals.py | from collections import OrderedDict
"""
This file contains helper functions that implement experimental functionality
for named tensors in python. All of these are experimental, unstable, and
subject to change or deletion.
"""
def check_serializing_named_tensor(tensor):
if tensor.has_names():
raise Runti... | 5,514 | 32.023952 | 90 | py |
pytorch | pytorch-main/torch/_lobpcg.py | """Locally Optimal Block Preconditioned Conjugate Gradient methods.
"""
# Author: Pearu Peterson
# Created: February 2020
from typing import Dict, Optional, Tuple
import torch
from torch import Tensor
from . import _linalg_utils as _utils
from .overrides import handle_torch_function, has_torch_function
__all__ = ["... | 43,939 | 36.523484 | 102 | py |
pytorch | pytorch-main/torch/_lowrank.py | """Implement various linear algebra algorithms for low rank matrices.
"""
__all__ = ["svd_lowrank", "pca_lowrank"]
from typing import Optional, Tuple
import torch
from torch import Tensor
from . import _linalg_utils as _utils
from .overrides import handle_torch_function, has_torch_function
def get_approximate_basi... | 10,929 | 35.433333 | 88 | py |
pytorch | pytorch-main/torch/quasirandom.py | import torch
from typing import Optional
class SobolEngine:
r"""
The :class:`torch.quasirandom.SobolEngine` is an engine for generating
(scrambled) Sobol sequences. Sobol sequences are an example of low
discrepancy quasi-random sequences.
This implementation of an engine for Sobol sequences is ca... | 7,536 | 40.640884 | 107 | py |
pytorch | pytorch-main/torch/storage.py | import io
import torch
from ._utils import _type, _cuda, _hpu
from torch.types import Storage
from typing import cast, Any, Dict as _Dict, Optional as _Optional, TypeVar, Type, Union
import copy
import collections
from functools import lru_cache
import warnings
import threading
import functools
try:
import numpy a... | 43,282 | 36.40968 | 145 | py |
pytorch | pytorch-main/torch/_meta_registrations.py | import math
from typing import List, Optional, Sequence, Tuple, Union
import torch
import torch._prims_common as utils
from torch import Tensor
from torch._decomp import (
_add_op_to_registry,
_convert_out_params,
global_decomposition_table,
meta_table,
)
from torch._decomp.decompositions import Reduct... | 159,043 | 29.427396 | 162 | py |
pytorch | pytorch-main/torch/_tensor.py | import copyreg
import enum
import functools
import warnings
from collections import OrderedDict
from copy import deepcopy
from numbers import Number
from typing import Any, Dict, Optional, Tuple, Union
import torch
import torch._C as _C
import torch.utils.hooks as hooks
from torch._namedtensor_internals import (
c... | 55,628 | 38.650036 | 127 | py |
pytorch | pytorch-main/torch/_VF.py | """
This makes the functions in torch._C._VariableFunctions available as
torch._VF.<funcname>
without mypy being able to find them.
A subset of those functions are mapped to ATen functions in
torch/jit/_builtins.py
See https://github.com/pytorch/pytorch/issues/21478 for the reason for
introducing torch._VF
"""
i... | 643 | 19.774194 | 70 | py |
pytorch | pytorch-main/torch/_utils.py | import copyreg
import sys
import traceback
import warnings
from collections import defaultdict
from typing import Any, DefaultDict, List, Optional
import torch
def _type(self, dtype=None, non_blocking=False, **kwargs):
"""Returns the type if `dtype` is not provided, else casts this object to
the specified ty... | 31,552 | 35.775058 | 112 | py |
pytorch | pytorch-main/torch/_torch_docs.py | # -*- coding: utf-8 -*-
"""Adds docstrings to functions defined in the torch._C"""
import re
import torch._C
from torch._C import _add_docstr as add_docstr
def parse_kwargs(desc):
"""Maps a description of args to a dictionary of {argname: description}.
Input:
(' weight (Tensor): a weight tensor\n... | 410,863 | 28.191048 | 132 | py |
pytorch | pytorch-main/torch/torch_version.py | from typing import Any, Iterable
from .version import __version__ as internal_version
__all__ = ['TorchVersion', 'Version', 'InvalidVersion']
class _LazyImport:
"""Wraps around classes lazy imported from packaging.version
Output of the function v in following snippets are identical:
from packaging.vers... | 3,588 | 38.877778 | 96 | py |
pytorch | pytorch-main/torch/_compile.py | """
APIs related to torch.compile which lazily import torch._dynamo to avoid
circular dependencies.
"""
import functools
def _disable_dynamo(fn=None, recursive=True):
"""
This API should be only used inside torch, external users should still use
torch._dynamo.disable. The main goal of this API is to avoid... | 1,001 | 31.322581 | 80 | py |
pytorch | pytorch-main/torch/functional.py | from typing import (
List, Tuple, Optional, Union, Any, Sequence, TYPE_CHECKING
)
import torch
from torch._C import _add_docstr
import torch.nn.functional as F
from ._lowrank import svd_lowrank, pca_lowrank
from .overrides import (
has_torch_function, has_torch_function_unary, has_torch_function_variadic,
... | 78,478 | 42.358564 | 125 | py |
pytorch | pytorch-main/torch/_vmap_internals.py | import functools
import warnings
from typing import Any, Callable, List, Optional, Tuple, Union
import torch
from torch import Tensor
from torch.utils._pytree import _broadcast_to_and_flatten, tree_flatten, tree_unflatten
in_dims_t = Union[int, Tuple]
out_dims_t = Union[int, Tuple[int, ...]]
# Checks that all args-... | 9,389 | 38.453782 | 118 | py |
pytorch | pytorch-main/torch/hub.py | import contextlib
import errno
import hashlib
import json
import os
import re
import shutil
import sys
import tempfile
import torch
import warnings
import zipfile
from pathlib import Path
from typing import Dict, Optional, Any
from urllib.error import HTTPError, URLError
from urllib.request import urlopen, Request
from... | 32,313 | 41.406824 | 130 | py |
pytorch | pytorch-main/torch/_ops.py | import contextlib
import ctypes
import inspect
import sys
import types
from typing import Any, Callable, Dict, List, Type, Union
import torch._C
from torch import _utils_internal
from torch._functorch.pyfunctorch import dispatch_functorch
# Query `hasattr` only once.
_SET_GLOBAL_FLAGS = hasattr(sys, "getdlopenflags... | 34,252 | 39.250294 | 127 | py |
pytorch | pytorch-main/torch/types.py | import torch
from typing import Any, List, Sequence, Tuple, Union
import builtins
# Convenience aliases for common composite types that we need
# to talk about in PyTorch
_TensorOrTensors = Union[torch.Tensor, Sequence[torch.Tensor]]
# In some cases, these basic types are shadowed by corresponding
# top-level value... | 2,312 | 27.9125 | 119 | py |
pytorch | pytorch-main/torch/_linalg_utils.py | """Various linear algebra utility methods for internal use.
"""
from typing import Optional, Tuple
import torch
from torch import Tensor
def is_sparse(A):
"""Check if tensor A is a sparse tensor"""
if isinstance(A, torch.Tensor):
return A.layout == torch.sparse_coo
error_str = "expected Tensor... | 3,584 | 26.576923 | 131 | py |
pytorch | pytorch-main/torch/_guards.py | import contextlib
import dataclasses
import enum
import functools
import logging
import traceback
import unittest.mock
import weakref
from abc import ABC, abstractmethod
from contextlib import contextmanager
from typing import (
Any,
Callable,
Dict,
Generic,
List,
NamedTuple,
Optional,
... | 20,718 | 30.344932 | 113 | py |
pytorch | pytorch-main/torch/random.py | import contextlib
from typing import Generator
import warnings
from torch._C import default_generator
import torch
def set_rng_state(new_state: torch.Tensor) -> None:
r"""Sets the random number generator state.
.. note: This function only works for CPU. For CUDA, please use
torch.manual_seed(se... | 6,706 | 38.452941 | 117 | py |
pytorch | pytorch-main/torch/_storage_docs.py | """Adds docstrings to Storage functions"""
import torch._C
from torch._C import _add_docstr as add_docstr
storage_classes = [
"StorageBase",
]
def add_docstr_all(method, docstr):
for cls_name in storage_classes:
cls = getattr(torch._C, cls_name)
try:
add_docstr(getattr(cls, meth... | 1,036 | 24.292683 | 80 | py |
pytorch | pytorch-main/torch/_python_dispatcher.py | import re
import torch._C as C
"""
PythonDispatcher class is a thin python-binding to C++ dispatcher and it
is designed to show how dispatcher precompute works. In particular,
it shows for a certain op `foo`, what the computed dispatch table looks
like after user register their kernels to certains dispatch keys.
In... | 7,130 | 38.181319 | 111 | py |
pytorch | pytorch-main/torch/library.py | from ._ops import OpOverload
from typing import Set
import traceback
import torch
import weakref
__all__ = ['Library', 'impl', 'define']
# Set containing the combination of (namespace, operator, DispatchKey) for which a new kernel has been registered
# The keys in the set are of the form `namespace + "/" + op_name + ... | 7,338 | 44.86875 | 120 | py |
pytorch | pytorch-main/torch/_weights_only_unpickler.py | # Unpickler restricted to loading only state dicts
# Restrict constructing types to a list defined in _get_allowed_globals()
# Restrict BUILD operation to `Tensor`, `Parameter` and `OrderedDict` types only
# Restrict APPEND/APPENDS to `list`
# In `GLOBALS` operation do not do class lookup by name, but rather rely on di... | 10,716 | 35.328814 | 99 | py |
pytorch | pytorch-main/torch/_tensor_docs.py | """Adds docstrings to Tensor functions"""
import torch._C
from torch._C import _add_docstr as add_docstr
from ._torch_docs import parse_kwargs, reproducibility_notes
def add_docstr_all(method, docstr):
add_docstr(getattr(torch._C._TensorBase, method), docstr)
common_args = parse_kwargs(
"""
memory_form... | 136,700 | 18.95635 | 118 | py |
pytorch | pytorch-main/torch/_classes.py | import types
import torch._C
class _ClassNamespace(types.ModuleType):
def __init__(self, name):
super().__init__("torch.classes" + name)
self.name = name
def __getattr__(self, attr):
proxy = torch._C._get_custom_class_python_wrapper(self.name, attr)
if proxy is None:
... | 1,686 | 29.125 | 81 | py |
pytorch | pytorch-main/torch/_sources.py | import ast
import functools
import inspect
from textwrap import dedent
from typing import Any, List, NamedTuple, Optional, Tuple
from torch._C import ErrorReport
from torch._C._jit_tree_views import SourceRangeFactory
def get_source_lines_and_file(
obj: Any,
error_msg: Optional[str] = None,
) -> Tuple[List[s... | 4,427 | 31.086957 | 96 | py |
pytorch | pytorch-main/torch/__init__.py |
r"""
The torch package contains data structures for multi-dimensional
tensors and defines mathematical operations over these tensors.
Additionally, it provides many utilities for efficient serialization of
Tensors and arbitrary types, and other useful utilities.
It has a CUDA counterpart, that enables you to run your... | 68,895 | 37.597199 | 141 | py |
pytorch | pytorch-main/torch/__config__.py | import torch
def show():
"""
Return a human-readable string with descriptions of the
configuration of PyTorch.
"""
return torch._C._show_config()
# TODO: In principle, we could provide more structured version/config
# information here. For now only CXX_FLAGS is exposed, as Timer
# uses them.
def... | 553 | 23.086957 | 69 | py |
pytorch | pytorch-main/torch/_deploy.py | import io
import torch
from torch.package import Importer, OrderedImporter, PackageImporter, sys_importer
from torch.package._package_pickler import create_pickler
from torch.package._package_unpickler import PackageUnpickler
from torch.serialization import _maybe_decode_ascii
def _save_storages(importer, obj):
... | 3,504 | 32.066038 | 88 | py |
pytorch | pytorch-main/torch/overrides.py | """
Python implementation of ``__torch_function__``
While most of the torch API and handling for ``__torch_function__`` happens
at the C++ level, some of the torch API is written in Python so we need
python-level handling for ``__torch_function__`` overrides as well. The main
developer-facing functionality in this fil... | 101,273 | 51.939885 | 173 | py |
pytorch | pytorch-main/torch/_tensor_str.py | import contextlib
import dataclasses
import math
import textwrap
from typing import Any, Dict, Optional
import torch
from torch import inf
@dataclasses.dataclass
class __PrinterOptions:
precision: int = 4
threshold: float = 1000
edgeitems: int = 3
linewidth: int = 80
sci_mode: Optional[bool] = No... | 25,840 | 37.568657 | 113 | py |
pytorch | pytorch-main/torch/_jit_internal.py | """
The weak_script annotation needs to be here instead of inside torch/jit/ so it
can be used in other places in torch/ (namely torch.nn) without running into
circular dependency problems
"""
import ast
import builtins
import collections
import contextlib
import enum
import inspect
import io
import pickle
import sys
... | 52,394 | 34.070281 | 125 | py |
pytorch | pytorch-main/torch/serialization.py | import difflib
import os
import io
import shutil
import struct
import sys
import torch
import tarfile
import tempfile
import warnings
from contextlib import closing, contextmanager
from enum import Enum
from ._utils import _import_dotted_name
from torch._sources import get_source_lines_and_file
from torch.types import ... | 61,121 | 41.593728 | 123 | py |
pytorch | pytorch-main/torch/return_types.py | import torch
import inspect
__all__ = ["pytree_register_structseq"]
# error: Module has no attribute "_return_types"
return_types = torch._C._return_types # type: ignore[attr-defined]
def pytree_register_structseq(cls):
def structseq_flatten(structseq):
return list(structseq), None
def structseq_un... | 1,085 | 30.028571 | 90 | py |
pytorch | pytorch-main/torch/_logging/_internal.py | import functools
import itertools
import logging
import os
import re
from dataclasses import dataclass, field
from importlib import __import__
from typing import Dict, Optional, Set, Union
from weakref import WeakSet
log = logging.getLogger(__name__)
DEFAULT_LOG_LEVEL = logging.WARN
LOG_ENV_VAR = "TORCH_LOGS"
@data... | 22,117 | 33.027692 | 118 | py |
pytorch | pytorch-main/torch/_logging/__init__.py | # Top level logging module for torch logging
# Design doc: https://docs.google.com/document/d/1ZRfTWKa8eaPq1AxaiHrq4ASTPouzzlPiuquSBEJYwS8/edit#
# Simple setup for onboarding (see above doc for more detail):
# 1. register any top-level log qualified name for your module in torch._logging._registrations (see there for e... | 658 | 72.222222 | 129 | py |
pytorch | pytorch-main/torch/_logging/_registrations.py | from ._internal import register_artifact, register_log
register_log("dynamo", "torch._dynamo")
register_log("aot", "torch._functorch.aot_autograd")
register_log("inductor", "torch._inductor")
register_log("dynamic", "torch.fx.experimental.symbolic_shapes")
register_log("torch", "torch")
register_log("distributed", "to... | 986 | 35.555556 | 64 | py |
pytorch | pytorch-main/torch/nn/functional.py | """Functional interface"""
from typing import Callable, List, Optional, Tuple, Union
import math
import warnings
import importlib
import torch
from torch import _VF
from torch import sym_int as _sym_int
from torch._C import _infer_size, _add_docstr
from torch._torch_docs import reproducibility_notes, tf32_notes, spars... | 223,847 | 39.990295 | 271 | py |
pytorch | pytorch-main/torch/nn/init.py | import math
import warnings
from torch import Tensor
import torch
from typing import Optional as _Optional
# These no_grad_* functions are necessary as wrappers around the parts of these
# functions that use `with torch.no_grad()`. The JIT doesn't support context
# managers, so these need to be implemented as builtin... | 20,431 | 34.845614 | 127 | py |
pytorch | pytorch-main/torch/nn/parameter.py | import torch
from torch._C import _disabled_torch_function_impl
from collections import OrderedDict
# Metaclass to combine _TensorMeta and the instance check override for Parameter.
class _ParameterMeta(torch._C._TensorMeta):
# Make `isinstance(t, Parameter)` return True for custom tensor instances that have the _... | 12,628 | 42.25 | 122 | py |
pytorch | pytorch-main/torch/nn/__init__.py | from .modules import * # noqa: F403
from .parameter import (
Buffer as Buffer,
Parameter as Parameter,
UninitializedParameter as UninitializedParameter,
UninitializedBuffer as UninitializedBuffer,
)
from .parallel import DataParallel as DataParallel
from . import init
from . import functional
from . im... | 2,125 | 39.113208 | 92 | py |
pytorch | pytorch-main/torch/nn/_reduction.py | from typing import Optional
import warnings
# NB: Keep this file in sync with enums in aten/src/ATen/core/Reduction.h
def get_enum(reduction: str) -> int:
if reduction == 'none':
ret = 0
elif reduction == 'mean':
ret = 1
elif reduction == 'elementwise_mean':
warnings.warn("reducti... | 1,564 | 31.604167 | 110 | py |
pytorch | pytorch-main/torch/nn/grad.py | """Gradient interface"""
import torch
from .modules.utils import _single, _pair, _triple
def conv1d_input(input_size, weight, grad_output, stride=1, padding=0, dilation=1, groups=1):
r"""
Computes the gradient of conv1d with respect to the input of the convolution.
This is same as the 1D transposed convo... | 9,715 | 49.341969 | 112 | py |
pytorch | pytorch-main/torch/nn/cpp.py | """Functionality for Python <-> C++ frontend inter-op."""
from torch import nn
class OrderedDictWrapper:
"""
A wrapper around a C++ OrderedDict that dynamically evaluates the
OrderedDict getter on a bound C++ module, such that new changes on the C++
side are picked up. Otherwise accessing e.g. ``cpp_... | 3,009 | 31.717391 | 114 | py |
pytorch | pytorch-main/torch/nn/quantized/functional.py | r"""nn.quantized.functional
Quantized equivalents of the `nn.functional`.
Note::
This location is in the process of being deprecated.
Please, use the `torch.ao.nn.quantized.functional` instead.
"""
from torch.ao.nn.quantized.functional import * # noqa: F401,F403
| 275 | 24.090909 | 65 | py |
pytorch | pytorch-main/torch/nn/quantized/modules/embedding_ops.py | # flake8: noqa: F401
r"""Quantized Modules
This file is in the process of migration to `torch/ao/nn/quantized`, and
is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized/modules`,
while... | 638 | 38.9375 | 77 | py |
pytorch | pytorch-main/torch/nn/quantized/modules/activation.py | # flake8: noqa: F401
r"""Quantized Modules
This file is in the process of migration to `torch/ao/nn/quantized`, and
is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized/modules`,
while... | 854 | 44 | 72 | py |
pytorch | pytorch-main/torch/nn/quantized/modules/batchnorm.py | # flake8: noqa: F401
r"""Quantized Modules
This file is in the process of migration to `torch/ao/nn/quantized`, and
is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized/modules`,
while... | 487 | 36.538462 | 72 | py |
pytorch | pytorch-main/torch/nn/quantized/modules/utils.py | # flake8: noqa: F401
r"""Quantized Modules
This file is in the process of migration to `torch/ao/nn/quantized`, and
is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized/modules`,
while... | 701 | 42.875 | 72 | py |
pytorch | pytorch-main/torch/nn/quantized/modules/functional_modules.py | # flake8: noqa: F401
r"""Quantized Modules
This file is in the process of migration to `torch/ao/nn/quantized`, and
is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized/modules`,
while... | 655 | 40 | 78 | py |
pytorch | pytorch-main/torch/nn/quantized/modules/linear.py | # flake8: noqa: F401
r"""Quantized Modules
This file is in the process of migration to `torch/ao/nn/quantized`, and
is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized/modules`,
while... | 527 | 34.2 | 72 | py |
pytorch | pytorch-main/torch/nn/quantized/modules/dropout.py | # flake8: noqa: F401
r"""Quantized Modules
This file is in the process of migration to `torch/ao/nn/quantized`, and
is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized/modules`,
while... | 440 | 30.5 | 72 | py |
pytorch | pytorch-main/torch/nn/quantized/modules/__init__.py | r"""Quantized Modules
Note::
The `torch.nn.quantized` namespace is in the process of being deprecated.
Please, use `torch.ao.nn.quantized` instead.
"""
from torch.ao.nn.quantized.modules.activation import ReLU6, Hardswish, ELU, LeakyReLU, Sigmoid, Softmax, MultiheadAttention, PReLU
from torch.ao.nn.quantized.... | 2,433 | 33.28169 | 130 | py |
pytorch | pytorch-main/torch/nn/quantized/modules/rnn.py | # flake8: noqa: F401
r"""Quantized Modules
This file is in the process of migration to `torch/ao/nn/quantized`, and
is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized/modules`,
while... | 410 | 33.25 | 72 | py |
pytorch | pytorch-main/torch/nn/quantized/modules/conv.py | # flake8: noqa: F401
r"""Quantized Modules
This file is in the process of migration to `torch/ao/nn/quantized`, and
is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized/modules`,
while... | 882 | 39.136364 | 97 | py |
pytorch | pytorch-main/torch/nn/quantized/modules/normalization.py | # flake8: noqa: F401
r"""Quantized Modules
This file is in the process of migration to `torch/ao/nn/quantized`, and
is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized/modules`,
while... | 796 | 43.277778 | 90 | py |
pytorch | pytorch-main/torch/nn/quantized/dynamic/__init__.py | from torch.ao.nn.quantized.dynamic import * # noqa: F403
| 58 | 28.5 | 57 | py |
pytorch | pytorch-main/torch/nn/quantized/dynamic/modules/linear.py | # flake8: noqa: F401
r"""Quantized Dynamic Modules
This file is in the process of migration to `torch/ao/nn/quantized/dynamic`,
and is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized... | 446 | 39.636364 | 76 | py |
pytorch | pytorch-main/torch/nn/quantized/dynamic/modules/__init__.py | # flake8: noqa: F401
r"""Quantized Dynamic Modules
This file is in the process of migration to `torch/ao/nn/quantized/dynamic`,
and is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized... | 1,036 | 30.424242 | 128 | py |
pytorch | pytorch-main/torch/nn/quantized/dynamic/modules/rnn.py | # flake8: noqa: F401
r"""Quantized Dynamic Modules
This file is in the process of migration to `torch/ao/nn/quantized/dynamic`,
and is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized... | 1,093 | 46.565217 | 113 | py |
pytorch | pytorch-main/torch/nn/quantized/dynamic/modules/conv.py | # flake8: noqa: F401
r"""Quantized Dynamic Modules
This file is in the process of migration to `torch/ao/nn/quantized/dynamic`,
and is kept here for compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/quantized... | 881 | 45.421053 | 97 | py |
pytorch | pytorch-main/torch/nn/quantized/_reference/modules/sparse.py | # flake8: noqa: F401
r"""Quantized Reference Modules
This module is in the process of migration to
`torch/ao/nn/quantized/reference`, and is kept here for
compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/qua... | 524 | 36.5 | 71 | py |
pytorch | pytorch-main/torch/nn/quantized/_reference/modules/utils.py | # flake8: noqa: F401
r"""Quantized Reference Modules
This module is in the process of migration to
`torch/ao/nn/quantized/reference`, and is kept here for
compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/qua... | 791 | 48.5 | 89 | py |
pytorch | pytorch-main/torch/nn/quantized/_reference/modules/linear.py | # flake8: noqa: F401
r"""Quantized Reference Modules
This module is in the process of migration to
`torch/ao/nn/quantized/reference`, and is kept here for
compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/qua... | 449 | 33.615385 | 66 | py |
pytorch | pytorch-main/torch/nn/quantized/_reference/modules/__init__.py | # flake8: noqa: F401
r"""Quantized Reference Modules
This module is in the process of migration to
`torch/ao/nn/quantized/reference`, and is kept here for
compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/qua... | 987 | 29.875 | 130 | py |
pytorch | pytorch-main/torch/nn/quantized/_reference/modules/rnn.py | # flake8: noqa: F401
r"""Quantized Reference Modules
This module is in the process of migration to
`torch/ao/nn/quantized/reference`, and is kept here for
compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/qua... | 769 | 41.777778 | 67 | py |
pytorch | pytorch-main/torch/nn/quantized/_reference/modules/conv.py | # flake8: noqa: F401
r"""Quantized Reference Modules
This module is in the process of migration to
`torch/ao/nn/quantized/reference`, and is kept here for
compatibility while the migration process is ongoing.
If you are adding a new entry/functionality, please, add it to the
appropriate file under the `torch/ao/nn/qua... | 933 | 45.7 | 73 | py |
pytorch | pytorch-main/torch/nn/modules/pooling.py | from typing import List, Optional
from torch import Tensor
from .module import Module
from .utils import _single, _pair, _triple
from .. import functional as F
from ..common_types import (_size_any_t, _size_1_t, _size_2_t, _size_3_t,
_ratio_3_t, _ratio_2_t, _size_any_opt_t, _size_2_opt_t, ... | 54,138 | 42.660484 | 125 | py |
pytorch | pytorch-main/torch/nn/modules/container.py | import warnings
from collections import OrderedDict, abc as container_abcs
from itertools import chain, islice
import operator
import torch
from .module import Module
from ..parameter import Parameter
from torch._jit_internal import _copy_to_script_wrapper
from typing import Any, Dict, Iterable, Iterator, Mapping, Op... | 34,662 | 36.473514 | 110 | py |
pytorch | pytorch-main/torch/nn/modules/activation.py | import warnings
from typing import Optional, Tuple
import torch
from torch import Tensor
from .linear import NonDynamicallyQuantizableLinear
from torch.nn.init import constant_, xavier_normal_, xavier_uniform_
from torch.nn.parameter import Parameter
from .module import Module
from .. import functional as F
__all__ =... | 55,041 | 33.880862 | 132 | py |
pytorch | pytorch-main/torch/nn/modules/batchnorm.py | from typing import Optional, Any
import torch
from torch import Tensor
from torch.nn.parameter import Parameter, UninitializedParameter, UninitializedBuffer
from .. import functional as F
from .. import init
from ._functions import SyncBatchNorm as sync_batch_norm
from .lazy import LazyModuleMixin
from .module import... | 37,157 | 43.714801 | 115 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.