#!/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}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://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://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}239240theme_variables = pytorch_sphinx_theme2.get_theme_variables()241242html_context = {243"theme_variables": theme_variables,244"display_github": True,245"github_url": "https://github.com",246"github_user": "pytorch",247"github_repo": "tutorials",248"feedback_url": "https://github.com/pytorch/tutorials",249"github_version": "main",250"doc_path": ".",251"library_links": theme_variables.get("library_links", []),252#"pytorch_project": "tutorials",253}254255256if os.getenv("GALLERY_PATTERN"):257# GALLERY_PATTERN is to be used when you want to work on a single258# tutorial. Previously this was fed into filename_pattern, but259# if you do that, you still end up parsing all of the other Python260# files which takes a few seconds. This strategy is better, as261# ignore_pattern also skips parsing.262# See https://github.com/sphinx-gallery/sphinx-gallery/issues/721263# for a more detailed description of the issue.264sphinx_gallery_conf["ignore_pattern"] = (265r"/(?!" + re.escape(os.getenv("GALLERY_PATTERN")) + r")[^/]+$"266)267268for i in range(len(sphinx_gallery_conf["examples_dirs"])):269gallery_dir = Path(sphinx_gallery_conf["gallery_dirs"][i])270source_dir = Path(sphinx_gallery_conf["examples_dirs"][i])271272# Copy rst files from source dir to gallery dir273for f in source_dir.rglob("*.rst"):274f_dir = Path(f).parent275gallery_subdir_path = gallery_dir / f_dir.relative_to(source_dir)276gallery_subdir_path.mkdir(parents=True, exist_ok=True)277distutils.file_util.copy_file(f, gallery_subdir_path, update=True)278279# Add any paths that contain templates here, relative to this directory.280templates_path = [281"_templates",282os.path.join(os.path.dirname(pytorch_sphinx_theme2.__file__), "templates"),283]284285# The suffix(es) of source filenames.286# You can specify multiple suffix as a list of string:287#288# source_suffix = ['.rst', '.md']289source_suffix = ".rst"290291# The master toctree document.292master_doc = "index"293294# General information about the project.295project = "PyTorch Tutorials"296copyright = "2024, PyTorch"297author = "PyTorch contributors"298299# The version info for the project you're documenting, acts as replacement for300# |version| and |release|, also used in various other places throughout the301# built documents.302#303# The short X.Y version.304version = "v" + str(torch.__version__)305# The full version, including alpha/beta/rc tags.306release = str(torch.__version__)307308# The language for content autogenerated by Sphinx. Refer to documentation309# for a list of supported languages.310#311# This is also used if you do content translation via gettext catalogs.312# Usually you set "language" from the command line for these cases.313language = "en"314315# List of patterns, relative to source directory, that match files and316# directories to ignore when looking for source files.317# This patterns also effect to html_static_path and html_extra_path318exclude_patterns = [319"_build",320"Thumbs.db",321".DS_Store",322"src/pytorch-sphinx-theme/docs*",323]324exclude_patterns += sphinx_gallery_conf["examples_dirs"]325exclude_patterns += ["*/index.rst"]326327328# Handling for HuggingFace Hub jinja templates329def handle_jinja_templates(app, docname, source):330if "huggingface_hub/templates" in docname:331# Replace Jinja templates with quoted strings332source[0] = re.sub(r"(\{\{.*?\}\})", r'"\1"', source[0])333334335# The name of the Pygments (syntax highlighting) style to use.336pygments_style = "sphinx"337338# If true, `todo` and `todoList` produce output, else they produce nothing.339todo_include_todos = False340341342# -- Options for HTML output ----------------------------------------------343344# The theme to use for HTML and HTML Help pages. See the documentation for345# a list of builtin themes.346#347# html_theme = 'alabaster'348349# # Theme options are theme-specific and customize the look and feel of a theme350# # further. For a list of options available for each theme, see the351# # documentation.352# #353354# html_theme_options = {355# 'page_width': '1000px',356# 'fixed_sidebar': True,357# 'code_font_size': '0.87em',358# 'sidebar_includehidden': True359# }360361# # Add any paths that contain custom static files (such as style sheets) here,362# # relative to this directory. They are copied after the builtin static files,363# # so a file named "default.css" will overwrite the builtin "default.css".364html_static_path = ["_static"]365366# # Custom sidebar templates, maps document names to template names.367# html_sidebars = {368# 'index': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html'],369# '**': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html']370# }371372373# -- Options for HTMLHelp output ------------------------------------------374375# Output file base name for HTML help builder.376htmlhelp_basename = "PyTorchTutorialsdoc"377378379# -- Options for LaTeX output ---------------------------------------------380381latex_elements = {382# The paper size ('letterpaper' or 'a4paper').383#384# 'papersize': 'letterpaper',385# The font size ('10pt', '11pt' or '12pt').386#387# 'pointsize': '10pt',388# Additional stuff for the LaTeX preamble.389#390# 'preamble': '',391# Latex figure (float) alignment392#393# 'figure_align': 'htbp',394}395396# Grouping the document tree into LaTeX files. List of tuples397# (source start file, target name, title,398# author, documentclass [howto, manual, or own class]).399latex_documents = [400(401master_doc,402"PyTorchTutorials.tex",403"PyTorch Tutorials",404"Sasank, PyTorch contributors",405"manual",406),407]408409410# -- Options for manual page output ---------------------------------------411412# One entry per manual page. List of tuples413# (source start file, name, description, authors, manual section).414man_pages = [(master_doc, "pytorchtutorials", "PyTorch Tutorials", [author], 1)]415416417# -- Options for Texinfo output -------------------------------------------418419# Grouping the document tree into Texinfo files. List of tuples420# (source start file, target name, title, author,421# dir menu entry, description, category)422texinfo_documents = [423(424master_doc,425"PyTorchTutorials",426"PyTorch Tutorials",427author,428"PyTorchTutorials",429"One line description of project.",430"Miscellaneous",431),432]433434html_css_files = [435"https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css",436]437438439def html_page_context(app, pagename, templatename, context, doctree):440# Check if the page is in gallery directories441for gallery_dir in sphinx_gallery_conf["gallery_dirs"]:442if pagename.startswith(gallery_dir):443# Get corresponding examples directory444examples_dir = sphinx_gallery_conf["examples_dirs"][445sphinx_gallery_conf["gallery_dirs"].index(gallery_dir)446]447448# Calculate relative path within the gallery449rel_path = (450pagename[len(gallery_dir) + 1 :] if pagename != gallery_dir else ""451)452453# Check for .py file in examples directory454py_path = os.path.join(app.srcdir, examples_dir, rel_path + ".py")455456# If a .py file exists, this page was generated from Python457if os.path.exists(py_path):458context["display_github"] = False459return460461# Enable for all other pages462context["display_github"] = True463464465def setup(app):466app.connect("source-read", handle_jinja_templates)467app.connect("html-page-context", html_page_context)468469470