#!/usr/bin/env python31# -*- coding: utf-8 -*-2#3# PyTorch Tutorials documentation build configuration file, created by4# sphinx-quickstart on Wed Mar 8 22:38:10 2017.5#6# This file is execfile()d with the current directory set to its7# containing dir.8#9# Note that not all possible configuration values are present in this10# autogenerated file.11#12# All configuration values have a default; values that are commented out13# serve to show the default.14#1516# Because the sphinx gallery might take a long time, you can control specific17# files that generate the results using `GALLERY_PATTERN` environment variable,18# For example to run only `neural_style_transfer_tutorial.py`:19# GALLERY_PATTERN="neural_style_transfer_tutorial.py" make html20# or21# GALLERY_PATTERN="neural_style_transfer_tutorial.py" sphinx-build . _build22#23# GALLERY_PATTERN variable respects regular expressions.2425# If extensions (or modules to document with autodoc) are in another directory,26# add these directories to sys.path here. If the directory is relative to the27# documentation root, use os.path.abspath to make it absolute, like shown here.28#29import os30import sys3132sys.path.insert(0, os.path.abspath("."))33sys.path.insert(0, os.path.abspath("./.jenkins"))34import pytorch_sphinx_theme23536html_theme = "pytorch_sphinx_theme2"37html_theme_path = [pytorch_sphinx_theme2.get_html_theme_path()]38import distutils.file_util39import glob40import random41import re42import shutil43from pathlib import Path4445import pandocfilters46import plotly.io as pio47import pypandoc48import torch49from get_sphinx_filenames import SPHINX_SHOULD_RUN5051pio.renderers.default = "sphinx_gallery"52import multiprocessing5354import sphinx_gallery.gen_rst55from redirects import redirects565758# Monkey patch sphinx gallery to run each example in an isolated process so that59# we don't need to worry about examples changing global state.60#61# Alt option 1: Parallelism was added to sphinx gallery (a later version that we62# are not using yet) using joblib, but it seems to result in errors for us, and63# it has no effect if you set parallel = 1 (it will not put each file run into64# its own process and run singly) so you need parallel >= 2, and there may be65# tutorials that cannot be run in parallel.66#67# Alt option 2: Run sphinx gallery once per file (similar to how we shard in CI68# but with shard sizes of 1), but running sphinx gallery for each file has a69# ~5min overhead, resulting in the entire suite taking ~2x time70def call_fn(func, args, kwargs, result_queue):71try:72result = func(*args, **kwargs)73result_queue.put((True, result))74except Exception as e:75result_queue.put((False, str(e)))767778def call_in_subprocess(func):79def wrapper(*args, **kwargs):80result_queue = multiprocessing.Queue()81p = multiprocessing.Process(82target=call_fn, args=(func, args, kwargs, result_queue)83)84p.start()85p.join()86success, result = result_queue.get()87if success:88return result89else:90raise RuntimeError(f"Error in subprocess: {result}")9192return wrapper939495# Windows does not support multiprocessing with fork and mac has issues with96# fork so we do not monkey patch sphinx gallery to run in subprocesses.97if (98os.getenv("TUTORIALS_ISOLATE_BUILD", "1") == "1"99and not sys.platform.startswith("win")100and not sys.platform == "darwin"101):102sphinx_gallery.gen_rst.generate_file_rst = call_in_subprocess(103sphinx_gallery.gen_rst.generate_file_rst104)105106try:107import torchvision108except ImportError:109import warnings110111warnings.warn('unable to load "torchvision" package')112113rst_epilog = """114.. |edit| image:: /_static/pencil-16.png115:width: 16px116:height: 16px117"""118119# -- General configuration ------------------------------------------------120121# If your documentation needs a minimal Sphinx version, state it here.122#123# needs_sphinx = '1.0'124125html_meta = {126"description": "Master PyTorch with our step-by-step tutorials for all skill levels. Start your journey to becoming a PyTorch expert today!",127"keywords": "PyTorch, tutorials, Getting Started, deep learning, AI",128"author": "PyTorch Contributors",129}130131# Add any Sphinx extension module names here, as strings. They can be132# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom133# ones.134extensions = [135"sphinxcontrib.katex",136"sphinx.ext.intersphinx",137"sphinx_copybutton",138"sphinx_gallery.gen_gallery",139"sphinx_design",140"sphinx_sitemap",141"sphinx_reredirects",142"sphinxcontrib.mermaid",143]144145intersphinx_mapping = {146"torch": ("https://pytorch.org/docs/stable/", None),147"tensordict": ("https://pytorch.github.io/tensordict/stable", None),148"torchrl": ("https://pytorch.org/rl/stable", None),149"torchaudio": ("https://pytorch.org/audio/stable/", None),150"torchtext": ("https://pytorch.org/text/stable/", None),151"torchvision": ("https://pytorch.org/vision/stable/", None),152}153154html_meta = {155"description": "Master PyTorch with our step-by-step tutorials for all skill levels. Start your journey to becoming a PyTorch expert today!",156"keywords": "PyTorch, tutorials, Getting Started, deep learning, AI",157"author": "PyTorch Contributors",158}159160html_additional_pages = {161"404": "404.html",162}163164# -- Sphinx-gallery configuration --------------------------------------------165166sphinx_gallery_conf = {167"examples_dirs": [168"beginner_source",169"intermediate_source",170"advanced_source",171"recipes_source",172"unstable_source",173],174"gallery_dirs": ["beginner", "intermediate", "advanced", "recipes", "unstable"],175"filename_pattern": re.compile(SPHINX_SHOULD_RUN),176"promote_jupyter_magic": True,177"backreferences_dir": None,178"write_computation_times": True,179"download_all_examples": False,180"show_signature": False,181"first_notebook_cell": (182"# For tips on running notebooks in Google Colab, see\n"183"# https://pytorch.org/tutorials/beginner/colab\n"184"%matplotlib inline"185),186"ignore_pattern": r"_torch_export_nightly_tutorial.py",187"pypandoc": {188"extra_args": ["--mathjax", "--toc"],189"filters": [".jenkins/custom_pandoc_filter.py"],190},191}192193html_baseurl = "https://pytorch.org/tutorials/" # needed for sphinx-sitemap194sitemap_locales = [None]195sitemap_excludes = [196"search.html",197"genindex.html",198]199sitemap_url_scheme = "{link}"200201html_theme_options = {202"navigation_with_keys": False,203"analytics_id": "GTM-T8XT4PS",204"logo": {205"text": "",206},207"icon_links": [208{209"name": "X",210"url": "https://x.com/PyTorch",211"icon": "fa-brands fa-x-twitter",212},213{214"name": "GitHub",215"url": "https://github.com/pytorch/tutorials",216"icon": "fa-brands fa-github",217},218{219"name": "Discourse",220"url": "https://dev-discuss.pytorch.org/",221"icon": "fa-brands fa-discourse",222},223{224"name": "PyPi",225"url": "https://pypi.org/project/torch/",226"icon": "fa-brands fa-python",227},228],229"use_edit_page_button": True,230"header_links_before_dropdown": 9,231"navbar_start": ["pytorch_version"],232"navbar_center": "navbar-nav",233"display_version": True,234"pytorch_project": "tutorials",235}236237theme_variables = pytorch_sphinx_theme2.get_theme_variables()238239html_context = {240"theme_variables": theme_variables,241"display_github": True,242"github_url": "https://github.com",243"github_user": "pytorch",244"github_repo": "tutorials",245"feedback_url": "https://github.com/pytorch/tutorials",246"github_version": "main",247"doc_path": ".",248"library_links": theme_variables.get("library_links", []),249#"pytorch_project": "tutorials",250}251252253if os.getenv("GALLERY_PATTERN"):254# GALLERY_PATTERN is to be used when you want to work on a single255# tutorial. Previously this was fed into filename_pattern, but256# if you do that, you still end up parsing all of the other Python257# files which takes a few seconds. This strategy is better, as258# ignore_pattern also skips parsing.259# See https://github.com/sphinx-gallery/sphinx-gallery/issues/721260# for a more detailed description of the issue.261sphinx_gallery_conf["ignore_pattern"] = (262r"/(?!" + re.escape(os.getenv("GALLERY_PATTERN")) + r")[^/]+$"263)264265for i in range(len(sphinx_gallery_conf["examples_dirs"])):266gallery_dir = Path(sphinx_gallery_conf["gallery_dirs"][i])267source_dir = Path(sphinx_gallery_conf["examples_dirs"][i])268269# Copy rst files from source dir to gallery dir270for f in source_dir.rglob("*.rst"):271f_dir = Path(f).parent272gallery_subdir_path = gallery_dir / f_dir.relative_to(source_dir)273gallery_subdir_path.mkdir(parents=True, exist_ok=True)274distutils.file_util.copy_file(f, gallery_subdir_path, update=True)275276# Add any paths that contain templates here, relative to this directory.277templates_path = [278"_templates",279os.path.join(os.path.dirname(pytorch_sphinx_theme2.__file__), "templates"),280]281282# The suffix(es) of source filenames.283# You can specify multiple suffix as a list of string:284#285# source_suffix = ['.rst', '.md']286source_suffix = ".rst"287288# The master toctree document.289master_doc = "index"290291# General information about the project.292project = "PyTorch Tutorials"293copyright = "2024, PyTorch"294author = "PyTorch contributors"295296# The version info for the project you're documenting, acts as replacement for297# |version| and |release|, also used in various other places throughout the298# built documents.299#300# The short X.Y version.301version = "v" + str(torch.__version__)302# The full version, including alpha/beta/rc tags.303release = str(torch.__version__)304305# The language for content autogenerated by Sphinx. Refer to documentation306# for a list of supported languages.307#308# This is also used if you do content translation via gettext catalogs.309# Usually you set "language" from the command line for these cases.310language = "en"311312# List of patterns, relative to source directory, that match files and313# directories to ignore when looking for source files.314# This patterns also effect to html_static_path and html_extra_path315exclude_patterns = [316"_build",317"Thumbs.db",318".DS_Store",319"src/pytorch-sphinx-theme/docs*",320]321exclude_patterns += sphinx_gallery_conf["examples_dirs"]322exclude_patterns += ["*/index.rst"]323324325# Handling for HuggingFace Hub jinja templates326def handle_jinja_templates(app, docname, source):327if "huggingface_hub/templates" in docname:328# Replace Jinja templates with quoted strings329source[0] = re.sub(r"(\{\{.*?\}\})", r'"\1"', source[0])330331332# The name of the Pygments (syntax highlighting) style to use.333pygments_style = "sphinx"334335# If true, `todo` and `todoList` produce output, else they produce nothing.336todo_include_todos = False337338339# -- Options for HTML output ----------------------------------------------340341# The theme to use for HTML and HTML Help pages. See the documentation for342# a list of builtin themes.343#344# html_theme = 'alabaster'345346# # Theme options are theme-specific and customize the look and feel of a theme347# # further. For a list of options available for each theme, see the348# # documentation.349# #350351# html_theme_options = {352# 'page_width': '1000px',353# 'fixed_sidebar': True,354# 'code_font_size': '0.87em',355# 'sidebar_includehidden': True356# }357358# # Add any paths that contain custom static files (such as style sheets) here,359# # relative to this directory. They are copied after the builtin static files,360# # so a file named "default.css" will overwrite the builtin "default.css".361html_static_path = ["_static"]362363# # Custom sidebar templates, maps document names to template names.364# html_sidebars = {365# 'index': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html'],366# '**': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html']367# }368369370# -- Options for HTMLHelp output ------------------------------------------371372# Output file base name for HTML help builder.373htmlhelp_basename = "PyTorchTutorialsdoc"374375376# -- Options for LaTeX output ---------------------------------------------377378latex_elements = {379# The paper size ('letterpaper' or 'a4paper').380#381# 'papersize': 'letterpaper',382# The font size ('10pt', '11pt' or '12pt').383#384# 'pointsize': '10pt',385# Additional stuff for the LaTeX preamble.386#387# 'preamble': '',388# Latex figure (float) alignment389#390# 'figure_align': 'htbp',391}392393# Grouping the document tree into LaTeX files. List of tuples394# (source start file, target name, title,395# author, documentclass [howto, manual, or own class]).396latex_documents = [397(398master_doc,399"PyTorchTutorials.tex",400"PyTorch Tutorials",401"Sasank, PyTorch contributors",402"manual",403),404]405406407# -- Options for manual page output ---------------------------------------408409# One entry per manual page. List of tuples410# (source start file, name, description, authors, manual section).411man_pages = [(master_doc, "pytorchtutorials", "PyTorch Tutorials", [author], 1)]412413414# -- Options for Texinfo output -------------------------------------------415416# Grouping the document tree into Texinfo files. List of tuples417# (source start file, target name, title, author,418# dir menu entry, description, category)419texinfo_documents = [420(421master_doc,422"PyTorchTutorials",423"PyTorch Tutorials",424author,425"PyTorchTutorials",426"One line description of project.",427"Miscellaneous",428),429]430431html_css_files = [432"https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css",433]434435436def html_page_context(app, pagename, templatename, context, doctree):437# Check if the page is in gallery directories438for gallery_dir in sphinx_gallery_conf["gallery_dirs"]:439if pagename.startswith(gallery_dir):440# Get corresponding examples directory441examples_dir = sphinx_gallery_conf["examples_dirs"][442sphinx_gallery_conf["gallery_dirs"].index(gallery_dir)443]444445# Calculate relative path within the gallery446rel_path = (447pagename[len(gallery_dir) + 1 :] if pagename != gallery_dir else ""448)449450# Check for .py file in examples directory451py_path = os.path.join(app.srcdir, examples_dir, rel_path + ".py")452453# If a .py file exists, this page was generated from Python454if os.path.exists(py_path):455context["display_github"] = False456return457458# Enable for all other pages459context["display_github"] = True460461462def setup(app):463app.connect("source-read", handle_jinja_templates)464app.connect("html-page-context", html_page_context)465466467