#!/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 sys31sys.path.insert(0, os.path.abspath('.'))32sys.path.insert(0, os.path.abspath('./.jenkins'))33import pytorch_sphinx_theme34import torch35import glob36import random37import shutil38from custom_directives import IncludeDirective, GalleryItemDirective, CustomGalleryItemDirective, CustomCalloutItemDirective, CustomCardItemDirective39import distutils.file_util40import re41from get_sphinx_filenames import SPHINX_SHOULD_RUN42import pandocfilters43import pypandoc44import plotly.io as pio45from pathlib import Path46pio.renderers.default = 'sphinx_gallery'47from redirects import redirects4849import sphinx_gallery.gen_rst50import multiprocessing5152# Monkey patch sphinx gallery to run each example in an isolated process so that53# we don't need to worry about examples changing global state.54#55# Alt option 1: Parallelism was added to sphinx gallery (a later version that we56# are not using yet) using joblib, but it seems to result in errors for us, and57# it has no effect if you set parallel = 1 (it will not put each file run into58# its own process and run singly) so you need parallel >= 2, and there may be59# tutorials that cannot be run in parallel.60#61# Alt option 2: Run sphinx gallery once per file (similar to how we shard in CI62# but with shard sizes of 1), but running sphinx gallery for each file has a63# ~5min overhead, resulting in the entire suite taking ~2x time64def call_fn(func, args, kwargs, result_queue):65try:66result = func(*args, **kwargs)67result_queue.put((True, result))68except Exception as e:69result_queue.put((False, str(e)))7071def call_in_subprocess(func):72def wrapper(*args, **kwargs):73result_queue = multiprocessing.Queue()74p = multiprocessing.Process(75target=call_fn,76args=(func, args, kwargs, result_queue)77)78p.start()79p.join()80success, result = result_queue.get()81if success:82return result83else:84raise RuntimeError(f"Error in subprocess: {result}")85return wrapper8687sphinx_gallery.gen_rst.generate_file_rst = call_in_subprocess(sphinx_gallery.gen_rst.generate_file_rst)8889try:90import torchvision91except ImportError:92import warnings93warnings.warn('unable to load "torchvision" package')94import pytorch_sphinx_theme9596rst_epilog ="""97.. |edit| image:: /_static/pencil-16.png98:width: 16px99:height: 16px100"""101102# -- General configuration ------------------------------------------------103104# If your documentation needs a minimal Sphinx version, state it here.105#106# needs_sphinx = '1.0'107108html_meta = {109'description': 'Master PyTorch with our step-by-step tutorials for all skill levels. Start your journey to becoming a PyTorch expert today!',110'keywords': 'PyTorch, tutorials, Getting Started, deep learning, AI',111'author': 'PyTorch Contributors'112}113114# Add any Sphinx extension module names here, as strings. They can be115# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom116# ones.117extensions = [118'sphinxcontrib.katex',119'sphinx.ext.intersphinx',120'sphinx_copybutton',121'sphinx_gallery.gen_gallery',122'sphinx_design',123'sphinx_sitemap',124'sphinx_reredirects'125]126127intersphinx_mapping = {128"torch": ("https://pytorch.org/docs/stable/", None),129"tensordict": ("https://pytorch.github.io/tensordict/", None),130"torchrl": ("https://pytorch.org/rl/", None),131"torchaudio": ("https://pytorch.org/audio/stable/", None),132"torchtext": ("https://pytorch.org/text/stable/", None),133"torchvision": ("https://pytorch.org/vision/stable/", None),134}135136# -- Sphinx-gallery configuration --------------------------------------------137138sphinx_gallery_conf = {139'examples_dirs': ['beginner_source', 'intermediate_source',140'advanced_source', 'recipes_source', 'prototype_source'],141'gallery_dirs': ['beginner', 'intermediate', 'advanced', 'recipes', 'prototype'],142'filename_pattern': re.compile(SPHINX_SHOULD_RUN),143'promote_jupyter_magic': True,144'backreferences_dir': None,145'first_notebook_cell': ("# For tips on running notebooks in Google Colab, see\n"146"# https://pytorch.org/tutorials/beginner/colab\n"147"%matplotlib inline"),148'ignore_pattern': r'_torch_export_nightly_tutorial.py',149'pypandoc': {'extra_args': ['--mathjax', '--toc'],150'filters': ['.jenkins/custom_pandoc_filter.py'],151},152}153154html_baseurl = 'https://pytorch.org/tutorials/' # needed for sphinx-sitemap155sitemap_locales = [None]156sitemap_excludes = [157"search.html",158"genindex.html",159]160sitemap_url_scheme = "{link}"161162if os.getenv('GALLERY_PATTERN'):163# GALLERY_PATTERN is to be used when you want to work on a single164# tutorial. Previously this was fed into filename_pattern, but165# if you do that, you still end up parsing all of the other Python166# files which takes a few seconds. This strategy is better, as167# ignore_pattern also skips parsing.168# See https://github.com/sphinx-gallery/sphinx-gallery/issues/721169# for a more detailed description of the issue.170sphinx_gallery_conf['ignore_pattern'] = r'/(?!' + re.escape(os.getenv('GALLERY_PATTERN')) + r')[^/]+$'171172for i in range(len(sphinx_gallery_conf['examples_dirs'])):173gallery_dir = Path(sphinx_gallery_conf["gallery_dirs"][i])174source_dir = Path(sphinx_gallery_conf["examples_dirs"][i])175176# Copy rst files from source dir to gallery dir177for f in source_dir.rglob("*.rst"):178f_dir = Path(f).parent179gallery_subdir_path = gallery_dir / f_dir.relative_to(source_dir)180gallery_subdir_path.mkdir(parents=True, exist_ok=True)181distutils.file_util.copy_file(f, gallery_subdir_path, update=True)182183# Add any paths that contain templates here, relative to this directory.184templates_path = ['_templates']185186# The suffix(es) of source filenames.187# You can specify multiple suffix as a list of string:188#189# source_suffix = ['.rst', '.md']190source_suffix = '.rst'191192# The master toctree document.193master_doc = 'index'194195# General information about the project.196project = 'PyTorch Tutorials'197copyright = '2024, PyTorch'198author = 'PyTorch contributors'199200# The version info for the project you're documenting, acts as replacement for201# |version| and |release|, also used in various other places throughout the202# built documents.203#204# The short X.Y version.205version = str(torch.__version__)206# The full version, including alpha/beta/rc tags.207release = str(torch.__version__)208209# The language for content autogenerated by Sphinx. Refer to documentation210# for a list of supported languages.211#212# This is also used if you do content translation via gettext catalogs.213# Usually you set "language" from the command line for these cases.214language = 'en'215216# List of patterns, relative to source directory, that match files and217# directories to ignore when looking for source files.218# This patterns also effect to html_static_path and html_extra_path219exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 'src/pytorch-sphinx-theme/docs*']220exclude_patterns += sphinx_gallery_conf['examples_dirs']221exclude_patterns += ['*/index.rst']222223# The name of the Pygments (syntax highlighting) style to use.224pygments_style = 'sphinx'225226# If true, `todo` and `todoList` produce output, else they produce nothing.227todo_include_todos = False228229230# -- Options for HTML output ----------------------------------------------231232# The theme to use for HTML and HTML Help pages. See the documentation for233# a list of builtin themes.234#235# html_theme = 'alabaster'236237# # Theme options are theme-specific and customize the look and feel of a theme238# # further. For a list of options available for each theme, see the239# # documentation.240# #241242# html_theme_options = {243# 'page_width': '1000px',244# 'fixed_sidebar': True,245# 'code_font_size': '0.87em',246# 'sidebar_includehidden': True247# }248249# # Add any paths that contain custom static files (such as style sheets) here,250# # relative to this directory. They are copied after the builtin static files,251# # so a file named "default.css" will overwrite the builtin "default.css".252html_static_path = ['_static']253254# # Custom sidebar templates, maps document names to template names.255# html_sidebars = {256# 'index': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html'],257# '**': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html']258# }259260261html_theme = 'pytorch_sphinx_theme'262html_theme_path = [pytorch_sphinx_theme.get_html_theme_path()]263html_logo = '_static/img/pytorch-logo-dark.svg'264html_theme_options = {265'pytorch_project': 'tutorials',266'collapse_navigation': False,267'display_version': True,268'navigation_with_keys': True,269'logo_only': False,270'analytics_id': 'GTM-T8XT4PS',271}272273274# -- Options for HTMLHelp output ------------------------------------------275276# Output file base name for HTML help builder.277htmlhelp_basename = 'PyTorchTutorialsdoc'278279280# -- Options for LaTeX output ---------------------------------------------281282latex_elements = {283# The paper size ('letterpaper' or 'a4paper').284#285# 'papersize': 'letterpaper',286287# The font size ('10pt', '11pt' or '12pt').288#289# 'pointsize': '10pt',290291# Additional stuff for the LaTeX preamble.292#293# 'preamble': '',294295# Latex figure (float) alignment296#297# 'figure_align': 'htbp',298}299300# Grouping the document tree into LaTeX files. List of tuples301# (source start file, target name, title,302# author, documentclass [howto, manual, or own class]).303latex_documents = [304(master_doc, 'PyTorchTutorials.tex', 'PyTorch Tutorials',305'Sasank, PyTorch contributors', 'manual'),306]307308309# -- Options for manual page output ---------------------------------------310311# One entry per manual page. List of tuples312# (source start file, name, description, authors, manual section).313man_pages = [314(master_doc, 'pytorchtutorials', 'PyTorch Tutorials',315[author], 1)316]317318319# -- Options for Texinfo output -------------------------------------------320321# Grouping the document tree into Texinfo files. List of tuples322# (source start file, target name, title, author,323# dir menu entry, description, category)324texinfo_documents = [325(master_doc, 'PyTorchTutorials', 'PyTorch Tutorials',326author, 'PyTorchTutorials', 'One line description of project.',327'Miscellaneous'),328]329330html_css_files = [331'https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css',332'css/custom.css',333'css/custom2.css'334]335336html_js_files = [337"js/custom.js",338]339340def setup(app):341# NOTE: in Sphinx 1.8+ `html_css_files` is an official configuration value342# and can be moved outside of this function (and the setup(app) function343# can be deleted).344#html_css_files = [345# 'https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css',346# 'css/custom.css'347#]348# In Sphinx 1.8 it was renamed to `add_css_file`, 1.7 and prior it is349# `add_stylesheet` (deprecated in 1.8).350#add_css = getattr(app, 'add_css_file', app.add_stylesheet)351#for css_file in html_css_files:352# add_css(css_file)353# Custom CSS354#app.add_stylesheet('css/pytorch_theme.css')355# app.add_stylesheet('https://fonts.googleapis.com/css?family=Lato')356# Custom directives357app.add_directive('includenodoc', IncludeDirective)358app.add_directive('galleryitem', GalleryItemDirective)359app.add_directive('customgalleryitem', CustomGalleryItemDirective)360app.add_directive('customcarditem', CustomCardItemDirective)361app.add_directive('customcalloutitem', CustomCalloutItemDirective)362363364