#!/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://docs.pytorch.org/docs/stable/", None),147"tensordict": ("https://docs.pytorch.org/tensordict/stable", None),148"torchrl": ("https://docs.pytorch.org/rl/stable", None),149"torchaudio": ("https://docs.pytorch.org/audio/stable/", None),150"torchtext": ("https://docs.pytorch.org/text/stable/", None),151"torchvision": ("https://docs.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}159160161162# -- Sphinx-gallery configuration --------------------------------------------163164sphinx_gallery_conf = {165"examples_dirs": [166"beginner_source",167"intermediate_source",168"advanced_source",169"recipes_source",170"unstable_source",171],172"gallery_dirs": ["beginner", "intermediate", "advanced", "recipes", "unstable"],173"filename_pattern": re.compile(SPHINX_SHOULD_RUN),174"promote_jupyter_magic": True,175"backreferences_dir": None,176"write_computation_times": True,177"download_all_examples": False,178"show_signature": False,179"first_notebook_cell": (180"# For tips on running notebooks in Google Colab, see\n"181"# https://docs.pytorch.org/tutorials/beginner/colab\n"182"%matplotlib inline"183),184"ignore_pattern": r"_torch_export_nightly_tutorial.py",185"pypandoc": {186"extra_args": ["--mathjax", "--toc"],187"filters": [".jenkins/custom_pandoc_filter.py"],188},189}190191html_additional_pages = {192"404": "404.html",193}194195196html_baseurl = "https://docs.pytorch.org/tutorials/" # needed for sphinx-sitemap197sitemap_locales = [None]198sitemap_excludes = [199"search.html",200"genindex.html",201]202sitemap_url_scheme = "{link}"203204html_theme_options = {205"navigation_with_keys": False,206"analytics_id": "GTM-T8XT4PS",207"logo": {208"text": "",209},210"icon_links": [211{212"name": "X",213"url": "https://x.com/PyTorch",214"icon": "fa-brands fa-x-twitter",215},216{217"name": "GitHub",218"url": "https://github.com/pytorch/tutorials",219"icon": "fa-brands fa-github",220},221{222"name": "Discourse",223"url": "https://dev-discuss.pytorch.org/",224"icon": "fa-brands fa-discourse",225},226{227"name": "PyPi",228"url": "https://pypi.org/project/torch/",229"icon": "fa-brands fa-python",230},231],232"use_edit_page_button": True,233"header_links_before_dropdown": 9,234"navbar_start": ["pytorch_version"],235"navbar_center": "navbar-nav",236"display_version": True,237"pytorch_project": "tutorials",238"canonical_url": "https://docs.pytorch.org/tutorials/",239}240241theme_variables = pytorch_sphinx_theme2.get_theme_variables()242243html_context = {244"theme_variables": theme_variables,245"display_github": True,246"github_url": "https://github.com",247"github_user": "pytorch",248"github_repo": "tutorials",249"feedback_url": "https://github.com/pytorch/tutorials",250"github_version": "main",251"doc_path": ".",252"library_links": theme_variables.get("library_links", []),253#"pytorch_project": "tutorials",254}255256257if os.getenv("GALLERY_PATTERN"):258# GALLERY_PATTERN is to be used when you want to work on a single259# tutorial. Previously this was fed into filename_pattern, but260# if you do that, you still end up parsing all of the other Python261# files which takes a few seconds. This strategy is better, as262# ignore_pattern also skips parsing.263# See https://github.com/sphinx-gallery/sphinx-gallery/issues/721264# for a more detailed description of the issue.265sphinx_gallery_conf["ignore_pattern"] = (266r"/(?!" + re.escape(os.getenv("GALLERY_PATTERN")) + r")[^/]+$"267)268269for i in range(len(sphinx_gallery_conf["examples_dirs"])):270gallery_dir = Path(sphinx_gallery_conf["gallery_dirs"][i])271source_dir = Path(sphinx_gallery_conf["examples_dirs"][i])272273# Copy rst files from source dir to gallery dir274for f in source_dir.rglob("*.rst"):275f_dir = Path(f).parent276gallery_subdir_path = gallery_dir / f_dir.relative_to(source_dir)277gallery_subdir_path.mkdir(parents=True, exist_ok=True)278distutils.file_util.copy_file(f, gallery_subdir_path, update=True)279280# Add any paths that contain templates here, relative to this directory.281templates_path = [282"_templates",283os.path.join(os.path.dirname(pytorch_sphinx_theme2.__file__), "templates"),284]285286# The suffix(es) of source filenames.287# You can specify multiple suffix as a list of string:288#289# source_suffix = ['.rst', '.md']290source_suffix = ".rst"291292# The master toctree document.293master_doc = "index"294295# General information about the project.296project = "PyTorch Tutorials"297copyright = "2024, PyTorch"298author = "PyTorch contributors"299300# The version info for the project you're documenting, acts as replacement for301# |version| and |release|, also used in various other places throughout the302# built documents.303#304# The short X.Y version.305version = "v" + str(torch.__version__)306# The full version, including alpha/beta/rc tags.307release = str(torch.__version__)308309# The language for content autogenerated by Sphinx. Refer to documentation310# for a list of supported languages.311#312# This is also used if you do content translation via gettext catalogs.313# Usually you set "language" from the command line for these cases.314language = "en"315316# List of patterns, relative to source directory, that match files and317# directories to ignore when looking for source files.318# This patterns also effect to html_static_path and html_extra_path319exclude_patterns = [320"_build",321"Thumbs.db",322".DS_Store",323"src/pytorch-sphinx-theme/docs*",324]325exclude_patterns += sphinx_gallery_conf["examples_dirs"]326exclude_patterns += ["*/index.rst"]327328329# Handling for HuggingFace Hub jinja templates330def handle_jinja_templates(app, docname, source):331if "huggingface_hub/templates" in docname:332# Replace Jinja templates with quoted strings333source[0] = re.sub(r"(\{\{.*?\}\})", r'"\1"', source[0])334335336# The name of the Pygments (syntax highlighting) style to use.337pygments_style = "sphinx"338339# If true, `todo` and `todoList` produce output, else they produce nothing.340todo_include_todos = False341342343# -- Options for HTML output ----------------------------------------------344345# The theme to use for HTML and HTML Help pages. See the documentation for346# a list of builtin themes.347#348# html_theme = 'alabaster'349350# # Theme options are theme-specific and customize the look and feel of a theme351# # further. For a list of options available for each theme, see the352# # documentation.353# #354355# html_theme_options = {356# 'page_width': '1000px',357# 'fixed_sidebar': True,358# 'code_font_size': '0.87em',359# 'sidebar_includehidden': True360# }361362# # Add any paths that contain custom static files (such as style sheets) here,363# # relative to this directory. They are copied after the builtin static files,364# # so a file named "default.css" will overwrite the builtin "default.css".365html_static_path = ["_static"]366367# # Custom sidebar templates, maps document names to template names.368# html_sidebars = {369# 'index': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html'],370# '**': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html']371# }372373374# -- Options for HTMLHelp output ------------------------------------------375376# Output file base name for HTML help builder.377htmlhelp_basename = "PyTorchTutorialsdoc"378379380# -- Options for LaTeX output ---------------------------------------------381382latex_elements = {383# The paper size ('letterpaper' or 'a4paper').384#385# 'papersize': 'letterpaper',386# The font size ('10pt', '11pt' or '12pt').387#388# 'pointsize': '10pt',389# Additional stuff for the LaTeX preamble.390#391# 'preamble': '',392# Latex figure (float) alignment393#394# 'figure_align': 'htbp',395}396397# Grouping the document tree into LaTeX files. List of tuples398# (source start file, target name, title,399# author, documentclass [howto, manual, or own class]).400latex_documents = [401(402master_doc,403"PyTorchTutorials.tex",404"PyTorch Tutorials",405"Sasank, PyTorch contributors",406"manual",407),408]409410411# -- Options for manual page output ---------------------------------------412413# One entry per manual page. List of tuples414# (source start file, name, description, authors, manual section).415man_pages = [(master_doc, "pytorchtutorials", "PyTorch Tutorials", [author], 1)]416417418# -- Options for Texinfo output -------------------------------------------419420# Grouping the document tree into Texinfo files. List of tuples421# (source start file, target name, title, author,422# dir menu entry, description, category)423texinfo_documents = [424(425master_doc,426"PyTorchTutorials",427"PyTorch Tutorials",428author,429"PyTorchTutorials",430"One line description of project.",431"Miscellaneous",432),433]434435html_css_files = [436"https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css",437]438439440def html_page_context(app, pagename, templatename, context, doctree):441# Check if the page is in gallery directories442for gallery_dir in sphinx_gallery_conf["gallery_dirs"]:443if pagename.startswith(gallery_dir):444# Get corresponding examples directory445examples_dir = sphinx_gallery_conf["examples_dirs"][446sphinx_gallery_conf["gallery_dirs"].index(gallery_dir)447]448449# Calculate relative path within the gallery450rel_path = (451pagename[len(gallery_dir) + 1 :] if pagename != gallery_dir else ""452)453454# Check for .py file in examples directory455py_path = os.path.join(app.srcdir, examples_dir, rel_path + ".py")456457# If a .py file exists, this page was generated from Python458if os.path.exists(py_path):459context["display_github"] = False460return461462# Enable for all other pages463context["display_github"] = True464465466def setup(app):467app.connect("source-read", handle_jinja_templates)468app.connect("html-page-context", html_page_context)469470471