python_code
stringlengths
0
1.02M
repo_name
stringlengths
9
48
file_path
stringlengths
5
114
# flake8: noqa F401 """The implementations should be moved here as soon as their deprecation period is over.""" from torch.testing._legacy import ( _validate_dtypes, _dispatch_dtypes, all_types, all_types_and, all_types_and_complex, all_types_and_complex_and, all_types_and_half, complex...
pytorch-master
torch/testing/_internal/common_dtype.py
from abc import abstractmethod import math import tempfile import unittest from copy import deepcopy from functools import reduce, partial, wraps from itertools import product from operator import mul from math import pi import torch import torch.cuda import torch.nn as nn import torch.nn.functional as F from torch....
pytorch-master
torch/testing/_internal/common_nn.py
import torch from torch.testing._internal.common_utils import TEST_WITH_ROCM class AutocastTestLists(object): def _rnn_cell_args(self, n, num_chunks, is_lstm, dev, dtype): input = (torch.randn((n, n), device=dev, dtype=torch.float32),) hx = ((torch.randn((n, n), device=dev, dtype=torch.float32), ...
pytorch-master
torch/testing/_internal/autocast_test_lists.py
# Owner(s): ["oncall: distributed"] import functools import itertools import sys from abc import ABC, abstractmethod from contextlib import suppress from copy import deepcopy from enum import Enum, auto from math import inf from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union from unittest import...
pytorch-master
torch/testing/_internal/common_fsdp.py
import copy import gc import inspect import runpy import threading from collections import namedtuple from enum import Enum from functools import wraps from typing import List, Any, ClassVar, Optional, Sequence, Tuple, Union, Dict, Set import unittest import os import torch from torch.testing._internal.common_utils imp...
pytorch-master
torch/testing/_internal/common_device_type.py
import faulthandler import logging import multiprocessing import os import sys import tempfile import threading import subprocess import time import traceback import types import unittest from contextlib import contextmanager from dataclasses import dataclass from datetime import timedelta from enum import Enum from fu...
pytorch-master
torch/testing/_internal/common_distributed.py
pytorch-master
torch/testing/_internal/__init__.py
from functools import wraps, partial from itertools import product, chain, islice import itertools import functools import collections import copy import operator import random import unittest import math import torch import numpy as np from torch._six import inf import collections.abc from typing import Any, Dict, L...
pytorch-master
torch/testing/_internal/common_methods_invocations.py
import torch from torch.utils._pytree import tree_map from typing import Iterator, List import logging import contextlib import itertools from torch.utils._python_dispatch import TorchDispatchMode # How the chain of calls works for LoggingTensor: # 1. Call torch.sin # 2. Attempt __torch_function__. In LoggingTensor t...
pytorch-master
torch/testing/_internal/logging_tensor.py
from collections import defaultdict from collections.abc import Iterable import numpy as np import torch import hypothesis from functools import reduce from hypothesis import assume from hypothesis import settings from hypothesis import strategies as st from hypothesis.extra import numpy as stnp from hypothesis.strate...
pytorch-master
torch/testing/_internal/hypothesis_utils.py
r"""This file is allowed to initialize CUDA context when imported.""" import functools import torch import torch.cuda from torch.testing._internal.common_utils import TEST_NUMBA, IS_WINDOWS import inspect import contextlib from distutils.version import LooseVersion TEST_CUDA = torch.cuda.is_available() TEST_MULTIGPU...
pytorch-master
torch/testing/_internal/common_cuda.py
r"""Importing this file includes common utility methods and base clases for checking quantization api and properties of resulting modules. """ import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.intrinsic.quantized.dynamic as nniqd import torch.nn.quantized as nnq import torch.nn.quantiz...
pytorch-master
torch/testing/_internal/common_quantization.py
import torch import unittest from copy import deepcopy from enum import Enum from functools import wraps, partial from itertools import chain, product import itertools import torch.nn.functional as F from torch.testing import make_tensor from torch.testing._internal.common_cuda import TEST_CUDNN from torch.testing._int...
pytorch-master
torch/testing/_internal/common_modules.py
# Torch import torch import torch.cuda import torch.jit import torch.jit._logging import torch.jit.frontend import torch.jit.quantized # Testing utils from torch.testing._internal.common_dtype import floating_and_complex_types_and from torch.testing._internal.common_utils import TestCase, \ freeze_rng_state, Tempo...
pytorch-master
torch/testing/_internal/common_jit.py
import torch from torch.utils._pytree import tree_flatten, tree_map from torch.fx.operator_schemas import normalize_function from torch.testing._internal.jit_utils import clone_inputs from torch.utils._python_dispatch import TorchDispatchMode from itertools import combinations from collections import namedtuple from co...
pytorch-master
torch/testing/_internal/schema_check_mode.py
# Torch from torch.jit.annotations import BroadcastingList2, BroadcastingList3 # noqa: F401 import torch.nn.functional as F import torch import torch.cuda import torch.jit import torch.jit._logging import torch.jit.frontend from torch.testing._internal.common_nn import module_tests, new_module_tests from torch.testing...
pytorch-master
torch/testing/_internal/jit_metaprogramming_utils.py
import os import re import sys from typing import List __all__ = [ "check_code_for_cuda_kernel_launches", "check_cuda_kernel_launches", ] # FILES TO EXCLUDE (match is done with suffix using `endswith`) # You wouldn't drive without a seatbelt, though, so why would you # launch a kernel without some safety? Use...
pytorch-master
torch/testing/_internal/check_kernel_launches.py
r"""Importing this file must **not** initialize CUDA context. test_distributed relies on this assumption to properly run. This means that when this is imported no CUDA calls shall be made, including torch.cuda.device_count(), etc. torch.testing._internal.common_cuda.py can freely initialize CUDA context when imported....
pytorch-master
torch/testing/_internal/common_utils.py
import math import torch import torch.nn as nn class LinearReluFunctionalChild(nn.Module): def __init__(self, N): super().__init__() self.w1 = nn.Parameter(torch.empty(N, N)) self.b1 = nn.Parameter(torch.zeros(N)) torch.nn.init.kaiming_uniform_(self.w1, a=math.sqrt(5)) def fo...
pytorch-master
torch/testing/_internal/quantization_torch_package_models.py
r"""Importing this file includes common utility methods for checking quantized tensors and modules. """ import numpy as np import torch from contextlib import contextmanager from torch.testing._internal.common_utils import TEST_WITH_ASAN, TEST_WITH_TSAN, TEST_WITH_UBSAN, IS_PPC, IS_MACOS, IS_WINDOWS supported_qengines...
pytorch-master
torch/testing/_internal/common_quantized.py
import torch from copy import deepcopy from torch.utils._pytree import tree_map # TODO: Move LoggingTensor here. from torch.testing._internal.logging_tensor import LoggingTensor # Base class for wrapper-style tensors. class WrapperTensor(torch.Tensor): @staticmethod def __new__(cls, *args, **kwargs): ...
pytorch-master
torch/testing/_internal/common_subclass.py
import torch from torch import Tensor import contextlib import itertools from torch.utils._pytree import tree_map, tree_flatten, tree_unflatten from functools import partial from torch.utils._mode_utils import no_dispatch from torch.utils._python_dispatch import enable_torch_dispatch_mode import torch.autograd.forward_...
pytorch-master
torch/testing/_internal/composite_compliance.py
import re import sys import time from functools import partial, wraps from typing import Tuple import torch.distributed as dist import torch.distributed.rpc as rpc from torch.distributed.rpc import _rref_context_get_debug_info from torch.testing._internal.common_utils import FILE_SCHEMA, TEST_WITH_TSAN if not dist.i...
pytorch-master
torch/testing/_internal/dist_utils.py
# Torch from torch.autograd import Variable from torch.autograd.function import _nested_map from torch.jit.annotations import BroadcastingList2, BroadcastingList3 # noqa: F401 from torch.onnx import OperatorExportTypes import torch import torch.cuda import torch.jit import torch.jit._logging import torch.jit.frontend...
pytorch-master
torch/testing/_internal/jit_utils.py
pytorch-master
torch/testing/_internal/generated/__init__.py
pytorch-master
torch/testing/_internal/opinfo/__init__.py
from dataclasses import dataclass, asdict import collections.abc import operator from typing import Any, Callable, List, Optional, Tuple, Iterable from enum import Enum import unittest import math from functools import partial from itertools import product import torch from torch.testing import make_tensor from torch....
pytorch-master
torch/testing/_internal/opinfo/core.py
import collections import warnings from functools import partial import torch from torch.testing._internal.common_cuda import (TEST_CUDA) from torch.testing._internal.common_dtype import ( all_types_and_complex_and, all_types_and_complex, all_types_and_half, all_types, complex_types, floating_a...
pytorch-master
torch/testing/_internal/opinfo/utils.py
pytorch-master
torch/testing/_internal/test_module/__init__.py
from __future__ import division def div_int_future(): return 1 / 2 def div_float_future(): return 3.14 / 0.125
pytorch-master
torch/testing/_internal/test_module/future_div.py
import torch # noqa: F401 def div_int_nofuture(): return 1 / 2 def div_float_nofuture(): return 3.14 / 0.125
pytorch-master
torch/testing/_internal/test_module/no_future_div.py
#!/usr/bin/env python3 import contextlib import enum import logging import os import threading from typing import NamedTuple import torch import torch.distributed as dist import torch.distributed.autograd as dist_autograd import torch.nn as nn from torch.distributed import rpc from torch.distributed.nn import RemoteM...
pytorch-master
torch/testing/_internal/distributed/ddp_under_dist_autograd_test.py
pytorch-master
torch/testing/_internal/distributed/__init__.py
from contextlib import contextmanager from datetime import timedelta from functools import ( partial, wraps, ) import torch.distributed as dist import torch.distributed.distributed_c10d as c10d class MockProcessGroup(dist.ProcessGroup): def __init__(self, rank, world): super(MockProcessGroup, sel...
pytorch-master
torch/testing/_internal/distributed/distributed_utils.py
import torch import torch.distributed as dist from torch import nn from torch.nn.parallel import DistributedDataParallel from torch.testing._internal.dist_utils import INIT_METHOD_TEMPLATE, dist_init from torch.testing._internal.distributed.rpc.rpc_agent_test_fixture import ( RpcAgentTestFixture, ) from torch.test...
pytorch-master
torch/testing/_internal/distributed/pipe_with_ddp_test.py
import copy import itertools import math import os import random import sys import tempfile import time from collections import namedtuple, OrderedDict from contextlib import contextmanager, suppress from datetime import timedelta from functools import reduce from typing import Union, NamedTuple, Callable, Any import n...
pytorch-master
torch/testing/_internal/distributed/distributed_test.py
#!/usr/bin/env python3 import os import sys import unittest from typing import Dict, List, Type from torch.testing._internal.common_distributed import MultiProcessTestCase from torch.testing._internal.common_utils import ( TEST_WITH_DEV_DBG_ASAN, find_free_port, IS_SANDCASTLE, ) from torch.testing._interna...
pytorch-master
torch/testing/_internal/distributed/rpc_utils.py
pytorch-master
torch/testing/_internal/distributed/pipeline/__init__.py
pytorch-master
torch/testing/_internal/distributed/nn/__init__.py
pytorch-master
torch/testing/_internal/distributed/nn/api/__init__.py
#!/usr/bin/python3 import enum from typing import Tuple import torch import torch.distributed.rpc as rpc import torch.testing._internal.dist_utils as dist_utils from torch import Tensor, nn from torch._jit_internal import Future from torch.distributed.nn import RemoteModule from torch.distributed.nn.api.remote_module ...
pytorch-master
torch/testing/_internal/distributed/nn/api/remote_module_test.py
import torch import torch.nn as nn from torch.distributed._shard.sharded_tensor import ShardedTensor class SimpleMegatronLM(nn.Module): def __init__(self, linear_size, rank=None, dtype=torch.float32): super().__init__() self.fc1 = nn.Linear(*linear_size[0], dtype=dtype) self.gelu = nn.GEL...
pytorch-master
torch/testing/_internal/distributed/_shard/test_common.py
pytorch-master
torch/testing/_internal/distributed/_shard/__init__.py
import sys from functools import wraps, partial import torch import torch.distributed as dist from torch.distributed import rpc from torch.testing._internal.common_distributed import ( MultiProcessTestCase, TEST_SKIPS, tp_transports, ) TEST_GPU_NUM = 4 class ShardedTensorTestBase(MultiProcessTestCase): ...
pytorch-master
torch/testing/_internal/distributed/_shard/sharded_tensor/__init__.py
import builtins import torch from torch.distributed._shard.sharding_spec import ( ChunkShardingSpec, EnumerableShardingSpec, ShardMetadata, ) from torch.distributed._shard.sharding_spec._internals import ( get_chunked_dim_size, get_split_size, ) def generate_chunk_sharding_specs_for_test(sharding...
pytorch-master
torch/testing/_internal/distributed/_shard/sharded_tensor/_test_ops_common.py
import copy import random import torch from torch.distributed._shard import sharded_tensor from torch.distributed._shard.sharding_spec import ( ChunkShardingSpec, ) PLACEMENTS = [ "rank:0/cuda:0", "rank:1/cuda:1", "rank:2/cuda:2", "rank:3/cuda:3", ] DEFAULT_GPU_NUM = 4 def _chunk_sharding_specs...
pytorch-master
torch/testing/_internal/distributed/_shard/sharded_tensor/_test_st_common.py
import torch.distributed.rpc as rpc import torch.distributed.rpc._testing # noqa: F401 from torch.testing._internal.distributed.rpc.rpc_agent_test_fixture import ( RpcAgentTestFixture, ) # The following message types are currently retried in the RREF protocol and # distributed autograd. Thus only these messages s...
pytorch-master
torch/testing/_internal/distributed/rpc/faulty_rpc_agent_test_fixture.py
import torch import time import torch.distributed.rpc as rpc from torch.distributed.rpc.api import _delete_all_user_and_unforked_owner_rrefs from torch.testing._internal.dist_utils import ( dist_init, wait_until_pending_futures_and_users_flushed, wait_until_owners_and_forks_on_rank, worker_name, ) from ...
pytorch-master
torch/testing/_internal/distributed/rpc/faulty_agent_rpc_test.py
pytorch-master
torch/testing/_internal/distributed/rpc/__init__.py
import sys import threading import time from enum import Enum import random import torch import torch.nn as nn from datetime import timedelta import torch.distributed as dist import torch.distributed.autograd as dist_autograd import torch.distributed.rpc as rpc import torch.testing._internal.dist_utils from torch.autog...
pytorch-master
torch/testing/_internal/distributed/rpc/dist_autograd_test.py
import os from abc import ABC, abstractmethod import torch.testing._internal.dist_utils class RpcAgentTestFixture(ABC): @property def world_size(self) -> int: return 4 @property def init_method(self): use_tcp_init = os.environ.get("RPC_INIT_WITH_TCP", None) if use_tcp_init ==...
pytorch-master
torch/testing/_internal/distributed/rpc/rpc_agent_test_fixture.py
import torch.distributed.rpc as rpc from torch.testing._internal.distributed.rpc.rpc_agent_test_fixture import ( RpcAgentTestFixture, ) from torch.testing._internal.common_distributed import ( tp_transports, ) class TensorPipeRpcAgentTestFixture(RpcAgentTestFixture): @property def rpc_backend(self): ...
pytorch-master
torch/testing/_internal/distributed/rpc/tensorpipe_rpc_agent_test_fixture.py
import concurrent.futures import contextlib import json import os import sys import threading import time from collections import namedtuple from functools import partial from threading import Event from threading import Lock from unittest import mock import torch import torch.nn as nn import torch.distributed as dis...
pytorch-master
torch/testing/_internal/distributed/rpc/rpc_test.py
import threading import torch import torch.distributed.autograd as dist_autograd import torch.distributed.rpc as rpc from torch import optim from torch.distributed.optim import DistributedOptimizer from torch.testing._internal.dist_utils import dist_init from torch.testing._internal.distributed.rpc.rpc_agent_test_fix...
pytorch-master
torch/testing/_internal/distributed/rpc/dist_optimizer_test.py
pytorch-master
torch/testing/_internal/distributed/rpc/jit/__init__.py
from typing import Dict, Tuple import torch import torch.distributed.autograd as dist_autograd import torch.distributed.rpc as rpc from torch import Tensor from torch.distributed.rpc import rpc_async from torch.testing import FileCheck from torch.testing._internal.dist_utils import dist_init, worker_name from torch.te...
pytorch-master
torch/testing/_internal/distributed/rpc/jit/dist_autograd_test.py
import time import io from typing import Dict, List, Tuple, Any import torch import torch.distributed as dist import torch.distributed.rpc as rpc from torch import Tensor from torch.autograd.profiler import record_function from torch.distributed.rpc import RRef from torch.distributed.rpc.internal import RPCExecMode, _...
pytorch-master
torch/testing/_internal/distributed/rpc/jit/rpc_test.py
from typing import Dict, Tuple import torch import torch.distributed.rpc as rpc from torch import Tensor from torch.distributed.rpc import RRef from torch.testing._internal.dist_utils import ( dist_init, worker_name, wait_until_pending_futures_and_users_flushed ) from torch.testing._internal.distributed.rp...
pytorch-master
torch/testing/_internal/distributed/rpc/jit/rpc_test_faulty.py
pytorch-master
torch/testing/_internal/distributed/rpc/examples/__init__.py
# If you need to modify this file to make this test pass, please also apply same edits accordingly to # https://github.com/pytorch/examples/blob/master/distributed/rpc/rl/main.py # and https://pytorch.org/tutorials/intermediate/rpc_tutorial.html import numpy as np from itertools import count import torch import torch...
pytorch-master
torch/testing/_internal/distributed/rpc/examples/reinforcement_learning_rpc_test.py
# If you need to modify this file to make this test pass, please also apply same edits accordingly to # https://github.com/pytorch/examples/blob/master/distributed/rpc/batch/parameter_server.py # and https://pytorch.org/tutorials/intermediate/rpc_async_execution.html#batch-updating-parameter-server import threading fr...
pytorch-master
torch/testing/_internal/distributed/rpc/examples/parameter_server_test.py
pytorch-master
torch/testing/_internal/codegen/__init__.py
import torch import numpy as np import argparse from typing import Dict # debug print DEBUG_PRINT = False ################################################################################ # configuration for random tests setup ################################################################################ # maximum ...
pytorch-master
torch/testing/_internal/codegen/random_topo_test.py
import torch.nn as nn class Net(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(10, 20)
pytorch-master
torch/testing/_internal/data/network1.py
pytorch-master
torch/testing/_internal/data/__init__.py
import torch.nn as nn class Net(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(10, 20) self.relu = nn.ReLU()
pytorch-master
torch/testing/_internal/data/network2.py
import torch import functools import warnings from typing import Any, Optional from torch.types import _dtype __all__ = ['autocast_decorator', 'autocast'] def autocast_decorator(autocast_instance, func): @functools.wraps(func) def decorate_autocast(*args, **kwargs): with autocast_instance: ...
pytorch-master
torch/amp/autocast_mode.py
from .autocast_mode import autocast
pytorch-master
torch/amp/__init__.py
import torch from typing import Union class _InsertPoint(object): def __init__(self, insert_point_graph: torch._C.Graph, insert_point: Union[torch._C.Node, torch._C.Block]): self.insert_point = insert_point self.g = insert_point_graph self.guard = None def __enter__(self): self...
pytorch-master
torch/jit/_ir_utils.py
import torch import inspect import typing import pathlib import sys from typing import Optional, Iterable, List, Dict from collections import defaultdict from types import CodeType _IS_MONKEYTYPE_INSTALLED = True try: import monkeytype # type: ignore[import] from monkeytype import trace as monkeytype_trace ...
pytorch-master
torch/jit/_monkeytype_config.py
import torch from torch import Tensor aten = torch.ops.aten from typing import Optional, List, Dict, Set import inspect from torch.fx.operator_schemas import get_signature_for_torch_op import warnings decomposition_table: Dict[str, torch.jit.ScriptFunction] = {} function_name_set: Set[str] = set() def check_decompo...
pytorch-master
torch/jit/_decompositions.py
import inspect import torch import types import collections import textwrap import functools import warnings import sys from typing import Dict, List, Set, Type import torch._jit_internal as _jit_internal from torch._sources import fake_range from torch.jit.frontend import get_default_args, get_jit_class_def, get_jit_...
pytorch-master
torch/jit/_recursive.py
import torch add_stat_value = torch.ops.prim.AddStatValue set_logger = torch._C._logging_set_logger LockingLogger = torch._C.LockingLogger AggregationType = torch._C.AggregationType NoopLogger = torch._C.NoopLogger time_point = torch.ops.prim.TimePoint
pytorch-master
torch/jit/_logging.py
"""Serialization This module contains functionality for serializing TorchScript modules, notably: * torch.jit.save * torch.jit.load This is not intended to be imported directly; please use the exposed functionalities in `torch.jit`. """ import os import pathlib import torch from torch._six import string_clas...
pytorch-master
torch/jit/_serialization.py
from torch import Tensor, _VF # noqa: F401 from torch.nn.utils.rnn import PackedSequence import torch import warnings from typing import List, Optional, Tuple class QuantizedLinear(torch.jit.ScriptModule): __constants__ = ['scale', 'zero_point'] def __init__(self, other): super(QuantizedLinear, se...
pytorch-master
torch/jit/quantized.py
"""TorchScript This module contains functionality to support the JIT's scripting frontend, notably: - torch.jit.script This is not intended to be imported directly; please use the exposed functionalities in `torch.jit`. """ import functools import collections import enum import inspect import copy import pickle i...
pytorch-master
torch/jit/_script.py
from typing import List, Any, Optional, Union, Dict, Callable, Tuple import math number = Union[int, float] # flake8: noqa ### # There are generated files that depend on this file # To re-generate, please run from the root of the repo: # python torchgen/shape_functions/gen_jit_shape_functions.py # How to test: # Afte...
pytorch-master
torch/jit/_shape_functions.py
import torch from torch._ops import OpOverload, OpOverloadPacket def _register_decomposition(op: OpOverload, graph: torch._C.Graph): assert not isinstance(op, OpOverloadPacket), f"Must pass specific op overload, not overload packet, found {op}" assert isinstance(op, OpOverload) torch._C._jit_register_deco...
pytorch-master
torch/jit/_decomposition_utils.py
"""Freezing This is not intended to be imported directly; please use the exposed functionalities in `torch.jit`. """ from typing import Optional, List import torch from torch.jit._script import RecursiveScriptModule, ScriptModule def freeze(mod, preserved_attrs: Optional[List[str]] = None, optimize_numerics: bool ...
pytorch-master
torch/jit/_freeze.py
# These functions are referenced from the pickle archives produced by # ScriptModule.save() # These (`build_*`) functions used to be used by `pickler.cpp` to specify # the type of the list for certain special types, but now all lists get # a type attached and restored via `restore_type_tag` below. The legacy # functi...
pytorch-master
torch/jit/_pickle.py
import ast import inspect import sys import textwrap import torch import warnings class AttributeTypeIsSupportedChecker(ast.NodeVisitor): """ Checks the ``__init__`` method of a given ``nn.Module`` to ensure that all instance-level attributes can be properly initialized. Specifically, we do type infe...
pytorch-master
torch/jit/_check.py
import torch.jit from textwrap import dedent from typing import Dict, Any def execWrapper(code, glob, loc): exec(code, glob, loc) def _gen_unsupported_methods_properties(): tensor_attrs = set(filter(lambda x: x[0] != "_", dir(torch.Tensor))) tensor = torch.tensor([2]) funcs_template = dedent(''' ...
pytorch-master
torch/jit/unsupported_tensor_ops.py
import torch import sys import ast import dataclasses import inspect import string import re from collections import namedtuple from textwrap import dedent from typing import List, Tuple # noqa: F401 from torch._C._jit_tree_views import ( ClassDef, Ident, Stmt, Decl, Def, Var, EmptyTypeAnnotation, Param, ExprS...
pytorch-master
torch/jit/frontend.py
import torch.jit from torch.jit._builtins import _find_builtin import inspect import textwrap # this file is for generating documentation using sphinx autodoc # > help(torch.jit.supported_ops) will also give a nice listed of the # supported ops programmatically def _hidden(name): return name.startswith('_') and no...
pytorch-master
torch/jit/supported_ops.py
import torch._C from contextlib import contextmanager from typing import Iterator, Any import warnings from torch.utils import set_module # These are imported so users can access them from the `torch.jit` module from torch._jit_internal import ( Final, Future, _IgnoreContextManager, _overload, _o...
pytorch-master
torch/jit/__init__.py
import contextlib import torch from typing import List, Tuple @contextlib.contextmanager def optimized_execution(should_optimize): """ A context manager that controls whether the JIT's executor will run optimizations before executing a function. """ stored_flag = torch._C._get_graph_executor_optim...
pytorch-master
torch/jit/_fuser.py
import math import cmath import warnings import torch import torch.backends.cudnn as cudnn from ..nn.modules.utils import _single, _pair, _triple, _quadruple, _list_with_default from collections import OrderedDict from typing import Dict, Optional _builtin_table: Optional[Dict[int, str]] = None _modules_containing...
pytorch-master
torch/jit/_builtins.py
# Functions for synthesizing magic methods for JIT-compiled dataclasses import os from functools import partial from torch._jit_internal import is_optional, FAKE_FILENAME_PREFIX from torch._sources import ParsedDef, SourceContext from typing import Callable, Dict, List import ast import dataclasses import inspect impor...
pytorch-master
torch/jit/_dataclass_impls.py
"""Tracing This module contains functionality to support the JIT's tracing frontend, notably: * torch.jit.trace * torch.jit.trace_module This is not intended to be imported directly; please use the exposed functionalities in `torch.jit`. """ import torch import copy import os import contextlib import functoo...
pytorch-master
torch/jit/_trace.py
from torch._C import _compile_graph_to_code_table, _generate_upgraders_graph from typing import List def format_bytecode(table): # given a nested tuple, convert it to nested list def listify(content): if not isinstance(content, tuple): return content return [listify(i) for i in cont...
pytorch-master
torch/jit/generate_bytecode.py
"""JIT-related state This module stores various pieces of Python-global state relating to the JIT. This is not intended to be imported directly; please the exposed functionalities in `torch.jit`. """ import torch import os import weakref class EnabledProxy: """Stores whether the JIT is enabled or not. This ...
pytorch-master
torch/jit/_state.py
"""Async API This module contains the API for parallelism in TorchScript, notably: * torch.jit.fork * torch.jit.wait This is not intended to be imported directly; please use the exposed functionalities in `torch.jit`. """ import torch from torch.utils import set_module from torch.jit._builtins import _regist...
pytorch-master
torch/jit/_async.py
import ast import enum import inspect import re import builtins import torch import warnings from .._jit_internal import List, Tuple, is_tuple, is_list, Dict, is_dict, Optional, \ is_optional, _qualified_name, Any, Future, is_future, is_ignored_fn, Union, is_union from .._jit_internal import BroadcastingList1, Broa...
pytorch-master
torch/jit/annotations.py
""" Tools to help with tensor property propagation. This is not intended to be imported directly; please use the exposed functionalities in `torch.jit`. """ from typing import Any, List import torch from torch import TensorType from torch._C import Graph def apply_input_props_using_example(graph: Graph, example_in...
pytorch-master
torch/jit/_passes/_property_propagation.py
pytorch-master
torch/jit/_passes/__init__.py
import torch from torch.jit._serialization import validate_map_location import pathlib import os def _load_for_lite_interpreter(f, map_location=None): r""" Load a :class:`LiteScriptModule` saved with :func:`torch.jit._save_for_lite_interpreter` Args: f: a file-like object (has to implement r...
pytorch-master
torch/jit/mobile/__init__.py
import torch._C._lazy def reset(): """Resets all metric counters.""" torch._C._lazy._reset_metrics() def counter_names(): """Retrieves all the currently active counter names.""" return torch._C._lazy._counter_names() def counter_value(name: str): """Return the value of the counter with the spe...
pytorch-master
torch/_lazy/metrics.py
import torch._C._lazy def get_force_fallback(): """Get the config used to force LTC fallback""" return torch._C._lazy._get_force_fallback() def set_force_fallback(configval): """Set the config used to force LTC fallback""" torch._C._lazy._set_force_fallback(configval) def set_reuse_ir(val: bool): ...
pytorch-master
torch/_lazy/config.py
import torch._C._lazy def mark_step(device: str = "", wait=False): """Triggers a mark step, which amounts to - collecting a group of 'live' lazy tensors to index into the compilation cache (lowering/compiling their IR graphs if not cached) - kicking off execution of the compiled function - (opti...
pytorch-master
torch/_lazy/__init__.py
import torch """ tensor_factory_functions defines the list of torch functions that create tensors. The list is grabbed by searching thru native_functions.yaml by the following regular expression: cat native_functions.yaml | grep 'func:' | grep -v "Tensor.*->" | grep "[-]>.*Tensor" It's possible that new tensor fac...
pytorch-master
torch/_lazy/tensor_factory_functions.py