python_code stringlengths 0 1.02M | repo_name stringlengths 9 48 | file_path stringlengths 5 114 |
|---|---|---|
# Module for defining "primitive" operations executable by the nvFuser. This
# list exists to decouple main set of primitives from the ones that provide a
# lowering of the op to nvFuser’s Python interface. Mostly torch.ops.nvprims is
# a subset of the primitives in torch.ops.prims, but some additional primitives
# can... | pytorch-master | torch/_prims/nvfuser_prims.py |
from typing import Callable
from torch._prims.context import NvfuserPrimsMode, TorchRefsMode
from torch._prims.nvfuser_executor import nvfuser_execute, nvfuser_execute_partitioned
from torch.fx import GraphModule
from torch.fx.experimental.proxy_tensor import make_fx, wrapper_and_args_for_make_fx
def execute(gm: Gr... | pytorch-master | torch/_prims/executor.py |
# this is imported by test_deploy to do some checks in python
import sys
import subprocess
from pathlib import Path
# we've taken steps to clear out the embedded python environment,
# so we have to go searching for real python to figure out where its libraries are installed.
def python_path(cpath):
for maybe in cp... | pytorch-master | torch/csrc/deploy/test_deploy_python.py |
from libfb.py import testutil
import test_deploy_python_ext
class TestDeployFromPython(testutil.BaseFacebookTestCase):
def test_deploy_from_python(self):
self.assertTrue(test_deploy_python_ext.run())
| pytorch-master | torch/csrc/deploy/test_deploy_from_python.py |
import numpy as np
import scipy
from scipy import linalg
print("Hello, torch::deploy unity!")
print(f"np.random.rand(5): {np.random.rand(5)}")
print(f"scipy {scipy}")
mat_a = np.array([[1, 0, 0, 0], [1, 1, 0, 0], [1, 2, 1, 0], [1, 3, 3, 1]])
mat_b = linalg.inv(mat_a)
print(mat_b)
| pytorch-master | torch/csrc/deploy/unity/example.py |
import torch
from torch import nn
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = nn.Linear(256, 64)
self.fc2 = nn.Linear(64, 10)
def forward(self, X):
X = self.fc(X)
X = torch.relu(X)
X = self.fc2(X)
X = t... | pytorch-master | torch/csrc/deploy/unity/tests/simple_model.py |
def func(*vlist):
return sum(vlist)
import sys
print("byebye!", file=sys.stderr)
| pytorch-master | torch/csrc/deploy/unity/tests/sum.py |
# used by the benchmarking program to wrap cpu models for GPU use
import torch
from copy import deepcopy
def to_device(i, d):
if isinstance(i, torch.Tensor):
return i.to(device=d)
elif isinstance(i, (tuple, list)):
return tuple(to_device(e, d) for e in i)
else:
raise RuntimeError('i... | pytorch-master | torch/csrc/deploy/example/gpu_wrapper.py |
from typing import List, Any
import pickle
import torch
class TestTRTModule(torch.nn.Module):
def __init__(self, engine, input_names=None, output_names=None, fp16_output=False):
super(TestTRTModule, self).__init__()
self.engine = engine
self.input_names = input_names
self.output_na... | pytorch-master | torch/csrc/deploy/example/tensorrt_example.py |
from typing import Tuple, List, Dict
import torch
import torch.nn as nn
from torch import Tensor
class Simple(torch.nn.Module):
def __init__(self, N, M):
super().__init__()
self.weight = torch.nn.Parameter(torch.rand(N, M))
def forward(self, input):
output = self.weight + input
... | pytorch-master | torch/csrc/deploy/example/examples.py |
"""
Generate the example files that torchpy_test uses.
"""
import argparse
from pathlib import Path
import torch
from torch.package import PackageExporter
from torch.fx import symbolic_trace
try:
from .examples import Simple, resnet18, MultiReturn, multi_return_metadata, load_library, BatchedModel
except ImportEr... | pytorch-master | torch/csrc/deploy/example/generate_examples.py |
import torch.fx
try:
from .some_dependency import a_non_torch_leaf
except ImportError:
from some_dependency import a_non_torch_leaf
torch.fx.wrap('a_non_torch_leaf')
class SimpleWithLeaf(torch.nn.Module):
def __init__(self, N, M):
super().__init__()
self.weight = torch.nn.Parameter(torch.r... | pytorch-master | torch/csrc/deploy/example/fx/examples.py |
# dependency for torch package
def a_non_torch_leaf(a: int, b):
return a * b
| pytorch-master | torch/csrc/deploy/example/fx/some_dependency.py |
#!/usr/bin/env python3
import argparse
from torchgen.gen import parse_native_yaml, FileManager
import torchgen.model as model
def num_leading_spaces(line: str) -> int:
return len(line) - len(line.lstrip())
def deindent(code: str) -> str:
lines = code.split('\n')
min_leading_spaces = min(map(num_leading_spa... | pytorch-master | torch/csrc/jit/tensorexpr/codegen_external.py |
import subprocess
import click
def test(cmd, limit):
print(f"Testing PYTORCH_JIT_OPT_LIMIT=tensorexpr_fuser={limit} {cmd}")
p = subprocess.run(
f"PYTORCH_JIT_OPT_LIMIT=tensorexpr_fuser={limit} {cmd}",
shell=True,
capture_output=True,
encoding="utf-8",
)
print(p.stdout)
... | pytorch-master | torch/csrc/jit/tensorexpr/scripts/bisect.py |
# Generates a C++ header files embedding the original input as a string literal
import argparse
import pathlib
from datetime import datetime
arg_parser = argparse.ArgumentParser(
description='Converts source files to C++ string literals', allow_abbrev=False)
arg_parser.add_argument('-i', '--input', required=Tru... | pytorch-master | torch/csrc/jit/codegen/cuda/tools/stringify_file.py |
import torch
from torch._C._nvfuser import Fusion, FusionDefinition, DataType
# Construct and Define Fusion
fusion = Fusion()
with FusionDefinition(fusion) as fd :
t0 = fd.define_tensor(2, DataType.Double)
t1 = fd.define_tensor(2, DataType.Double)
t0h = fd.ops.cast(t0, DataType.Half)
t1h = fd.ops.ca... | pytorch-master | torch/csrc/jit/codegen/cuda/python_frontend/examples/double_half_cast.py |
import torch
from torch._C._nvfuser import Fusion, FusionDefinition, DataType
# Construct and Define Fusion
fusion = Fusion()
with FusionDefinition(fusion) as fd :
t0 = fd.define_tensor(3, DataType.Half)
t1 = fd.define_tensor(1, DataType.Half)
s0 = fd.define_scalar()
c0 = fd.define_constant(3.0)
... | pytorch-master | torch/csrc/jit/codegen/cuda/python_frontend/examples/python_example_fp16.py |
import torch
from torch._C._nvfuser import Fusion, FusionDefinition, DataType
# Construct and Define Fusion
fusion = Fusion()
with FusionDefinition(fusion) as fd :
t0 = fd.define_tensor(3)
t1 = fd.define_tensor(3)
s0 = fd.define_scalar()
c0 = fd.define_constant(3.0)
t2 = fd.ops.add(t0, t1)
t... | pytorch-master | torch/csrc/jit/codegen/cuda/python_frontend/examples/python_example.py |
import torch
from torch._C._nvfuser import Fusion, FusionDefinition
import torch._prims as prims
import torch._refs as refs
# Construct and Define Fusion
fusion1 = Fusion()
with FusionDefinition(fusion1) as fd :
t0 = fd.define_tensor(1)
t1 = fd.define_tensor(3)
t0_b = fd.ops.broadcast_in_dim(t0, [2, 3, ... | pytorch-master | torch/csrc/jit/codegen/cuda/python_frontend/examples/python_example_broadcast_in_dim.py |
import torch
from torch._C._nvfuser import Fusion, FusionDefinition, DataType
# Construct and Define Fusion
fusion = Fusion()
with FusionDefinition(fusion) as fd :
t0 = fd.define_tensor(2, DataType.Half)
t1 = fd.define_tensor(2, DataType.Double)
t2 = fd.ops.add(t0, t1)
t5 = fd.ops.relu(t2)
fd.a... | pytorch-master | torch/csrc/jit/codegen/cuda/python_frontend/examples/half_double_cast.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!")
| pytorch-master | torch/csrc/jit/codegen/cuda/examples/sinh_extension/test.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... | pytorch-master | torch/csrc/jit/codegen/cuda/examples/sinh_extension/setup.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import os
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
import torch._lazy
import torch._lazy.ts_backend
import torch._lazy.metrics
torch._lazy.ts_backend.init()
class Net(nn.Modul... | pytorch-master | torch/csrc/lazy/test_mnist.py |
from torch._C._monitor import * # noqa: F403
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from torch.utils.tensorboard import SummaryWriter
STAT_EVENT = "torch.monitor.Stat"
class TensorboardEventHandler:
"""
TensorboardEventHandler is an event handler that will write known events to
the pro... | pytorch-master | torch/monitor/__init__.py |
import weakref
import torch
from torch.multiprocessing.reductions import StorageWeakRef
from torch.utils._mode_utils import no_dispatch
def safe_is_leaf(t):
try:
return t.is_leaf
except RuntimeError:
# inference mode can trigger this
return False
# torch.Tensors cannot be used as a ... | pytorch-master | torch/_subclasses/meta_utils.py |
import torch
from torch._subclasses.fake_tensor import (
DynamicOutputShapeException,
FakeTensor,
FakeTensorMode,
UnsupportedFakeTensorException,
)
__all__ = [
"FakeTensor",
"FakeTensorMode",
"UnsupportedFakeTensorException",
"DynamicOutputShapeException",
]
| pytorch-master | torch/_subclasses/__init__.py |
import contextlib
import functools
import itertools
import weakref
from dataclasses import dataclass
from functools import partial
from typing import Callable, Union
import torch
import torch.fx.experimental.symbolic_shapes as symbolic_shapes
from torch._ops import OpOverload
from torch._subclasses.meta_utils import M... | pytorch-master | torch/_subclasses/fake_tensor.py |
from __future__ import annotations
from typing import cast, Callable, Generic, List, Optional, Type, TypeVar, Union
import torch
__all__ = ['Future', 'collect_all', 'wait_all']
T = TypeVar("T")
S = TypeVar("S")
class _PyFutureMeta(type(torch._C.Future), type(Generic)): # type: ignore[misc, no-redef]
pass
cla... | pytorch-master | torch/futures/__init__.py |
# -*- coding: utf-8 -*-
import sys
import torch
from torch._C import _add_docstr, _linalg # type: ignore[attr-defined]
LinAlgError = torch._C._LinAlgError # type: ignore[attr-defined]
Tensor = torch.Tensor
common_notes = {
"experimental_warning": """This function is "experimental" and it may change in a futur... | pytorch-master | torch/linalg/__init__.py |
from typing import TypeVar, Union, Tuple, Optional
from .. import Tensor
# Create some useful type aliases
# Template for arguments which can be supplied as a tuple, or which can be a scalar which PyTorch will internally
# broadcast to a tuple.
# Comes in several variants: A tuple of unknown size, and a fixed-size tu... | pytorch-master | torch/nn/common_types.py |
from .modules import * # noqa: F403
from .parameter import (
Parameter as Parameter,
UninitializedParameter as UninitializedParameter,
UninitializedBuffer as UninitializedBuffer,
)
from .parallel import DataParallel as DataParallel
from . import init
from . import functional
from . import utils
def facto... | pytorch-master | torch/nn/__init__.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... | pytorch-master | torch/nn/_reduction.py |
"""Functionality for Python <-> C++ frontend inter-op."""
from torch import nn
class OrderedDictWrapper(object):
"""
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... | pytorch-master | torch/nn/cpp.py |
r"""Functional interface"""
from typing import Callable, List, Optional, Tuple, Union
import math
import warnings
import torch
from torch import _VF
from torch._C import _infer_size, _add_docstr
from torch._torch_docs import reproducibility_notes, tf32_notes
# A workaround to support both TorchScript and MyPy:
from ty... | pytorch-master | torch/nn/functional.py |
import math
import warnings
from torch import Tensor
import torch
# 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 builtins. Using these wrappers
# lets us keep t... | pytorch-master | torch/nn/init.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... | pytorch-master | torch/nn/grad.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 _... | pytorch-master | torch/nn/parameter.py |
from contextlib import contextmanager
_DDP_WITH_REPLICATED_TENSOR = False
@contextmanager
def _ddp_replicated_tensor(val):
"""
A context manager to tag tensors in the forward pass of DDP to be
``ReplicatedTensor``. This can be used by ReplicatedTensor inter-op
during the forward pass to perform approp... | pytorch-master | torch/nn/parallel/_replicated_tensor_ddp_utils.py |
import threading
import torch
from torch.cuda._utils import _get_device_index
from torch.cuda.amp import autocast
from torch._utils import ExceptionWrapper
def get_a_var(obj):
if isinstance(obj, torch.Tensor):
return obj
if isinstance(obj, list) or isinstance(obj, tuple):
for result in map(ge... | pytorch-master | torch/nn/parallel/parallel_apply.py |
import warnings
import torch
from torch.cuda import nccl
from torch._utils import _take_tensors, _flatten_dense_tensors, \
_unflatten_dense_tensors, _reorder_tensors_as, _get_device_index, _handle_complex
from typing import List
def broadcast(tensor, devices=None, *, out=None):
r"""Broadcasts a tensor to speci... | pytorch-master | torch/nn/parallel/comm.py |
import torch
from ._functions import Scatter, Gather
import warnings
__all__ = ['scatter', 'scatter_kwargs', 'gather']
def is_namedtuple(obj):
# Check if type was created from collections.namedtuple or a typing.NamedTuple.
warnings.warn("is_namedtuple is deprecated, please use the python checks instead")
... | pytorch-master | torch/nn/parallel/scatter_gather.py |
from . import comm
from torch._utils import _get_device_index
from collections import OrderedDict
def _is_script_module(module):
import torch.jit
return isinstance(module, torch.jit.ScriptModule)
def _is_script_method(module):
import torch.jit
return isinstance(module, torch._C.ScriptMethod)
def ... | pytorch-master | torch/nn/parallel/replicate.py |
import warnings
import torch
from . import comm
from torch.autograd import Function
from torch._utils import _get_device_index
from typing import List, Optional
class Broadcast(Function):
@staticmethod
def forward(ctx, target_gpus, *inputs):
assert all(i.device.type != 'cpu' for i in inputs), (
... | pytorch-master | torch/nn/parallel/_functions.py |
import operator
import torch
import warnings
from itertools import chain
from ..modules import Module
from .scatter_gather import scatter_kwargs, gather
from .replicate import replicate
from .parallel_apply import parallel_apply
from torch._utils import (
_get_all_device_indices,
_get_available_device_type,
... | pytorch-master | torch/nn/parallel/data_parallel.py |
from .parallel_apply import parallel_apply
from .replicate import replicate
from .data_parallel import DataParallel, data_parallel
from .scatter_gather import scatter, gather
from .distributed import DistributedDataParallel
__all__ = ['replicate', 'scatter', 'parallel_apply', 'gather', 'data_parallel',
'Dat... | pytorch-master | torch/nn/parallel/__init__.py |
import sys
import copy
from dataclasses import dataclass
from typing import Callable, Any, Type
from enum import Enum, auto
import inspect
import itertools
import logging
import os
import warnings
from contextlib import contextmanager
import torch
import torch.distributed as dist
from torch.autograd import Function, V... | pytorch-master | torch/nn/parallel/distributed.py |
import torch
from torch.distributed._shard.replicated_tensor import ReplicatedTensor
class ReplicatedTensorFunction(torch.autograd.Function):
"""
Autograd function to ensure gradients are replicated between the
replicated tensor and the original one.
"""
@staticmethod
def forward(ctx, inp, proc... | pytorch-master | torch/nn/parallel/_replicated_tensor_ddp_interop.py |
from .modules import * # noqa: F403
| pytorch-master | torch/nn/qat/__init__.py |
from .modules import * # noqa: F403
| pytorch-master | torch/nn/qat/dynamic/__init__.py |
import torch
from torch.ao.quantization import activation_is_memoryless
class Linear(torch.nn.qat.Linear):
r"""
A linear module attached with FakeQuantize modules for weight,
used for dynamic quantization aware training.
We adopt the same interface as `torch.nn.Linear`, please see
https://pytorch... | pytorch-master | torch/nn/qat/dynamic/modules/linear.py |
from .linear import Linear
__all__ = ["Linear"]
| pytorch-master | torch/nn/qat/dynamic/modules/__init__.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.intrinsic import LinearReLU
from torch.nn.utils.parametrize import (
is_parametrized,
type_before_parametrizations,
transfer_parametrizations_and_params,
)
class Linear(nn.Linear):
r"""
A linear module attached with Fa... | pytorch-master | torch/nn/qat/modules/linear.py |
from .linear import Linear
from .conv import Conv1d
from .conv import Conv2d
from .conv import Conv3d
from .embedding_ops import EmbeddingBag, Embedding
__all__ = [
"Linear",
"Conv1d",
"Conv2d",
"Conv3d",
"Embedding",
"EmbeddingBag",
]
| pytorch-master | torch/nn/qat/modules/__init__.py |
import torch
import torch.nn as nn
from torch.nn.modules.utils import _single, _pair, _triple
from torch.nn.intrinsic import _FusedModule
from typing import Tuple, TypeVar, Union
from torch.nn.common_types import _size_1_t, _size_2_t, _size_3_t
MOD = TypeVar('MOD', bound=nn.modules.conv._ConvNd)
class _ConvNd(nn.modu... | pytorch-master | torch/nn/qat/modules/conv.py |
import torch
from torch import Tensor
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['Embedding', 'EmbeddingBag']
class Embedding(nn.Embedding):
r"""
An embedding bag module attached with FakeQuantize modules for weight,
used for quantization aware training.
We adopt the same interf... | pytorch-master | torch/nn/qat/modules/embedding_ops.py |
from .modules import * # noqa: F403
| pytorch-master | torch/nn/quantized/__init__.py |
r""" Functional interface (quantized)."""
from typing import List, Optional
import warnings
import torch
from torch import Tensor
from torch.nn.modules.utils import _pair, _triple
from torch.nn.quantized.modules.utils import _pair_from_first
from torch.jit.annotations import BroadcastingList2
# Although some of the f... | pytorch-master | torch/nn/quantized/functional.py |
from .modules import * # noqa: F403
| pytorch-master | torch/nn/quantized/_reference/__init__.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional, Dict, Any
from .utils import ReferenceQuantizedModule
class Linear(nn.Linear, ReferenceQuantizedModule):
""" A reference quantized linear module that fits into the FX
Graph Mode Quantization workflow
activation ... | pytorch-master | torch/nn/quantized/_reference/modules/linear.py |
from .linear import Linear
from .conv import Conv1d, Conv2d, Conv3d, ConvTranspose1d, ConvTranspose2d, ConvTranspose3d
from .rnn import RNNCell, LSTMCell, GRUCell, LSTM
from .sparse import Embedding, EmbeddingBag
__all__ = [
'Linear',
'Conv1d',
'Conv2d',
'Conv3d',
'ConvTranspose1d',
'ConvTransp... | pytorch-master | torch/nn/quantized/_reference/modules/__init__.py |
import torch
from typing import Dict, Any
class ReferenceQuantizedModule(torch.nn.Module):
def _init_weight_qparams(self, weight_qparams, device):
if weight_qparams is None:
weight_qparams = {
"qscheme": torch.per_tensor_affine,
"dtype": torch.quint8,
... | pytorch-master | torch/nn/quantized/_reference/modules/utils.py |
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from .utils import ReferenceQuantizedModule
from typing import Optional, Dict, Any
class Embedding(nn.Embedding, ReferenceQuantizedModule):
""" A reference quantized Embedding module that fits into the
FX Graph Mode Quantization wor... | pytorch-master | torch/nn/quantized/_reference/modules/sparse.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional, Dict, Any, List
from torch.nn.common_types import _size_1_t
from .utils import ReferenceQuantizedModule
class _ConvNd(torch.nn.modules.conv._ConvNd, ReferenceQuantizedModule):
""" A reference version of nn.quantized.Con... | pytorch-master | torch/nn/quantized/_reference/modules/conv.py |
import torch
import torch.nn as nn
from torch import Tensor
from .utils import _quantize_and_dequantize_weight
from .utils import _quantize_weight
from typing import Optional, Dict, Any, Tuple
from torch import _VF
from torch.nn.utils.rnn import PackedSequence
def apply_permutation(tensor: Tensor, permutation: Tensor,... | pytorch-master | torch/nn/quantized/_reference/modules/rnn.py |
from .modules import * # noqa: F403
| pytorch-master | torch/nn/quantized/dynamic/__init__.py |
import torch
import torch.nn.quantized as nnq
import torch.nn.intrinsic as nni
from torch.nn.quantized.modules.utils import _quantize_weight
class Linear(nnq.Linear):
r"""
A dynamic quantized linear module with floating point tensor as inputs and outputs.
We adopt the same interface as `torch.nn.Linear`, p... | pytorch-master | torch/nn/quantized/dynamic/modules/linear.py |
from .linear import Linear
from .rnn import LSTM, GRU, LSTMCell, RNNCell, GRUCell
from .conv import Conv1d, Conv2d, Conv3d, ConvTranspose1d, ConvTranspose2d, ConvTranspose3d
__all__ = [
'Linear',
'LSTM',
'GRU',
'LSTMCell',
'RNNCell',
'GRUCell',
'Conv1d',
'Conv2d',
'Conv3d',
'Co... | pytorch-master | torch/nn/quantized/dynamic/modules/__init__.py |
# coding=utf-8
r"""Dynamically quantized convolution modules."""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torch._ops import ops
from torch.nn.common_types import _size_1_t
from torch.nn.modules.utils import _single, _pair, _triple
from torch.nn.quantized.modules... | pytorch-master | torch/nn/quantized/dynamic/modules/conv.py |
import numbers
import warnings
import torch
import torch.nn as nn
from torch import Tensor # noqa: F401
from torch._jit_internal import Tuple, Optional, List, Union, Dict # noqa: F401
from torch.nn.utils.rnn import PackedSequence
from torch.nn.quantized.modules.utils import _quantize_weight
__all__ = ['pack_weight_... | pytorch-master | torch/nn/quantized/dynamic/modules/rnn.py |
import torch
import torch.nn.quantized.functional
import torch.nn.intrinsic as nni
from torch import Tensor
class _BatchNorm(torch.nn.modules.batchnorm._BatchNorm):
def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None) -> None:
factory_kwargs = {'device': device, 'dtype': dtype}... | pytorch-master | torch/nn/quantized/modules/batchnorm.py |
from typing import List
import torch
from torch import Tensor
from torch._ops import ops
__all__ = ['FloatFunctional', 'FXFloatFunctional', 'QFunctional']
class FloatFunctional(torch.nn.Module):
r"""State collector class for float operations.
The instance of this class can be used instead of the ``torch.`` ... | pytorch-master | torch/nn/quantized/modules/functional_modules.py |
from collections.abc import Iterable
import torch
import torch.nn as nn
import torch.nn.intrinsic as nni
import torch.nn.intrinsic.qat as nniqat
from torch.nn.quantized.modules.utils import _quantize_weight, hide_packed_params_repr, WeightedQuantizedModule
from torch.nn.utils.fusion import fuse_linear_bn_weights
from ... | pytorch-master | torch/nn/quantized/modules/linear.py |
import torch
from torch.nn.modules.pooling import MaxPool2d
from .activation import ReLU6, Hardswish, ELU, LeakyReLU, Sigmoid, Softmax, MultiheadAttention, PReLU
from .dropout import Dropout
from .batchnorm import BatchNorm2d, BatchNorm3d
from .normalization import LayerNorm, GroupNorm, InstanceNorm1d, \
InstanceN... | pytorch-master | torch/nn/quantized/modules/__init__.py |
import torch
import torch.nn.quantized.functional
class ReLU6(torch.nn.ReLU):
r"""Applies the element-wise function:
:math:`\text{ReLU6}(x) = \min(\max(x_0, x), q(6))`, where :math:`x_0` is the
zero_point, and :math:`q(6)` is the quantized representation of number 6.
Args:
inplace: can option... | pytorch-master | torch/nn/quantized/modules/activation.py |
import abc
import torch
from itertools import repeat
import collections
from torch.nn.modules.module import _addindent
class WeightedQuantizedModule(torch.nn.Module, metaclass=abc.ABCMeta):
"""Wrapper for quantized modules than can be lowered from reference modules."""
@classmethod
@abc.abstractmethod
... | pytorch-master | torch/nn/quantized/modules/utils.py |
import torch
import torch.nn.quantized.functional
__all__ = ['Dropout']
class Dropout(torch.nn.Dropout):
r"""This is the quantized equivalent of :class:`~torch.nn.Dropout`.
And this is a placeholder to enable models where fp32 tensors
had dropout to work with quantized tensors in train and eval mo... | pytorch-master | torch/nn/quantized/modules/dropout.py |
# coding=utf-8
r"""Quantized convolution modules."""
from typing import Optional, List, TypeVar
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.intrinsic as nni
import torch.nn.intrinsic.qat as nniqat
from torch._ops import ops
from torch.nn.common_types import _size_1_t
from torch... | pytorch-master | torch/nn/quantized/modules/conv.py |
import torch
import torch.nn.quantized.functional
__all__ = ['LayerNorm', 'GroupNorm', 'InstanceNorm1d', 'InstanceNorm2d', 'InstanceNorm3d']
class LayerNorm(torch.nn.LayerNorm):
r"""This is the quantized version of :class:`~torch.nn.LayerNorm`.
Additional args:
* **scale** - quantization scale of the... | pytorch-master | torch/nn/quantized/modules/normalization.py |
import torch
class LSTM(torch.nn.quantizable.LSTM):
r"""A quantized long short-term memory (LSTM).
For the description and the argument types, please, refer to :class:`~torch.nn.LSTM`
Attributes:
layers : instances of the `_LSTMLayer`
.. note::
To access the weights and biases, you n... | pytorch-master | torch/nn/quantized/modules/rnn.py |
import torch
import torch.nn as nn
from torch import Tensor # noqa: F401
from torch._jit_internal import Optional, List # noqa: F401
from torch.nn.quantized.modules.utils import hide_packed_params_repr
from torch.nn.quantized.modules.utils import _quantize_weight
__all__ = ['EmbeddingPackedParams', 'Embedding', 'Emb... | pytorch-master | torch/nn/quantized/modules/embedding_ops.py |
# this is for historical pickle deserilaization, it is not used otherwise
def _get_thnn_function_backend():
pass
| pytorch-master | torch/nn/backends/thnn.py |
pytorch-master | torch/nn/backends/__init__.py | |
"""
Spectral Normalization from https://arxiv.org/abs/1802.05957
"""
import torch
from torch.nn.functional import normalize
from typing import Any, Optional, TypeVar
from ..modules import Module
__all__ = ['SpectralNorm', 'SpectralNormLoadStateDictPreHook', 'SpectralNormStateDictHook',
'spectral_norm', 'rem... | pytorch-master | torch/nn/utils/spectral_norm.py |
import torch
from typing import Iterable, Optional
def parameters_to_vector(parameters: Iterable[torch.Tensor]) -> torch.Tensor:
r"""Convert parameters to one vector
Args:
parameters (Iterable[Tensor]): an iterator of Tensors that are the
parameters of a model.
Returns:
The p... | pytorch-master | torch/nn/utils/convert_parameters.py |
import contextlib
from typing import Any, Callable, Dict, Iterator, List, Tuple
import torch
from torch import Tensor
__all__ = ["functional_call"]
# We avoid typing module here because module attributes are declared as Union[Parameter, Tensor] by default
# and using other types causes mypy errors
def _change_class(... | pytorch-master | torch/nn/utils/stateless.py |
import torch
from torch.nn.modules.container import ModuleList, ModuleDict, Module
from torch.nn.parameter import Parameter
from torch import Tensor
import collections
import copyreg
from copy import deepcopy
from contextlib import contextmanager
from typing import Union, Optional, Dict, Tuple, Sequence
__all__ = ['c... | pytorch-master | torch/nn/utils/parametrize.py |
import torch
def convert_conv2d_weight_memory_format(module, memory_format):
r"""Convert ``memory_format`` of ``nn.Conv2d.weight`` to ``memory_format``
The conversion recursively applies to nested ``nn.Module``, including ``module``.
Note that it only changes the memory_format, but not the semantics of eac... | pytorch-master | torch/nn/utils/memory_format.py |
import functools
import torch
from torch.nn.utils.stateless import functional_call
from torch.nn.utils._expanded_weights.expanded_weights_impl import ExpandedWeight
from torch.utils._pytree import tree_flatten
# dependency on `functional_call` means that this can't be exposed in utils
# without creating circular dep... | pytorch-master | torch/nn/utils/_per_sample_grad.py |
from . import rnn
from .clip_grad import clip_grad_norm, clip_grad_norm_, clip_grad_value_
from .weight_norm import weight_norm, remove_weight_norm
from .convert_parameters import parameters_to_vector, vector_to_parameters
from .spectral_norm import spectral_norm, remove_spectral_norm
from .fusion import fuse_conv_bn_e... | pytorch-master | torch/nn/utils/__init__.py |
r"""
Weight Normalization from https://arxiv.org/abs/1602.07868
"""
from torch.nn.parameter import Parameter, UninitializedParameter
from torch import _weight_norm, norm_except_dim
from typing import Any, TypeVar
from ..modules import Module
__all__ = ['WeightNorm', 'weight_norm', 'remove_weight_norm']
class WeightNo... | pytorch-master | torch/nn/utils/weight_norm.py |
# This file is never automatically imported within PyTorch so it is ok to
# always warn here
import warnings
warnings.warn("The `torch.nn.utils._stateless` code is deprecated now that "
"it is publicly available. Please use `torch.nn.utils.stateless "
"instead.", DeprecationWarning)
# Impo... | pytorch-master | torch/nn/utils/_stateless.py |
import copy
import torch
def fuse_conv_bn_eval(conv, bn, transpose=False):
assert(not (conv.training or bn.training)), "Fusion only for eval!"
fused_conv = copy.deepcopy(conv)
fused_conv.weight, fused_conv.bias = \
fuse_conv_bn_weights(fused_conv.weight, fused_conv.bias,
... | pytorch-master | torch/nn/utils/fusion.py |
r"""
Pruning methods
"""
import numbers
from abc import ABC, abstractmethod
from collections.abc import Iterable
from typing import Tuple
import torch
class BasePruningMethod(ABC):
r"""Abstract base class for creation of new pruning techniques.
Provides a skeleton for customization requiring the overriding ... | pytorch-master | torch/nn/utils/prune.py |
from enum import Enum, auto
import torch
from torch import Tensor
from ..utils import parametrize
from ..modules import Module
from .. import functional as F
from typing import Optional
__all__ = ['orthogonal', 'spectral_norm']
def _is_orthogonal(Q, eps=None):
n, k = Q.size(-2), Q.size(-1)
Id = torch.eye(k,... | pytorch-master | torch/nn/utils/parametrizations.py |
import inspect
import torch
def skip_init(module_cls, *args, **kwargs):
r"""
Given a module class object and args / kwargs, instantiates the module without initializing
parameters / buffers. This can be useful if initialization is slow or if custom initialization will
be performed, making the default... | pytorch-master | torch/nn/utils/init.py |
from collections import namedtuple
import warnings
import torch
from torch import Tensor
from ... import _VF
from ..._jit_internal import Optional
from typing import List, Tuple, Union, Iterable
__all__ = ['PackedSequence', 'invert_permutation', 'pack_padded_sequence', 'pad_packed_sequence', 'pad_sequence',
... | pytorch-master | torch/nn/utils/rnn.py |
import warnings
import torch
from torch._six import inf
from typing import Union, Iterable
_tensor_or_tensors = Union[torch.Tensor, Iterable[torch.Tensor]]
__all__ = ['clip_grad_norm_', 'clip_grad_norm', 'clip_grad_value_']
def clip_grad_norm_(
parameters: _tensor_or_tensors, max_norm: float, norm_type: floa... | pytorch-master | torch/nn/utils/clip_grad.py |
from functools import reduce
import operator
import torch
import torch.nn.functional as F
from .expanded_weights_impl import ExpandedWeight, implements_per_sample_grads
from .expanded_weights_utils import standard_kwargs, \
forward_helper, set_grad_sample_if_exists, unpack_expanded_weight_or_tensor
from typing impo... | pytorch-master | torch/nn/utils/_expanded_weights/group_norm_expanded_weights.py |
import torch
import torch.nn.functional as F
from .expanded_weights_impl import ExpandedWeight, implements_per_sample_grads
from .expanded_weights_utils import forward_helper, set_grad_sample_if_exists, \
standard_kwargs, sum_over_all_but_batch_and_last_n, unpack_expanded_weight_or_tensor
from typing import List, ... | pytorch-master | torch/nn/utils/_expanded_weights/layer_norm_expanded_weights.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.