import functools
import inspect
import os
import pkgutil
import re
import sys
from os import path
from sphinx.ext.autodoc import FunctionDocumenter
from sphinx.util.inspect import stringify_signature
import torch
try:
import torchvision
except ImportError:
import warnings
warnings.warn('unable to load "torchvision" package')
RELEASE = os.environ.get("RELEASE", False)
import pytorch_sphinx_theme2
html_theme = "pytorch_sphinx_theme2"
html_theme_path = [pytorch_sphinx_theme2.get_html_theme_path()]
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
from redirects import redirects
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.doctest",
"sphinx.ext.intersphinx",
"sphinx.ext.todo",
"sphinx.ext.coverage",
"sphinx.ext.napoleon",
"sphinx.ext.autosectionlabel",
"sphinxcontrib.katex",
"sphinx_copybutton",
"sphinx_design",
"myst_nb",
"sphinx.ext.linkcode",
"sphinxcontrib.mermaid",
"sphinx_sitemap",
"sphinx_reredirects",
]
myst_enable_extensions = [
"colon_fence",
"deflist",
"dollarmath",
"html_image",
]
myst_dmath_allow_space = False
myst_dmath_allow_digits = False
nb_execution_mode = "off"
suppress_warnings = ["myst-nb.lexer"]
html_baseurl = "https://docs.pytorch.org/docs/stable/"
sitemap_locales = [None]
sitemap_excludes = [
"search.html",
"genindex.html",
]
sitemap_url_scheme = "{link}"
html_additional_pages = {
"404": "404.html",
}
autosummary_generate = True
numpydoc_show_class_members = False
autosectionlabel_prefix_document = True
katex_prerender = True
project = "PyTorch"
copyright = "PyTorch Contributors"
author = "PyTorch Contributors"
torch_version = str(torch.__version__)
version = "main (" + torch_version + " )"
release = "main"
if RELEASE:
version = ".".join(torch_version.split(".")[:2])
html_title = " ".join((project, version, "documentation"))
release = version
switcher_version = "main" if not RELEASE else version
html_static_path = ["_static"]
html_theme_options = {
"analytics_id": "GTM-T8XT4PS",
"canonical_url": "https://docs.pytorch.org/docs/stable/",
"switcher": {
"json_url": "https://docs.pytorch.org/docs/pytorch-versions.json",
"version_match": switcher_version,
},
"show_toc_level": 2,
"navigation_with_keys": False,
"external_links": [
{
"name": "Tutorials",
"url": "https://docs.pytorch.org/tutorials/",
},
],
"show_version_warning_banner": True,
"llm_generate_full": "false",
"icon_links": [
{
"name": "X",
"url": "https://x.com/PyTorch",
"icon": "fa-brands fa-x-twitter",
},
{
"name": "GitHub",
"url": "https://github.com/pytorch/pytorch",
"icon": "fa-brands fa-github",
},
{
"name": "PyTorch Forum",
"url": "https://discuss.pytorch.org/",
"icon": "fa-brands fa-discourse",
},
{
"name": "PyPi",
"url": "https://pypi.org/project/torch/",
"icon": "fa-brands fa-python",
},
],
"navbar_align": "left",
"navbar_start": ["navbar-logo", "version-switcher"],
"navbar_center": ["navbar-nav"],
"navbar_end": ["search-field-custom", "theme-switcher", "navbar-icon-links"],
"header_links_before_dropdown": 6,
"navbar_persistent": [],
"use_edit_page_button": True,
"runllm_assistant_id": "834",
"runllm_name": "PyTorch Assistant",
"pytorch_project": "docs",
}
theme_variables = pytorch_sphinx_theme2.get_theme_variables()
html_context = {
"github_url": "https://github.com",
"github_user": "pytorch",
"github_repo": "pytorch",
"feedback_url": "https://github.com/pytorch/pytorch",
"github_version": "main",
"pytorch_project": "docs",
"doc_path": "docs/source",
"theme_variables": theme_variables,
"library_links": theme_variables.get("library_links", []),
"version": version,
"date_info": {
"paths_to_skip": ["generated/", "index"],
},
}
napoleon_use_ivar = True
templates_path = [
"_templates",
os.path.join(os.path.dirname(pytorch_sphinx_theme2.__file__), "templates"),
]
autosummary_filename_map = {
"torch.nn.utils.prune.identity": "torch.nn.utils.prune.identity_function",
"torch.nn.utils.prune.Identity": "torch.nn.utils.prune.Identity_class",
"torch.optim.adamw.adamw": "torch.optim.adamw.adamw_function",
"torch.optim.adamw.AdamW": "torch.optim.adamw.AdamW_class",
"torch.optim.asgd.asgd": "torch.optim.asgd.asgd_function",
"torch.optim.asgd.ASGD": "torch.optim.asgd.ASGD_class",
"torch.optim.nadam.nadam": "torch.optim.nadam.nadam_function",
"torch.optim.nadam.NAdam": "torch.optim.nadam.NAdam_class",
"torch.optim.radam.radam": "torch.optim.radam.radam_function",
"torch.optim.radam.RAdam": "torch.optim.radam.RAdam_class",
"torch.optim.rmsprop.rmsprop": "torch.optim.rmsprop.rmsprop_function",
"torch.optim.rmsprop.RMSprop": "torch.optim.rmsprop.RMSprop_class",
"torch.optim.rprop.rprop": "torch.optim.rprop.rprop_function",
"torch.optim.rprop.Rprop": "torch.optim.rprop.Rprop_class",
"torch.optim.sgd.sgd": "torch.optim.sgd.sgd_function",
"torch.optim.sgd.SGD": "torch.optim.sgd.SGD_class",
"torch.optim.adadelta.adadelta": "torch.optim.adadelta.adadelta_function",
"torch.optim.adadelta.Adadelta": "torch.optim.adadelta.Adadelta_class",
"torch.optim.adagrad.adagrad": "torch.optim.adagrad.adagrad_function",
"torch.optim.adagrad.Adagrad": "torch.optim.adagrad.Adagrad_class",
"torch.optim.adam.adam": "torch.optim.adam.adam_function",
"torch.optim.adam.Adam": "torch.optim.adam.Adam_class",
"torch.optim.adamax.adamax": "torch.optim.adamax.adamax_function",
"torch.optim.adamax.Adamax": "torch.optim.adamax.Adamax_class",
"torch.mtia.stream": "torch.mtia.stream_function",
"torch.mtia.Stream": "torch.mtia.Stream_class",
"torch.cpu.stream": "torch.cpu.stream_function",
"torch.cpu.Stream": "torch.cpu.Stream_class",
"torch.cuda.stream": "torch.cuda.stream_function",
"torch.cuda.Stream": "torch.cuda.Stream_class",
"torch.mps.stream": "torch.mps.stream_function",
"torch.mps.Stream": "torch.mps.Stream_class",
"torch.xpu.stream": "torch.xpu.stream_function",
"torch.xpu.Stream": "torch.xpu.Stream_class",
}
coverage_ignore_functions = [
"main",
"run",
"read_vitals",
"set_vital",
"vitals_enabled",
"import_module",
"execWrapper",
"disable_global_flags",
"flags_frozen",
"DistributedDataParallelCPU",
"burn_in_info",
"get_info_and_burn_skeleton",
"get_storage_info",
"hierarchical_pickle",
"autocast_decorator",
"apply_permutation",
"pack_weight_bias",
"get_quantized_weight",
"get_matching_subgraph_pairs",
"add_loggers_to_model",
"create_a_shadows_b",
"add_op_to_sets_of_related_ops",
"get_base_name_for_op",
"get_base_name_to_sets_of_related_ops",
"get_node_type_to_io_type_map",
"get_unmatchable_types_map",
"create_add_loggers_graph",
"create_n_transformed_and_logged_copies_of_subgraph",
"create_one_transformed_and_logged_copy_of_subgraph",
"create_results_comparison",
"create_submodule_from_subgraph",
"extract_weight_comparison",
"group_results_by_subgraph",
"print_n_shadows_summary",
"end_node_matches_reversed_fusion",
"get_reversed_fusions",
"get_type_a_related_to_b",
"get_arg_indices_of_inputs_to_log",
"get_node_first_input_and_output_type",
"get_node_input_qparams",
"get_normalized_nth_input",
"get_number_of_non_param_args",
"get_target_type_str",
"maybe_add_missing_fqns",
"maybe_dequantize_first_two_tensor_args_and_handle_tuples",
"op_type_supports_shadowing",
"rekey_logger_info_on_node_name_of_model",
"return_first_non_observer_node",
"extract_weight_from_node",
"get_conv_fun_weight",
"get_conv_mod_weight",
"get_linear_fun_weight",
"get_linear_mod_weight",
"get_lstm_mod_weights",
"get_lstm_weight",
"get_op_to_type_to_weight_extraction_fn",
"get_qconv_fun_weight",
"get_qlinear_fun_weight",
"get_qlstm_weight",
"mod_0_weight_detach",
"mod_weight_bias_0",
"mod_weight_detach",
"fqn_to_module",
"get_arg_info_from_tensor_fqn",
"module_contains_param",
"module_to_fqn",
"swap_module",
"get_native_backend_config",
"get_native_backend_config_dict",
"get_test_only_legacy_native_backend_config",
"get_test_only_legacy_native_backend_config_dict",
"get_qnnpack_backend_config",
"get_tensorrt_backend_config",
"get_tensorrt_backend_config_dict",
"get_x86_backend_config",
"fuse_known_modules",
"fuse_modules_qat",
"fuse_conv_bn",
"fuse_conv_bn_relu",
"fuse_convtranspose_bn",
"fuse_linear_bn",
"get_fuser_method",
"get_fuser_method_new",
"convert",
"convert_custom_module",
"convert_standalone_module",
"convert_weighted_module",
"fuse",
"lower_to_fbgemm",
"lower_to_qnnpack",
"get_default_fusion_patterns",
"get_default_output_activation_post_process_map",
"get_default_quant_patterns",
"insert_observers_for_model",
"prepare",
"propagate_dtypes_for_known_nodes",
"bfs_trace_with_node_process",
"find_sequential_partitions",
"get_equivalent_types",
"update_equivalent_types_dict",
"prepare",
"reference_representation_rewrite",
"fold_bn_weights_into_conv_node",
"remove_tensor_overload_for_qdq_ops",
"get_default_qat_qconfig_dict",
"get_default_qconfig_dict",
"get_default_custom_config_dict",
"convert_pt2e",
"prepare_pt2e",
"prepare_qat_pt2e",
"get_embedding_operators_config",
"get_bias_qspec",
"get_input_act_qspec",
"get_output_act_qspec",
"get_weight_qspec",
"propagate_annotation",
"register_annotator",
"activation_dtype",
"check_node",
"has_no_children_ignoring_parametrizations",
"is_per_channel",
"is_per_tensor",
"op_is_int8_dynamically_quantized",
"to_underlying_dtype",
"weight_dtype",
"weight_is_quantized",
"weight_is_statically_quantized",
"get_cudnn_mode",
"init_dropout_state",
"custom_bwd",
"custom_fwd",
"amp_definitely_not_available",
"all_gather",
"all_reduce",
"broadcast",
"init_rank",
"reduce",
"reduce_scatter",
"unique_id",
"init",
"find_state_dict_object",
"find_tensor_shard",
"isend",
"monitored_barrier",
"new_group",
"new_subgroups",
"new_subgroups_by_enumeration",
"recv",
"reduce",
"reduce_scatter",
"all_gather_into_tensor",
"gather_into_tensor",
"reduce_scatter_tensor",
"scatter",
"scatter_object_list",
"send",
"set_timeout",
"supports_complex",
"get_logging_handler",
"configure",
"getStream",
"get_elapsed_time_ms",
"prof",
"profile",
"publish_metric",
"put_metric",
"get_std_cm",
"to_map",
"get_error_handler",
"get_libc",
"redirect",
"tail_logfile",
"get_method_name",
"create_rdzv_handler",
"find_free_port",
"stop_etcd",
"cas_delay",
"create_rdzv_handler",
"parse_rendezvous_endpoint",
"configure",
"expires",
"get_socket_with_port",
"create_c10d_store",
"get_socket_with_port",
"barrier",
"get_all",
"synchronize",
"store_timeout",
"all_to_all",
"all_to_all_single",
"get_arg_return_types_from_interface",
"instantiate_non_scriptable_remote_module_template",
"instantiate_scriptable_remote_module_template",
"get_remote_module_template",
"as_functional_optim",
"rendezvous",
"method_factory",
"new_method",
"remote",
"rpc_async",
"rpc_sync",
"shutdown",
"construct_rpc_backend_options",
"init_backend",
"deserialize",
"serialize",
"get_CSE_banned_ops",
"get_tensor_meta",
"split_module",
"split_module_simple",
"getattr_recursive",
"get_acc_ops_name",
"get_node_target",
"legalize_graph",
"fuse_by_partitions",
"insert_subgm",
"assert_fn",
"format_stack",
"get_current_meta",
"has_preserved_node_meta",
"preserve_node_meta",
"reset_grad_fn_seq_nr",
"set_current_meta",
"set_current_replay_node",
"set_grad_fn_seq_nr",
"set_stack_trace",
"get_current_replay_node",
"wrap_key",
"wrapper_and_args_for_make_fx",
"wrap_node",
"ann_to_type",
"check_fn",
"get_enum_value_type",
"get_param_names",
"get_signature",
"get_type_line",
"is_function_or_method",
"is_tensor",
"is_vararg",
"parse_type_line",
"split_type_line",
"try_ann_to_type",
"try_real_annotations",
"build_class_def",
"build_def",
"build_ignore_context_manager",
"build_param",
"build_param_list",
"build_stmts",
"build_withitems",
"find_before",
"get_class_assigns",
"get_class_properties",
"get_default_args",
"get_default_args_for_class",
"get_jit_class_def",
"get_jit_def",
"is_reserved_name",
"is_torch_jit_ignore_context_manager",
"format_bytecode",
"generate_upgraders_bytecode",
"apply_permutation",
"quantize_linear_modules",
"quantize_rnn_cell_modules",
"quantize_rnn_modules",
"as_masked_tensor",
"masked_tensor",
"clean_worker",
"fd_id",
"init_reductions",
"rebuild_cuda_tensor",
"rebuild_meta_tensor",
"rebuild_event",
"rebuild_nested_tensor",
"rebuild_sparse_coo_tensor",
"rebuild_sparse_compressed_tensor",
"rebuild_storage_empty",
"rebuild_storage_fd",
"rebuild_storage_filename",
"rebuild_tensor",
"rebuild_typed_storage",
"rebuild_typed_storage_child",
"reduce_storage",
"reduce_tensor",
"reduce_typed_storage",
"reduce_typed_storage_child",
"storage_from_cache",
"start_processes",
"adaptive_max_pool1d_with_indices",
"adaptive_max_pool2d_with_indices",
"adaptive_max_pool3d_with_indices",
"assert_int_or_pair",
"fractional_max_pool2d_with_indices",
"fractional_max_pool3d_with_indices",
"max_pool1d_with_indices",
"max_pool2d_with_indices",
"max_pool3d_with_indices",
"multi_head_attention_forward",
"conv1d_input",
"conv1d_weight",
"conv2d_input",
"conv2d_weight",
"conv3d_input",
"conv3d_weight",
"constant",
"dirac",
"eye",
"kaiming_normal",
"kaiming_uniform",
"normal",
"orthogonal",
"sparse",
"uniform",
"xavier_normal",
"xavier_uniform",
"apply_permutation",
"broadcast",
"broadcast_coalesced",
"gather",
"reduce_add",
"reduce_add_coalesced",
"scatter",
"data_parallel",
"get_a_var",
"parallel_apply",
"replicate",
"gather",
"is_namedtuple",
"scatter",
"scatter_kwargs",
"bind",
"reshape_from_tensor_shape",
"shape_as_tensor",
"add",
"avg_pool2d",
"cat",
"conv2d",
"conv2d_relu",
"conv_prepack",
"dequantize",
"linear",
"linear_prepack",
"max_pool2d",
"nchw2nhwc",
"nhwc2nchw",
"quantize_per_tensor",
"register_quantized_ops",
"relu",
"reshape",
"sigmoid",
"slice",
"upsample_nearest2d",
"args_have_same_dtype",
"check_training_mode",
"dequantize_helper",
"is_complex_value",
"quantize_helper",
"quantized_args",
"requantize_bias_helper",
"dequantize",
"div",
"embedding_bag",
"fake_quantize_per_tensor_affine",
"flip",
"fmod",
"isfinite",
"isinf",
"nan_to_num",
"quantize_per_tensor",
"quantized_add",
"quantized_add_relu",
"quantized_cat",
"quantized_conv1d",
"quantized_conv1d_relu",
"quantized_conv2d",
"quantized_conv2d_relu",
"quantized_conv3d",
"quantized_conv3d_relu",
"quantized_conv_transpose1d",
"quantized_conv_transpose2d",
"quantized_conv_transpose3d",
"quantized_group_norm",
"quantized_hardswish",
"quantized_instance_norm",
"quantized_layer_norm",
"quantized_leaky_relu",
"quantized_linear",
"quantized_linear_relu",
"quantized_mul",
"quantized_sigmoid",
"slice",
"sort",
"topk",
"Delete",
"add",
"append",
"arange",
"argsort",
"atleast_1d",
"atleast_2d",
"atleast_3d",
"cat",
"chunk",
"clamp",
"clamp_max",
"clamp_min",
"constant_pad_nd",
"cumsum",
"embedding_bag",
"embedding_renorm",
"flatten",
"gather",
"hardtanh",
"hstack",
"im2col",
"index",
"index_copy",
"index_fill",
"index_put",
"insert",
"linalg_det",
"linalg_vector_norm",
"logdet",
"masked_scatter",
"masked_select",
"mm",
"narrow",
"normal",
"pad",
"pixel_shuffle",
"pop",
"prim_constant_chunk",
"reflection_pad",
"relu6",
"remainder",
"replication_pad",
"round",
"scatter",
"select",
"size",
"sort",
"split",
"split_with_sizes",
"squeeze",
"stack",
"topk",
"unbind",
"unique_dim",
"unsqueeze",
"vstack",
"argmax",
"argmin",
"binary_cross_entropy_with_logits",
"celu",
"cross_entropy_loss",
"dropout",
"einsum",
"ge",
"le",
"native_dropout",
"nll_loss",
"nll_loss2d",
"nll_loss_nd",
"outer",
"pow",
"tensordot",
"unfold",
"diagonal",
"fake_quantize_per_channel_affine",
"fake_quantize_per_tensor_affine",
"frobenius_norm",
"log_softmax",
"nonzero_numpy",
"quantized_conv1d",
"quantized_conv1d_relu",
"quantized_conv2d",
"quantized_conv2d_relu",
"quantized_conv3d",
"quantized_conv3d_relu",
"quantized_conv_transpose1d",
"quantized_conv_transpose2d",
"quantized_conv_transpose3d",
"quantized_linear",
"quantized_linear_relu",
"repeat_interleave",
"softmax",
"split",
"split_with_sizes",
"tensor_split",
"tile",
"unbind",
"unflatten",
"unsafe_chunk",
"unsafe_split",
"unsafe_split_with_sizes",
"where",
"batch_norm",
"hardswish",
"quantized_hardswish",
"reshape",
"scaled_dot_product_attention",
"tril",
"triu",
"aten__is_",
"aten__isnot_",
"bernoulli",
"prim_unchecked_cast",
"grid_sampler",
"scatter_add",
"scatter_reduce",
"layer_norm",
"stft",
"col2im",
"max",
"min",
"dim",
"export",
"check_export_model_diff",
"verify",
"verify_aten_graph",
"enable_reentrant_dispatch",
"pytree_register_structseq",
"load",
"location_tag",
"mkdtemp",
"normalize_storage_type",
"save",
"storage_to_tensor_type",
"validate_cuda_device",
"validate_hpu_device",
"generate_methods_for_privateuse1_backend",
"rename_privateuse1_backend",
"power_range",
"ordered_unique",
"set_torch_threads",
"unit_to_english",
"optional_min",
"bench_loop",
"compile_callgrind_template",
"compile_timeit_template",
"get_compat_bindings",
"dtype_size",
"timer",
"wrapper_singleton",
"augment_many_model_functions_with_bundled_inputs",
"augment_model_with_bundled_inputs",
"bundle_inputs",
"bundle_large_tensor",
"bundle_randn",
"check_backward_validity",
"detach_variable",
"get_device_states",
"noop_context_fn",
"check_compiler_is_gcc",
"check_compiler_ok_for_platform",
"get_cxx_compiler",
"get_default_build_root",
"library_paths",
"remove_extension_h_precompiler_headers",
"worker_init_fn",
"concat",
"create_dataframe",
"get_columns",
"get_df_wrapper",
"get_item",
"get_len",
"is_column",
"is_dataframe",
"iterate",
"set_df_wrapper",
"disable_capture",
"get_val",
"extract_class_name",
"extract_method_name",
"find_file_paths",
"gen_from_template",
"get_method_definitions",
"materialize_lines",
"parse_datapipe_file",
"parse_datapipe_files",
"process_signature",
"split_outside_bracket",
"default_fn",
"get_file_binaries_from_pathnames",
"get_file_pathnames_from_root",
"match_masks",
"validate_pathname_binary_tuple",
"apply_random_seed",
"apply_sharding",
"apply_shuffle_seed",
"apply_shuffle_settings",
"get_all_graph_pipes",
"warn_if_has_hooks",
"extract_ir",
"load_graph_and_inputs",
"make_tensor_from_type",
"no_fuser",
"time_cpu",
"time_cuda",
"to_mkldnn",
"audio",
"compute_curve",
"custom_scalars",
"draw_boxes",
"half_to_int",
"histogram",
"histogram_raw",
"hparams",
"image",
"image_boxes",
"int_to_half",
"make_histogram",
"make_image",
"make_video",
"mesh",
"pr_curve",
"pr_curve_raw",
"scalar",
"tensor_proto",
"text",
"video",
]
coverage_ignore_classes = [
"FatalError",
"QUInt2x4Storage",
"Size",
"Storage",
"Stream",
"Tensor",
"finfo",
"iinfo",
"qscheme",
"AggregationType",
"AliasDb",
"AnyType",
"Argument",
"ArgumentSpec",
"AwaitType",
"BenchmarkConfig",
"BenchmarkExecutionStats",
"Block",
"BoolType",
"BufferDict",
"CallStack",
"Capsule",
"ClassType",
"Code",
"CompleteArgumentSpec",
"ComplexType",
"ConcreteModuleType",
"ConcreteModuleTypeBuilder",
"DeepCopyMemoTable",
"DeserializationStorageContext",
"DeviceObjType",
"DictType",
"DispatchKey",
"DispatchKeySet",
"EnumType",
"ExcludeDispatchKeyGuard",
"ExecutionPlan",
"FileCheck",
"FloatType",
"FunctionSchema",
"Gradient",
"Graph",
"GraphExecutorState",
"IODescriptor",
"InferredType",
"IntType",
"InterfaceType",
"ListType",
"LockingLogger",
"MobileOptimizerType",
"ModuleDict",
"Node",
"NoneType",
"NoopLogger",
"NumberType",
"OperatorInfo",
"OptionalType",
"ParameterDict",
"PyObjectType",
"PyTorchFileReader",
"PyTorchFileWriter",
"RRefType",
"ScriptClass",
"ScriptClassFunction",
"ScriptDict",
"ScriptDictIterator",
"ScriptDictKeyIterator",
"ScriptList",
"ScriptListIterator",
"ScriptMethod",
"ScriptModule",
"ScriptModuleSerializer",
"ScriptObject",
"ScriptObjectProperty",
"SerializationStorageContext",
"StaticModule",
"StringType",
"SymIntType",
"SymBoolType",
"ThroughputBenchmark",
"TracingState",
"TupleType",
"Type",
"UnionType",
"Use",
"Value",
"BFloat16Storage",
"BFloat16Tensor",
"BoolStorage",
"BoolTensor",
"ByteStorage",
"ByteTensor",
"CharStorage",
"CharTensor",
"ComplexDoubleStorage",
"ComplexFloatStorage",
"CudaError",
"DeferredCudaCallError",
"DoubleStorage",
"DoubleTensor",
"FloatStorage",
"FloatTensor",
"HalfStorage",
"HalfTensor",
"IntStorage",
"IntTensor",
"LongStorage",
"LongTensor",
"ShortStorage",
"ShortTensor",
"cudaStatus",
"Access",
"AccessType",
"Await",
"CUDASanitizer",
"CUDASanitizerDispatchMode",
"CUDASanitizerErrors",
"EventHandler",
"SynchronizationError",
"UnsynchronizedAccessError",
"ChildFailedError",
"ProcessFailure",
"cat",
"greater_than",
"greater_than_eq",
"half_open_interval",
"independent",
"integer_interval",
"interval",
"less_than",
"multinomial",
"stack",
"AffineTransform",
"CatTransform",
"ComposeTransform",
"CorrCholeskyTransform",
"CumulativeDistributionTransform",
"ExpTransform",
"IndependentTransform",
"PowerTransform",
"ReshapeTransform",
"SigmoidTransform",
"SoftmaxTransform",
"SoftplusTransform",
"StackTransform",
"StickBreakingTransform",
"TanhTransform",
"Transform",
"CompilationUnit",
"Error",
"Future",
"ScriptFunction",
"CheckerError",
"ExportTypes",
"ContextProp",
"PropModule",
"cuBLASModule",
"cuFFTPlanCache",
"cuFFTPlanCacheAttrContextProp",
"cuFFTPlanCacheManager",
"DDPCommHookType",
"LiteScriptModule",
"DeQuantize",
"Quantize",
"Warning",
"ELU",
"Hardswish",
"LeakyReLU",
"MultiheadAttention",
"PReLU",
"ReLU6",
"Sigmoid",
"Softmax",
"BatchNorm2d",
"BatchNorm3d",
"Conv1d",
"Conv2d",
"Conv3d",
"ConvTranspose1d",
"ConvTranspose2d",
"ConvTranspose3d",
"Dropout",
"Embedding",
"EmbeddingBag",
"EmbeddingPackedParams",
"FXFloatFunctional",
"FloatFunctional",
"QFunctional",
"Linear",
"LinearPackedParams",
"GroupNorm",
"InstanceNorm1d",
"InstanceNorm2d",
"InstanceNorm3d",
"LayerNorm",
"LSTM",
"WeightedQuantizedModule",
"Conv1d",
"Conv2d",
"Conv3d",
"ConvTranspose1d",
"ConvTranspose2d",
"ConvTranspose3d",
"Linear",
"GRU",
"GRUCell",
"LSTM",
"LSTMCell",
"RNNBase",
"RNNCell",
"RNNCellBase",
"Embedding",
"EmbeddingBag",
"ReferenceQuantizedModule",
"Linear",
"Linear",
"LinearPackedParams",
"LinearBlockSparsePattern",
"SubgraphTypeRelationship",
"OutputProp",
"NSSingleResultValuesType",
"NSSubgraph",
"QConfigMultiMapping",
"BaseScheduler",
"CubicSL",
"LambdaSL",
"BaseSparsifier",
"NearlyDiagonalSparsifier",
"FakeSparsity",
"WeightNormSparsifier",
"BackendConfig",
"BackendPatternConfig",
"DTypeConfig",
"FakeQuantize",
"FakeQuantizeBase",
"FixedQParamsFakeQuantize",
"FusedMovingAvgObsFakeQuantize",
"DefaultFuseHandler",
"FuseHandler",
"FusedGraphModule",
"ObservedGraphModule",
"ObservedStandaloneGraphModule",
"BatchNormQuantizeHandler",
"BinaryOpQuantizeHandler",
"CatQuantizeHandler",
"ConvReluQuantizeHandler",
"CopyNodeQuantizeHandler",
"CustomModuleQuantizeHandler",
"DefaultNodeQuantizeHandler",
"EmbeddingQuantizeHandler",
"FixedQParamsOpQuantizeHandler",
"GeneralTensorShapeOpQuantizeHandler",
"LinearReLUQuantizeHandler",
"RNNDynamicQuantizeHandler",
"StandaloneModuleQuantizeHandler",
"QuantizationTracer",
"ScopeContextManager",
"ObservedGraphModuleAttrs",
"FixedQParamsObserver",
"HistogramObserver",
"MinMaxObserver",
"MovingAverageMinMaxObserver",
"MovingAveragePerChannelMinMaxObserver",
"NoopObserver",
"ObserverBase",
"PerChannelMinMaxObserver",
"PlaceholderObserver",
"RecordingObserver",
"ReuseInputObserver",
"UniformQuantizationObserverBase",
"default_debug_observer",
"default_placeholder_observer",
"default_reuse_input_observer",
"QConfigDynamic",
"QuantType",
"DeQuantStub",
"QuantStub",
"QuantWrapper",
"MatchAllNode",
"Unserializable",
"GradScaler",
"OptState",
"PostLocalSGDState",
"PowerSGDState",
"Join",
"JoinHook",
"Joinable",
"ModelAverager",
"PeriodicModelAverager",
"HierarchicalModelAverager",
"check_env",
"env",
"DefaultLoadPlanner",
"DefaultSavePlanner",
"FileSystemReader",
"FileSystemWriter",
"HuggingFaceStorageReader",
"HuggingFaceStorageWriter",
"QuantizedHuggingFaceStorageReader",
"LoadPlanner",
"SavePlanner",
"DistributedStateDictOptions",
"SyncPayload",
"AllToAllOptions",
"AllreduceCoalescedOptions",
"AllreduceOptions",
"Backend",
"BackendConfig",
"BarrierOptions",
"BroadcastOptions",
"DebugLevel",
"GatherOptions",
"GroupMember",
"ProcessGroup",
"ProcessGroupGloo",
"ProcessGroupNCCL",
"ReduceOptions",
"ReduceScatterOptions",
"ScatterOptions",
"Work",
"group",
"ElasticAgent",
"RunResult",
"SimpleElasticAgent",
"WorkerSpec",
"Event",
"ConsoleMetricHandler",
"MetricHandler",
"MetricStream",
"MetricsConfig",
"NullMetricHandler",
"MultiprocessContext",
"PContext",
"RunProcsResult",
"SubprocessContext",
"SubprocessHandler",
"TailLog",
"RendezvousHandler",
"RendezvousHandlerRegistry",
"RendezvousParameters",
"DynamicRendezvousHandler",
"RendezvousSettings",
"EtcdRendezvous",
"EtcdRendezvousHandler",
"EtcdRendezvousRetryImmediately",
"EtcdRendezvousRetryableFailure",
"EtcdServer",
"StaticTCPRendezvous",
"RequestQueue",
"TimerClient",
"TimerServer",
"FileTimerClient",
"FileTimerRequest",
"FileTimerServer",
"LocalTimerClient",
"LocalTimerServer",
"MultiprocessingRequestQueue",
"macros",
"CyclingIterator",
"ElasticDistributedSampler",
"FullyShardedDataParallel",
"LaunchConfig",
"elastic_launch",
"DistributedOptimizer",
"PostLocalSGDOptimizer",
"ZeroRedundancyOptimizer",
"AllGatherStates",
"RRef",
"BackendValue",
"PythonUDF",
"RPCExecMode",
"RemoteException",
"RRefProxy",
"DTensorExtensions",
"LogisticNormal",
"OneHotCategoricalStraightThrough",
"ExpRelaxedCategorical",
"lazy_property",
"UnflattenedModule",
"ConstantArgument",
"ExportedProgram",
"DAG",
"DAGNode",
"PartitionResult",
"Partitioner",
"FoldedGraphModule",
"Refine",
"MetaAttribute",
"MetaDeviceAttribute",
"MetaProxy",
"MetaTracer",
"ApplyBroadcasting",
"BVar",
"BinConstraintD",
"BinConstraintT",
"BinaryConstraint",
"CalcConv",
"CalcMaxPool",
"CalcProduct",
"CanReshape",
"Conj",
"Constraint",
"DGreatestUpperBound",
"DVar",
"Disj",
"F",
"GetItem",
"GetItemTensor",
"IndexSelect",
"Prod",
"T",
"TGreatestUpperBound",
"TVar",
"Transpose",
"ConstraintGenerator",
"NormalizeArgs",
"NormalizeOperators",
"MklSubgraph",
"UnionFind",
"Device",
"Partition",
"PartitionLatency",
"PartitionMode",
"PartitionerConfig",
"DecompositionInterpreter",
"PreDispatchTorchFunctionMode",
"ProxySymDispatchMode",
"ProxyTorchDispatchMode",
"PythonKeyTracer",
"FakeTensorMeta",
"NotEqualError",
"ShapeEnvEvent",
"Equality",
"AST_Rewriter",
"RewritingTracer",
"AnnotateTypesWithSchema",
"SymNode",
"Constraint",
"ConstraintViolationError",
"DynamicDimConstraintPrinter",
"GuardOnDataDependentSymNode",
"PendingUnbackedSymbolNotFound",
"LoggingShapeGuardPrinter",
"SymExprPrinter",
"RelaxedUnspecConstraint",
"RuntimeAssert",
"ShapeGuardPrinter",
"ShapeGuardPythonPrinter",
"SymDispatchMode",
"SymbolicContext",
"Dispatcher",
"VarDispatcher",
"AmbiguityWarning",
"Dispatcher",
"MDNotImplementedError",
"MethodDispatcher",
"Variadic",
"VariadicSignatureMeta",
"VariadicSignatureType",
"Var",
"BisectValidationException",
"PopulateValidator",
"SympyToZ3",
"ValidationException",
"PythonCode",
"immutable_dict",
"immutable_list",
"Interpreter",
"ArgsKwargsPair",
"CudaGraphsSupport",
"CSEPass",
"FakeTensorProp",
"FxGraphDrawer",
"size_bytes",
"CapabilityBasedPartitioner",
"Partition",
"PassBase",
"PassResult",
"PassManager",
"FxNetMinimizerBadModuleError",
"FxNetMinimizerResultMismatchError",
"FxNetMinimizerRunFuncError",
"OpSupports",
"OperatorSupport",
"OperatorSupportBase",
"PassManager",
"ShapeProp",
"Partition",
"Component",
"FxNetAccNodesFinder",
"FxNetSplitterInternalError",
"SplitResult",
"Subgraph",
"TestPassManager",
"FxNetAccFusionsFinder",
"HolderModule",
"InternalMatch",
"SubgraphMatcher",
"SourcePartition",
"Attribute",
"ParameterProxy",
"Proxy",
"Scope",
"ScopeContextManager",
"TraceError",
"TracerBase",
"Match",
"ReplacedPatterns",
"EvalEnv",
"Module",
"Builder",
"ExprBuilder",
"FrontendError",
"FrontendTypeError",
"NotSupportedError",
"StmtBuilder",
"UnsupportedNodeError",
"WithItemBuilder",
"MaskedTensor",
"Pool",
"ConnectionWrapper",
"Queue",
"SimpleQueue",
"SharedCache",
"ProcessContext",
"ProcessException",
"ProcessExitedException",
"ProcessRaisedException",
"SpawnContext",
"ModuleWrapper",
"OrderedDictWrapper",
"Container",
"NonDynamicallyQuantizableLinear",
"Module",
"NLLLoss2d",
"CrossMapLRN2d",
"DataParallel",
"DistributedDataParallel",
"UninitializedTensorMixin",
"ParametrizationList",
"CustomFromMask",
"Identity",
"L1Unstructured",
"RandomUnstructured",
"PackedSequence",
"PackedSequence_",
"SpectralNorm",
"SpectralNormLoadStateDictPreHook",
"SpectralNormStateDictHook",
"WeightNorm",
"OnnxExporterError",
"OnnxExporterWarning",
"SymbolicValueError",
"UnsupportedOperatorError",
"OnnxBackend",
"OnnxTestCaseRepro",
"Optimizer",
"BaseTorchFunctionMode",
"TorchFunctionMode",
"Directory",
"GlobGroup",
"Importer",
"ObjMismatchError",
"ObjNotFoundError",
"OrderedImporter",
"PackageExporter",
"PackagingErrorReason",
"PackageImporter",
"EventMetadata",
"ExecutionTraceObserver",
"profile",
"aminmax",
"aminmax_out",
"cummax",
"cummax_out",
"cummin",
"cummin_out",
"frexp",
"frexp_out",
"geqrf",
"geqrf_out",
"histogram",
"histogram_out",
"histogramdd",
"kthvalue",
"kthvalue_out",
"linalg_cholesky_ex",
"linalg_cholesky_ex_out",
"linalg_eig",
"linalg_eig_out",
"linalg_eigh",
"linalg_eigh_out",
"linalg_inv_ex",
"linalg_inv_ex_out",
"linalg_ldl_factor",
"linalg_ldl_factor_ex",
"linalg_ldl_factor_ex_out",
"linalg_ldl_factor_out",
"linalg_lstsq",
"linalg_lstsq_out",
"linalg_lu",
"linalg_lu_factor",
"linalg_lu_factor_ex",
"linalg_lu_factor_ex_out",
"linalg_lu_factor_out",
"linalg_lu_out",
"linalg_polar",
"linalg_polar_out",
"linalg_qr",
"linalg_qr_out",
"linalg_slogdet",
"linalg_slogdet_out",
"linalg_solve_ex",
"linalg_solve_ex_out",
"linalg_svd",
"linalg_svd_out",
"lu_unpack",
"lu_unpack_out",
"max",
"max_out",
"median",
"median_out",
"min",
"min_out",
"mode",
"mode_out",
"nanmedian",
"nanmedian_out",
"slogdet",
"slogdet_out",
"sort",
"sort_out",
"svd",
"svd_out",
"topk",
"topk_out",
"triangular_solve",
"triangular_solve_out",
"LoadEndianness",
"SourceChangeWarning",
"SparseSemiStructuredTensor",
"UntypedStorage",
"TorchVersion",
"SymBool",
"SymFloat",
"SymInt",
"FauxTorch",
"Benchmark",
"BinaryOpFuzzer",
"BinaryOpSparseFuzzer",
"UnaryOpSparseFuzzer",
"SpectralOpFuzzer",
"UnaryOpFuzzer",
"Measurement",
"TaskSpec",
"Colorize",
"Compare",
"Table",
"FuzzedParameter",
"FuzzedTensor",
"Fuzzer",
"ParameterAlias",
"FuzzedSparseTensor",
"CPPTimer",
"Language",
"Timer",
"CallgrindStats",
"CopyIfCallgrind",
"FunctionCount",
"FunctionCounts",
"GlobalsBridge",
"Serialization",
"InflatableArg",
"CheckpointError",
"CheckpointFunction",
"DefaultDeviceType",
"SystemEnv",
"BuildExtension",
"DataLoader",
"PandasWrapper",
"default_wrapper",
"Capture",
"CaptureA",
"CaptureAdd",
"CaptureCall",
"CaptureControl",
"CaptureDataFrame",
"CaptureDataFrameWithDataPipeOps",
"CaptureF",
"CaptureGetAttr",
"CaptureGetItem",
"CaptureInitial",
"CaptureLikeMock",
"CaptureMul",
"CaptureSetItem",
"CaptureSub",
"CaptureVariable",
"CaptureVariableAssign",
"DataFrameTracedOps",
"DataFrameTracer",
"ConcatDataFramesPipe",
"DataFramesAsTuplesPipe",
"ExampleAggregateAsDataFrames",
"FilterDataFramesPipe",
"PerRowDataFramesPipe",
"ShuffleDataFramesPipe",
"DataChunkDF",
"DFIterDataPipe",
"DataChunk",
"IterDataPipe",
"MapDataPipe",
"CollatorIterDataPipe",
"MapperIterDataPipe",
"SamplerIterDataPipe",
"ShufflerIterDataPipe",
"ConcaterIterDataPipe",
"DemultiplexerIterDataPipe",
"ForkerIterDataPipe",
"MultiplexerIterDataPipe",
"ZipperIterDataPipe",
"FileListerIterDataPipe",
"FileOpenerIterDataPipe",
"BatcherIterDataPipe",
"GrouperIterDataPipe",
"UnBatcherIterDataPipe",
"FilterIterDataPipe",
"SHARDING_PRIORITIES",
"ShardingFilterIterDataPipe",
"IterableWrapperIterDataPipe",
"MapperMapDataPipe",
"ShufflerIterDataPipe",
"ConcaterMapDataPipe",
"ZipperMapDataPipe",
"BatcherMapDataPipe",
"SequenceWrapperMapDataPipe",
"ConcatDataset",
"DistributedSampler",
"DLDeviceType",
"FileBaton",
"CurrentState",
"GeneratedFileCleaner",
"HipifyResult",
"InputError",
"Trie",
"bcolors",
"BackwardHook",
"RemovableHandle",
"MkldnnBatchNorm",
"MkldnnConv1d",
"MkldnnConv2d",
"MkldnnConv3d",
"MkldnnLinear",
"MkldnnPrelu",
"LintCode",
"DumpUnpickler",
"FakeClass",
"FakeObject",
"FileWriter",
"SummaryWriter",
"ExecutionStats",
"WeakIdKeyDictionary",
"WeakIdRef",
"WeakTensorKeyDictionary",
]
source_suffix = ".rst"
master_doc = "index"
@functools.cache
def _add_docstr_source_lines(module_file):
pattern = re.compile(r"^([A-Za-z_]\w*)\s*=\s*_add_docstr\(")
source_lines = {}
try:
with open(module_file, encoding="utf-8") as f:
for lineno, line in enumerate(f, 1):
match = pattern.match(line)
if match is not None:
source_lines[match.group(1)] = lineno
except OSError:
return {}
return source_lines
def _find_add_docstr_source(module, fullname):
if "." in fullname or not re.match(r"^[A-Za-z_]\w*$", fullname):
return None
module_file = getattr(module, "__file__", None)
if module_file is None or not module_file.endswith(".py"):
return None
lineno = _add_docstr_source_lines(module_file).get(fullname)
if lineno is None:
return None
return module_file, lineno
def linkcode_resolve(domain, info):
if domain != "py":
return None
if not info["module"]:
return None
try:
module = __import__(info["module"], fromlist=[""])
except Exception:
return None
try:
obj = module
for part in info["fullname"].split("."):
obj = getattr(obj, part)
obj = inspect.unwrap(obj)
fn = inspect.getsourcefile(obj)
source, lineno = inspect.getsourcelines(obj)
except Exception:
resolved = _find_add_docstr_source(module, info["fullname"])
if resolved is None:
return None
fn, lineno = resolved
if RELEASE:
version_parts = torch_version.split(
"."
)
patch_version = (
version_parts[2].split("+")[0].split("a")[0]
)
version_path = f"v{version_parts[0]}.{version_parts[1]}.{patch_version}"
else:
version_path = torch.version.git_version
fn = os.path.relpath(fn, start=os.path.dirname(torch.__file__))
return (
f"https://github.com/pytorch/pytorch/blob/{version_path}/torch/{fn}#L{lineno}"
)
language = "en"
exclude_patterns = ["distributed/elastic/generated"]
pygments_style = "sphinx"
autodoc_inherit_docstrings = False
autodoc_typehints = "description"
autodoc_typehints_description_target = "documented_params"
autodoc_type_aliases = {
"_size_1_t": "int or tuple[int]",
"_size_2_t": "int or tuple[int, int]",
"_size_3_t": "int or tuple[int, int, int]",
"_size_4_t": "int or tuple[int, int, int, int]",
"_size_5_t": "int or tuple[int, int, int, int, int]",
"_size_6_t": "int or tuple[int, int, int, int, int, int]",
"_size_any_opt_t": "int or None or tuple",
"_size_2_opt_t": "int or None or 2-tuple",
"_size_3_opt_t": "int or None or 3-tuple",
"_ratio_2_t": "float or tuple[float, float]",
"_ratio_3_t": "float or tuple[float, float, float]",
"_ratio_any_t": "float or tuple",
"_tensor_list_t": "Tensor or tuple[Tensor]",
}
autodoc_docstring_signature = True
autodoc_default_options = {
"exclude-members": "from_bytes, to_bytes",
}
html_css_files = [
"css/jit.css",
"css/foreach.css",
"https://cdn.jsdelivr.net/npm/katex@0.10.0-beta/dist/katex.min.css",
]
from sphinx.ext.coverage import CoverageBuilder
ignore_duplicated_modules = {
"torch.nn.utils.weight_norm",
"torch.nn.utils.spectral_norm",
"torch.nn.parallel.data_parallel",
"torch.ao.quantization.quantize",
}
def coverage_post_process(app, exception):
if exception is not None:
return
if not isinstance(app.builder, CoverageBuilder):
return
if not torch.distributed.is_available():
raise RuntimeError(
"The coverage tool cannot run with a version "
"of PyTorch that was built with USE_DISTRIBUTED=0 "
"as this module's API changes."
)
modules = app.env.domaindata["py"]["modules"]
def is_not_internal(modname):
split_name = modname.split(".")
for name in split_name:
if name[0] == "_":
return False
return True
objects = app.env.domaindata["py"]["objects"]
ignore_names = set(app.config.coverage_ignore_functions) | set(
app.config.coverage_ignore_classes
)
ignore_names |= {"ErrorReport", "FutureType", "StreamObjType", "unify_type_list"}
undocumented = []
for mod_name in modules:
if not is_not_internal(mod_name):
continue
try:
mod = __import__(mod_name, fromlist=["__all__"])
except ImportError:
continue
for name in getattr(mod, "__all__", []):
if name.startswith("_") or name in ignore_names:
continue
full_name = f"{mod_name}.{name}"
obj = getattr(mod, name, None)
if obj is None or not callable(obj):
continue
if getattr(obj, "__module__", mod_name) != mod_name:
continue
if full_name in objects:
continue
parts = mod_name.split(".")
if any(
f"{'.'.join(parts[:i])}.{name}" in objects for i in range(1, len(parts))
):
continue
undocumented.append(full_name)
if undocumented:
items = "\n".join(f" - {u}" for u in sorted(undocumented))
print(
f"\nThe following public APIs are in __all__ but not documented:\n{items}\n"
"Either add them to the appropriate .rst/.md doc file or "
"remove from __all__."
)
sys.exit(1)
missing = set()
if "torch" not in modules:
missing.add("torch")
for _, modname, _ in pkgutil.walk_packages(
path=torch.__path__, prefix=torch.__name__ + "."
):
if is_not_internal(modname):
if modname not in modules and modname not in ignore_duplicated_modules:
missing.add(modname)
output = []
if missing:
mods = ", ".join(missing)
output.append(
f"\nYou added the following module(s) to the PyTorch namespace '{mods}' "
"but they have no corresponding entry in a doc .rst file. You should "
"either make sure that the .rst file that contains the module's documentation "
"properly contains either '.. automodule:: mod_name' (if you do not want "
"the paragraph added by the automodule, you can simply use '.. py:module:: mod_name') "
" or make the module private (by appending an '_' at the beginning of its name)."
)
output_file = path.join(app.outdir, "python.txt")
if output:
with open(output_file, "a") as f:
f.writelines(output)
def process_docstring(app, what_, name, obj, options, lines):
"""
Custom process to transform docstring lines Remove "Ignore" blocks
Args:
app (sphinx.application.Sphinx): the Sphinx application object
what (str):
the type of the object which the docstring belongs to (one of
"module", "class", "exception", "function", "method", "attribute")
name (str): the fully qualified name of the object
obj: the object itself
options: the options given to the directive: an object with
attributes inherited_members, undoc_members, show_inheritance
and noindex that are true if the flag option of same name was
given to the auto directive
lines (List[str]): the lines of the docstring, see above
References:
https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html
"""
import re
remove_directives = [
re.compile(r"\s*>>>\s*#\s*x?doctest:\s*.*"),
re.compile(r"\s*>>>\s*#\s*x?doc:\s*.*"),
re.compile(r"\s*>>>.*#\s*docs:\s*hide\s*$"),
]
filtered_lines = [
line for line in lines if not any(pat.match(line) for pat in remove_directives)
]
lines[:] = filtered_lines
if lines and lines[-1].strip():
lines.append("")
def _foreach_annotation_name(annotation):
parsed_aliases = {
"_TensorList": "TensorList",
"_ScalarList[_ScalarT]": "ScalarList",
"_Scalar": "Scalar",
"Tensor": "Tensor",
}
if isinstance(annotation, str):
return parsed_aliases.get(annotation, annotation)
aliases = (
(torch.foreach._TensorList, "TensorList"),
(torch.foreach._ScalarList, "ScalarList"),
(torch.foreach._Scalar, "Scalar"),
(torch.Tensor, "Tensor"),
)
return next((name for alias, name in aliases if annotation == alias), annotation)
class ForeachFunctionDocumenter(FunctionDocumenter):
def format_signature(self, **kwargs):
if not self.fullname.startswith("torch.foreach."):
return super().format_signature(**kwargs)
overloads = (
self.analyzer.overloads.get(".".join(self.objpath), ())
if self.analyzer is not None
else ()
)
actual = inspect.signature(self.object)
if overloads:
signatures = [
self.merge_default_value(actual, overload) for overload in overloads
]
else:
signatures = [inspect.signature(self.object.__wrapped__, eval_str=True)]
formatted_signatures = []
for signature in signatures:
parameters = [
parameter.replace(
annotation=_foreach_annotation_name(parameter.annotation)
)
for parameter in signature.parameters.values()
]
returns_input_container = signature.return_annotation in (
"_TensorList",
torch.foreach._TensorList,
)
return_annotation = "tuple[Tensor, ...]"
if returns_input_container:
return_annotation += " | list[Tensor]"
signature = signature.replace(
parameters=parameters, return_annotation=return_annotation
)
if self.config.autodoc_typehints_format == "short":
kwargs.setdefault("unqualified_typehints", True)
formatted_signatures.append(stringify_signature(signature, **kwargs))
return "\n".join(formatted_signatures)
def add_directive_header(self, sig):
super().add_directive_header(sig)
if self.fullname.startswith("torch.foreach."):
self.add_line(" :single-line-parameter-list:", self.get_sourcename())
def setup(app):
app.add_autodocumenter(ForeachFunctionDocumenter, override=True)
app.connect("build-finished", coverage_post_process)
app.connect("autodoc-process-docstring", process_docstring)
app.connect("html-page-context", hide_edit_button_for_pages)
app.config.add_last_updated = True
from sphinx.builders import Builder
_orig_read_serial = Builder._read_serial
def _serial_read_ignoring_nproc(self, docnames, nproc=1):
return _orig_read_serial(self, docnames)
Builder._read_parallel = _serial_read_ignoring_nproc
_fix_katex_server_race(app)
return {"version": "0.1", "parallel_read_safe": True}
def _fix_katex_server_race(app):
"""Retry on ConnectionRefusedError when connecting to the KaTeX server.
sphinxcontrib-katex 0.9.x starts a Node.js server and connects via Unix
socket. There's a race: Python sees the socket file (created by bind())
and calls connect() before Node.js has called listen(). On slow CI
machines this causes ConnectionRefusedError. Fix by retrying connect().
"""
try:
from sphinxcontrib.katex import KaTeXServer
except ImportError:
return
import socket as _socket
import time as _time
@classmethod
def _start_with_retry(cls, rundir, timeout):
from subprocess import PIPE, Popen
from sphinxcontrib.katex import ONE_MILLISECOND
socket_path = rundir / "katex.sock"
cmd = cls.build_command(socket=socket_path)
process = Popen(cmd, stdin=PIPE, stdout=PIPE, cwd=rundir)
startup_start = _time.monotonic()
while not socket_path.is_socket():
_time.sleep(ONE_MILLISECOND)
if _time.monotonic() - startup_start > timeout:
raise cls.timeout_error(timeout)
while True:
remaining = startup_start + timeout - _time.monotonic()
if remaining <= 0:
raise cls.timeout_error(timeout)
try:
sock = _socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM)
sock.settimeout(remaining)
sock.connect(str(socket_path))
break
except ConnectionRefusedError:
sock.close()
_time.sleep(ONE_MILLISECOND)
except TimeoutError:
sock.close()
raise cls.timeout_error(timeout)
return process, sock
KaTeXServer.start_server_process = _start_with_retry
def hide_edit_button_for_pages(app, pagename, templatename, context, doctree):
if pagename.startswith("generated/"):
context["theme_use_edit_page_button"] = False
context["theme_navigation_depth"] = 2
context["theme_collapse_navigation"] = "true"
from sphinx.writers import html, html5
def replace(Klass):
old_call = Klass.visit_reference
def visit_reference(self, node):
if "refuri" in node and "generated" in node.get("refuri"):
ref = node.get("refuri")
ref_anchor = ref.split("#")
if len(ref_anchor) > 1:
anchor = ref_anchor[1]
txt = node.parent.astext()
if txt == anchor or txt == anchor.split(".")[-1]:
self.body.append(f'<p id="{ref_anchor[1]}"/>')
return old_call(self, node)
Klass.visit_reference = visit_reference
replace(html.HTMLTranslator)
replace(html5.HTML5Translator)
htmlhelp_basename = "PyTorchdoc"
latex_engine = "lualatex"
latex_show_urls = "footnote"
latex_elements = {
"papersize": "letterpaper",
"pointsize": "10pt",
"tableofcontents": r"\pdfbookmark[0]{Contents}{toc}\tableofcontents",
"preamble": r"""
\usepackage{tocloft}
\setcounter{tocdepth}{3}
\setcounter{secnumdepth}{3}
% Fix table column widths
\renewenvironment{tabulary}{\begin{longtable}{p{0.3\linewidth}p{0.7\linewidth}}}{\end{longtable}}
% Ensure tables don't overflow
\AtBeginEnvironment{tabular}{\sloppy}
""",
"fncychap": r"\usepackage[Bjornstrup]{fncychap}",
"extraclassoptions": "oneside",
}
latex_documents = [
(
master_doc,
"pytorch.tex",
"PyTorch Documentation",
"Torch Contributors",
"manual",
),
]
latex_use_xindy = False
man_pages = [(master_doc, "PyTorch", "PyTorch Documentation", [author], 1)]
texinfo_documents = [
(
master_doc,
"PyTorch",
"PyTorch Documentation",
author,
"PyTorch",
"One line description of project.",
"Miscellaneous",
),
]
intersphinx_mapping = {
"python": ("https://docs.python.org/3", None),
"numpy": ("https://numpy.org/doc/stable", None),
}
import sphinx.ext.doctest
from docutils import nodes
from sphinx import addnodes
from sphinx.util.docfields import TypedField
doctest_test_doctest_blocks = ""
doctest_default_flags = sphinx.ext.doctest.doctest.ELLIPSIS
doctest_global_setup = """
import torch
try:
import torchvision
except ImportError:
torchvision = None
"""
def patched_make_field(self, types, domain, items, **kw):
def handle_item(fieldarg, content):
par = nodes.paragraph()
par += addnodes.literal_strong("", fieldarg)
if fieldarg in types:
par += nodes.Text(" (")
fieldtype = types.pop(fieldarg)
if len(fieldtype) == 1 and isinstance(fieldtype[0], nodes.Text):
typename = fieldtype[0].astext()
builtin_types = ["int", "long", "float", "bool", "type"]
for builtin_type in builtin_types:
pattern = rf"(?<![\w.]){builtin_type}(?![\w.])"
repl = f"python:{builtin_type}"
typename = re.sub(pattern, repl, typename)
par.extend(
self.make_xrefs(
self.typerolename,
domain,
typename,
addnodes.literal_emphasis,
**kw,
)
)
else:
par += fieldtype
par += nodes.Text(")")
par += nodes.Text(" -- ")
par += content
return par
fieldname = nodes.field_name("", self.label)
if len(items) == 1 and self.can_collapse:
fieldarg, content = items[0]
bodynode = handle_item(fieldarg, content)
else:
bodynode = self.list_type()
for fieldarg, content in items:
bodynode += nodes.list_item("", handle_item(fieldarg, content))
fieldbody = nodes.field_body("", bodynode)
return nodes.field("", fieldname, fieldbody)
TypedField.make_field = patched_make_field
copybutton_prompt_text = r">>> |\.\.\. "
copybutton_prompt_is_regexp = True