Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pytorch
GitHub Repository: pytorch/tutorials
Path: blob/main/conf.py
1384 views
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
#
4
# PyTorch Tutorials documentation build configuration file, created by
5
# sphinx-quickstart on Wed Mar 8 22:38:10 2017.
6
#
7
# This file is execfile()d with the current directory set to its
8
# containing dir.
9
#
10
# Note that not all possible configuration values are present in this
11
# autogenerated file.
12
#
13
# All configuration values have a default; values that are commented out
14
# serve to show the default.
15
#
16
17
# Because the sphinx gallery might take a long time, you can control specific
18
# files that generate the results using `GALLERY_PATTERN` environment variable,
19
# For example to run only `neural_style_transfer_tutorial.py`:
20
# GALLERY_PATTERN="neural_style_transfer_tutorial.py" make html
21
# or
22
# GALLERY_PATTERN="neural_style_transfer_tutorial.py" sphinx-build . _build
23
#
24
# GALLERY_PATTERN variable respects regular expressions.
25
26
# If extensions (or modules to document with autodoc) are in another directory,
27
# add these directories to sys.path here. If the directory is relative to the
28
# documentation root, use os.path.abspath to make it absolute, like shown here.
29
#
30
import os
31
import sys
32
sys.path.insert(0, os.path.abspath('.'))
33
sys.path.insert(0, os.path.abspath('./.jenkins'))
34
import pytorch_sphinx_theme
35
import torch
36
import glob
37
import random
38
import shutil
39
from custom_directives import IncludeDirective, GalleryItemDirective, CustomGalleryItemDirective, CustomCalloutItemDirective, CustomCardItemDirective
40
import distutils.file_util
41
import re
42
from get_sphinx_filenames import SPHINX_SHOULD_RUN
43
import pandocfilters
44
import pypandoc
45
import plotly.io as pio
46
from pathlib import Path
47
pio.renderers.default = 'sphinx_gallery'
48
from redirects import redirects
49
50
import sphinx_gallery.gen_rst
51
import multiprocessing
52
53
# Monkey patch sphinx gallery to run each example in an isolated process so that
54
# we don't need to worry about examples changing global state.
55
#
56
# Alt option 1: Parallelism was added to sphinx gallery (a later version that we
57
# are not using yet) using joblib, but it seems to result in errors for us, and
58
# it has no effect if you set parallel = 1 (it will not put each file run into
59
# its own process and run singly) so you need parallel >= 2, and there may be
60
# tutorials that cannot be run in parallel.
61
#
62
# Alt option 2: Run sphinx gallery once per file (similar to how we shard in CI
63
# but with shard sizes of 1), but running sphinx gallery for each file has a
64
# ~5min overhead, resulting in the entire suite taking ~2x time
65
def call_fn(func, args, kwargs, result_queue):
66
try:
67
result = func(*args, **kwargs)
68
result_queue.put((True, result))
69
except Exception as e:
70
result_queue.put((False, str(e)))
71
72
def call_in_subprocess(func):
73
def wrapper(*args, **kwargs):
74
result_queue = multiprocessing.Queue()
75
p = multiprocessing.Process(
76
target=call_fn,
77
args=(func, args, kwargs, result_queue)
78
)
79
p.start()
80
p.join()
81
success, result = result_queue.get()
82
if success:
83
return result
84
else:
85
raise RuntimeError(f"Error in subprocess: {result}")
86
return wrapper
87
88
sphinx_gallery.gen_rst.generate_file_rst = call_in_subprocess(sphinx_gallery.gen_rst.generate_file_rst)
89
90
try:
91
import torchvision
92
except ImportError:
93
import warnings
94
warnings.warn('unable to load "torchvision" package')
95
import pytorch_sphinx_theme
96
97
rst_epilog ="""
98
.. |edit| image:: /_static/pencil-16.png
99
:width: 16px
100
:height: 16px
101
"""
102
103
# -- General configuration ------------------------------------------------
104
105
# If your documentation needs a minimal Sphinx version, state it here.
106
#
107
# needs_sphinx = '1.0'
108
109
html_meta = {
110
'description': 'Master PyTorch with our step-by-step tutorials for all skill levels. Start your journey to becoming a PyTorch expert today!',
111
'keywords': 'PyTorch, tutorials, Getting Started, deep learning, AI',
112
'author': 'PyTorch Contributors'
113
}
114
115
# Add any Sphinx extension module names here, as strings. They can be
116
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
117
# ones.
118
extensions = [
119
'sphinxcontrib.katex',
120
'sphinx.ext.intersphinx',
121
'sphinx_copybutton',
122
'sphinx_gallery.gen_gallery',
123
'sphinx_design',
124
'sphinx_sitemap',
125
'sphinx_reredirects'
126
]
127
128
intersphinx_mapping = {
129
"torch": ("https://pytorch.org/docs/stable/", None),
130
"tensordict": ("https://pytorch.github.io/tensordict/", None),
131
"torchrl": ("https://pytorch.org/rl/", None),
132
"torchaudio": ("https://pytorch.org/audio/stable/", None),
133
"torchtext": ("https://pytorch.org/text/stable/", None),
134
"torchvision": ("https://pytorch.org/vision/stable/", None),
135
}
136
137
# -- Sphinx-gallery configuration --------------------------------------------
138
139
sphinx_gallery_conf = {
140
'examples_dirs': ['beginner_source', 'intermediate_source',
141
'advanced_source', 'recipes_source', 'prototype_source'],
142
'gallery_dirs': ['beginner', 'intermediate', 'advanced', 'recipes', 'prototype'],
143
'filename_pattern': re.compile(SPHINX_SHOULD_RUN),
144
'promote_jupyter_magic': True,
145
'backreferences_dir': None,
146
'first_notebook_cell': ("# For tips on running notebooks in Google Colab, see\n"
147
"# https://pytorch.org/tutorials/beginner/colab\n"
148
"%matplotlib inline"),
149
'ignore_pattern': r'_torch_export_nightly_tutorial.py',
150
'pypandoc': {'extra_args': ['--mathjax', '--toc'],
151
'filters': ['.jenkins/custom_pandoc_filter.py'],
152
},
153
}
154
155
html_baseurl = 'https://pytorch.org/tutorials/' # needed for sphinx-sitemap
156
sitemap_locales = [None]
157
sitemap_excludes = [
158
"search.html",
159
"genindex.html",
160
]
161
sitemap_url_scheme = "{link}"
162
163
if os.getenv('GALLERY_PATTERN'):
164
# GALLERY_PATTERN is to be used when you want to work on a single
165
# tutorial. Previously this was fed into filename_pattern, but
166
# if you do that, you still end up parsing all of the other Python
167
# files which takes a few seconds. This strategy is better, as
168
# ignore_pattern also skips parsing.
169
# See https://github.com/sphinx-gallery/sphinx-gallery/issues/721
170
# for a more detailed description of the issue.
171
sphinx_gallery_conf['ignore_pattern'] = r'/(?!' + re.escape(os.getenv('GALLERY_PATTERN')) + r')[^/]+$'
172
173
for i in range(len(sphinx_gallery_conf['examples_dirs'])):
174
gallery_dir = Path(sphinx_gallery_conf["gallery_dirs"][i])
175
source_dir = Path(sphinx_gallery_conf["examples_dirs"][i])
176
177
# Copy rst files from source dir to gallery dir
178
for f in source_dir.rglob("*.rst"):
179
f_dir = Path(f).parent
180
gallery_subdir_path = gallery_dir / f_dir.relative_to(source_dir)
181
gallery_subdir_path.mkdir(parents=True, exist_ok=True)
182
distutils.file_util.copy_file(f, gallery_subdir_path, update=True)
183
184
# Add any paths that contain templates here, relative to this directory.
185
templates_path = ['_templates']
186
187
# The suffix(es) of source filenames.
188
# You can specify multiple suffix as a list of string:
189
#
190
# source_suffix = ['.rst', '.md']
191
source_suffix = '.rst'
192
193
# The master toctree document.
194
master_doc = 'index'
195
196
# General information about the project.
197
project = 'PyTorch Tutorials'
198
copyright = '2024, PyTorch'
199
author = 'PyTorch contributors'
200
201
# The version info for the project you're documenting, acts as replacement for
202
# |version| and |release|, also used in various other places throughout the
203
# built documents.
204
#
205
# The short X.Y version.
206
version = str(torch.__version__)
207
# The full version, including alpha/beta/rc tags.
208
release = str(torch.__version__)
209
210
# The language for content autogenerated by Sphinx. Refer to documentation
211
# for a list of supported languages.
212
#
213
# This is also used if you do content translation via gettext catalogs.
214
# Usually you set "language" from the command line for these cases.
215
language = 'en'
216
217
# List of patterns, relative to source directory, that match files and
218
# directories to ignore when looking for source files.
219
# This patterns also effect to html_static_path and html_extra_path
220
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 'src/pytorch-sphinx-theme/docs*']
221
exclude_patterns += sphinx_gallery_conf['examples_dirs']
222
exclude_patterns += ['*/index.rst']
223
224
# The name of the Pygments (syntax highlighting) style to use.
225
pygments_style = 'sphinx'
226
227
# If true, `todo` and `todoList` produce output, else they produce nothing.
228
todo_include_todos = False
229
230
231
# -- Options for HTML output ----------------------------------------------
232
233
# The theme to use for HTML and HTML Help pages. See the documentation for
234
# a list of builtin themes.
235
#
236
# html_theme = 'alabaster'
237
238
# # Theme options are theme-specific and customize the look and feel of a theme
239
# # further. For a list of options available for each theme, see the
240
# # documentation.
241
# #
242
243
# html_theme_options = {
244
# 'page_width': '1000px',
245
# 'fixed_sidebar': True,
246
# 'code_font_size': '0.87em',
247
# 'sidebar_includehidden': True
248
# }
249
250
# # Add any paths that contain custom static files (such as style sheets) here,
251
# # relative to this directory. They are copied after the builtin static files,
252
# # so a file named "default.css" will overwrite the builtin "default.css".
253
html_static_path = ['_static']
254
255
# # Custom sidebar templates, maps document names to template names.
256
# html_sidebars = {
257
# 'index': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html'],
258
# '**': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html']
259
# }
260
261
262
html_theme = 'pytorch_sphinx_theme'
263
html_theme_path = [pytorch_sphinx_theme.get_html_theme_path()]
264
html_logo = '_static/img/pytorch-logo-dark.svg'
265
html_theme_options = {
266
'pytorch_project': 'tutorials',
267
'collapse_navigation': False,
268
'display_version': True,
269
'navigation_with_keys': True,
270
'logo_only': False,
271
'analytics_id': 'GTM-T8XT4PS',
272
}
273
274
275
# -- Options for HTMLHelp output ------------------------------------------
276
277
# Output file base name for HTML help builder.
278
htmlhelp_basename = 'PyTorchTutorialsdoc'
279
280
281
# -- Options for LaTeX output ---------------------------------------------
282
283
latex_elements = {
284
# The paper size ('letterpaper' or 'a4paper').
285
#
286
# 'papersize': 'letterpaper',
287
288
# The font size ('10pt', '11pt' or '12pt').
289
#
290
# 'pointsize': '10pt',
291
292
# Additional stuff for the LaTeX preamble.
293
#
294
# 'preamble': '',
295
296
# Latex figure (float) alignment
297
#
298
# 'figure_align': 'htbp',
299
}
300
301
# Grouping the document tree into LaTeX files. List of tuples
302
# (source start file, target name, title,
303
# author, documentclass [howto, manual, or own class]).
304
latex_documents = [
305
(master_doc, 'PyTorchTutorials.tex', 'PyTorch Tutorials',
306
'Sasank, PyTorch contributors', 'manual'),
307
]
308
309
310
# -- Options for manual page output ---------------------------------------
311
312
# One entry per manual page. List of tuples
313
# (source start file, name, description, authors, manual section).
314
man_pages = [
315
(master_doc, 'pytorchtutorials', 'PyTorch Tutorials',
316
[author], 1)
317
]
318
319
320
# -- Options for Texinfo output -------------------------------------------
321
322
# Grouping the document tree into Texinfo files. List of tuples
323
# (source start file, target name, title, author,
324
# dir menu entry, description, category)
325
texinfo_documents = [
326
(master_doc, 'PyTorchTutorials', 'PyTorch Tutorials',
327
author, 'PyTorchTutorials', 'One line description of project.',
328
'Miscellaneous'),
329
]
330
331
html_css_files = [
332
'https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css',
333
'css/custom.css',
334
'css/custom2.css'
335
]
336
337
html_js_files = [
338
"js/custom.js",
339
]
340
341
def setup(app):
342
# NOTE: in Sphinx 1.8+ `html_css_files` is an official configuration value
343
# and can be moved outside of this function (and the setup(app) function
344
# can be deleted).
345
#html_css_files = [
346
# 'https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css',
347
# 'css/custom.css'
348
#]
349
# In Sphinx 1.8 it was renamed to `add_css_file`, 1.7 and prior it is
350
# `add_stylesheet` (deprecated in 1.8).
351
#add_css = getattr(app, 'add_css_file', app.add_stylesheet)
352
#for css_file in html_css_files:
353
# add_css(css_file)
354
# Custom CSS
355
#app.add_stylesheet('css/pytorch_theme.css')
356
# app.add_stylesheet('https://fonts.googleapis.com/css?family=Lato')
357
# Custom directives
358
app.add_directive('includenodoc', IncludeDirective)
359
app.add_directive('galleryitem', GalleryItemDirective)
360
app.add_directive('customgalleryitem', CustomGalleryItemDirective)
361
app.add_directive('customcarditem', CustomCardItemDirective)
362
app.add_directive('customcalloutitem', CustomCalloutItemDirective)
363
364