Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pytorch
GitHub Repository: pytorch/tutorials
Path: blob/main/conf.py
3697 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
33
sys.path.insert(0, os.path.abspath("."))
34
sys.path.insert(0, os.path.abspath("./.jenkins"))
35
import pytorch_sphinx_theme2
36
37
html_theme = "pytorch_sphinx_theme2"
38
html_theme_path = [pytorch_sphinx_theme2.get_html_theme_path()]
39
import distutils.file_util
40
import glob
41
import random
42
import re
43
import shutil
44
from pathlib import Path
45
46
import pandocfilters
47
import plotly.io as pio
48
import pypandoc
49
import torch
50
from get_sphinx_filenames import SPHINX_SHOULD_RUN
51
52
pio.renderers.default = "sphinx_gallery"
53
import multiprocessing
54
55
import sphinx_gallery.gen_rst
56
from redirects import redirects
57
58
59
# Monkey patch sphinx gallery to run each example in an isolated process so that
60
# we don't need to worry about examples changing global state.
61
#
62
# Alt option 1: Parallelism was added to sphinx gallery (a later version that we
63
# are not using yet) using joblib, but it seems to result in errors for us, and
64
# it has no effect if you set parallel = 1 (it will not put each file run into
65
# its own process and run singly) so you need parallel >= 2, and there may be
66
# tutorials that cannot be run in parallel.
67
#
68
# Alt option 2: Run sphinx gallery once per file (similar to how we shard in CI
69
# but with shard sizes of 1), but running sphinx gallery for each file has a
70
# ~5min overhead, resulting in the entire suite taking ~2x time
71
def call_fn(func, args, kwargs, result_queue):
72
try:
73
result = func(*args, **kwargs)
74
result_queue.put((True, result))
75
except Exception as e:
76
result_queue.put((False, str(e)))
77
78
79
def call_in_subprocess(func):
80
def wrapper(*args, **kwargs):
81
result_queue = multiprocessing.Queue()
82
p = multiprocessing.Process(
83
target=call_fn, args=(func, args, kwargs, result_queue)
84
)
85
p.start()
86
p.join()
87
success, result = result_queue.get()
88
if success:
89
return result
90
else:
91
raise RuntimeError(f"Error in subprocess: {result}")
92
93
return wrapper
94
95
96
# Windows does not support multiprocessing with fork and mac has issues with
97
# fork so we do not monkey patch sphinx gallery to run in subprocesses.
98
if (
99
os.getenv("TUTORIALS_ISOLATE_BUILD", "1") == "1"
100
and not sys.platform.startswith("win")
101
and not sys.platform == "darwin"
102
):
103
sphinx_gallery.gen_rst.generate_file_rst = call_in_subprocess(
104
sphinx_gallery.gen_rst.generate_file_rst
105
)
106
107
try:
108
import torchvision
109
except ImportError:
110
import warnings
111
112
warnings.warn('unable to load "torchvision" package')
113
114
rst_epilog = """
115
.. |edit| image:: /_static/pencil-16.png
116
:width: 16px
117
:height: 16px
118
"""
119
120
# -- General configuration ------------------------------------------------
121
122
# If your documentation needs a minimal Sphinx version, state it here.
123
#
124
# needs_sphinx = '1.0'
125
126
html_meta = {
127
"description": "Master PyTorch with our step-by-step tutorials for all skill levels. Start your journey to becoming a PyTorch expert today!",
128
"keywords": "PyTorch, tutorials, Getting Started, deep learning, AI",
129
"author": "PyTorch Contributors",
130
}
131
132
# Add any Sphinx extension module names here, as strings. They can be
133
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
134
# ones.
135
extensions = [
136
"sphinxcontrib.katex",
137
"sphinx.ext.intersphinx",
138
"sphinx_copybutton",
139
"sphinx_gallery.gen_gallery",
140
"sphinx_design",
141
"sphinx_sitemap",
142
"sphinx_reredirects",
143
"sphinxcontrib.mermaid",
144
]
145
146
intersphinx_mapping = {
147
"torch": ("https://docs.pytorch.org/docs/stable/", None),
148
"tensordict": ("https://docs.pytorch.org/tensordict/stable", None),
149
"torchrl": ("https://docs.pytorch.org/rl/stable", None),
150
"torchaudio": ("https://docs.pytorch.org/audio/stable/", None),
151
"torchtext": ("https://docs.pytorch.org/text/stable/", None),
152
"torchvision": ("https://docs.pytorch.org/vision/stable/", None),
153
}
154
155
html_meta = {
156
"description": "Master PyTorch with our step-by-step tutorials for all skill levels. Start your journey to becoming a PyTorch expert today!",
157
"keywords": "PyTorch, tutorials, Getting Started, deep learning, AI",
158
"author": "PyTorch Contributors",
159
}
160
161
162
163
# -- Sphinx-gallery configuration --------------------------------------------
164
165
sphinx_gallery_conf = {
166
"examples_dirs": [
167
"beginner_source",
168
"intermediate_source",
169
"advanced_source",
170
"recipes_source",
171
"unstable_source",
172
],
173
"gallery_dirs": ["beginner", "intermediate", "advanced", "recipes", "unstable"],
174
"filename_pattern": re.compile(SPHINX_SHOULD_RUN),
175
"promote_jupyter_magic": True,
176
"backreferences_dir": None,
177
"write_computation_times": True,
178
"download_all_examples": False,
179
"show_signature": False,
180
"first_notebook_cell": (
181
"# For tips on running notebooks in Google Colab, see\n"
182
"# https://docs.pytorch.org/tutorials/beginner/colab\n"
183
"%matplotlib inline"
184
),
185
"ignore_pattern": r"_torch_export_nightly_tutorial.py",
186
"pypandoc": {
187
"extra_args": ["--mathjax", "--toc"],
188
"filters": [".jenkins/custom_pandoc_filter.py"],
189
},
190
}
191
192
html_additional_pages = {
193
"404": "404.html",
194
}
195
196
197
html_baseurl = "https://docs.pytorch.org/tutorials/" # needed for sphinx-sitemap
198
sitemap_locales = [None]
199
sitemap_excludes = [
200
"search.html",
201
"genindex.html",
202
]
203
sitemap_url_scheme = "{link}"
204
205
html_theme_options = {
206
"navigation_with_keys": False,
207
"analytics_id": "GTM-T8XT4PS",
208
"logo": {
209
"text": "",
210
},
211
"icon_links": [
212
{
213
"name": "X",
214
"url": "https://x.com/PyTorch",
215
"icon": "fa-brands fa-x-twitter",
216
},
217
{
218
"name": "GitHub",
219
"url": "https://github.com/pytorch/tutorials",
220
"icon": "fa-brands fa-github",
221
},
222
{
223
"name": "Discourse",
224
"url": "https://dev-discuss.pytorch.org/",
225
"icon": "fa-brands fa-discourse",
226
},
227
{
228
"name": "PyPi",
229
"url": "https://pypi.org/project/torch/",
230
"icon": "fa-brands fa-python",
231
},
232
],
233
"use_edit_page_button": True,
234
"header_links_before_dropdown": 9,
235
"navbar_start": ["pytorch_version"],
236
"navbar_center": "navbar-nav",
237
"display_version": True,
238
"pytorch_project": "tutorials",
239
"canonical_url": "https://docs.pytorch.org/tutorials/",
240
}
241
242
theme_variables = pytorch_sphinx_theme2.get_theme_variables()
243
244
html_context = {
245
"theme_variables": theme_variables,
246
"display_github": True,
247
"github_url": "https://github.com",
248
"github_user": "pytorch",
249
"github_repo": "tutorials",
250
"feedback_url": "https://github.com/pytorch/tutorials",
251
"github_version": "main",
252
"doc_path": ".",
253
"library_links": theme_variables.get("library_links", []),
254
#"pytorch_project": "tutorials",
255
}
256
257
258
if os.getenv("GALLERY_PATTERN"):
259
# GALLERY_PATTERN is to be used when you want to work on a single
260
# tutorial. Previously this was fed into filename_pattern, but
261
# if you do that, you still end up parsing all of the other Python
262
# files which takes a few seconds. This strategy is better, as
263
# ignore_pattern also skips parsing.
264
# See https://github.com/sphinx-gallery/sphinx-gallery/issues/721
265
# for a more detailed description of the issue.
266
# GALLERY_PATTERN should be a regular expression.
267
sphinx_gallery_conf["ignore_pattern"] = (
268
r"^(?!.*" + os.getenv("GALLERY_PATTERN") + r")"
269
)
270
271
for i in range(len(sphinx_gallery_conf["examples_dirs"])):
272
gallery_dir = Path(sphinx_gallery_conf["gallery_dirs"][i])
273
source_dir = Path(sphinx_gallery_conf["examples_dirs"][i])
274
275
# Copy rst files from source dir to gallery dir
276
for f in source_dir.rglob("*.rst"):
277
f_dir = Path(f).parent
278
gallery_subdir_path = gallery_dir / f_dir.relative_to(source_dir)
279
gallery_subdir_path.mkdir(parents=True, exist_ok=True)
280
distutils.file_util.copy_file(f, gallery_subdir_path, update=True)
281
282
# Add any paths that contain templates here, relative to this directory.
283
templates_path = [
284
"_templates",
285
os.path.join(os.path.dirname(pytorch_sphinx_theme2.__file__), "templates"),
286
]
287
288
# The suffix(es) of source filenames.
289
# You can specify multiple suffix as a list of string:
290
#
291
# source_suffix = ['.rst', '.md']
292
source_suffix = ".rst"
293
294
# The master toctree document.
295
master_doc = "index"
296
297
# General information about the project.
298
project = "PyTorch Tutorials"
299
copyright = "2024, PyTorch"
300
author = "PyTorch contributors"
301
302
# The version info for the project you're documenting, acts as replacement for
303
# |version| and |release|, also used in various other places throughout the
304
# built documents.
305
#
306
# The short X.Y version.
307
version = "v" + str(torch.__version__)
308
# The full version, including alpha/beta/rc tags.
309
release = str(torch.__version__)
310
311
# The language for content autogenerated by Sphinx. Refer to documentation
312
# for a list of supported languages.
313
#
314
# This is also used if you do content translation via gettext catalogs.
315
# Usually you set "language" from the command line for these cases.
316
language = "en"
317
318
# List of patterns, relative to source directory, that match files and
319
# directories to ignore when looking for source files.
320
# This patterns also effect to html_static_path and html_extra_path
321
exclude_patterns = [
322
"_build",
323
"Thumbs.db",
324
".DS_Store",
325
"src/pytorch-sphinx-theme/docs*",
326
]
327
exclude_patterns += sphinx_gallery_conf["examples_dirs"]
328
exclude_patterns += ["*/index.rst"]
329
330
331
# Handling for HuggingFace Hub jinja templates
332
def handle_jinja_templates(app, docname, source):
333
if "huggingface_hub/templates" in docname:
334
# Replace Jinja templates with quoted strings
335
source[0] = re.sub(r"(\{\{.*?\}\})", r'"\1"', source[0])
336
337
338
# The name of the Pygments (syntax highlighting) style to use.
339
pygments_style = "sphinx"
340
341
# If true, `todo` and `todoList` produce output, else they produce nothing.
342
todo_include_todos = False
343
344
345
# -- Options for HTML output ----------------------------------------------
346
347
# The theme to use for HTML and HTML Help pages. See the documentation for
348
# a list of builtin themes.
349
#
350
# html_theme = 'alabaster'
351
352
# # Theme options are theme-specific and customize the look and feel of a theme
353
# # further. For a list of options available for each theme, see the
354
# # documentation.
355
# #
356
357
# html_theme_options = {
358
# 'page_width': '1000px',
359
# 'fixed_sidebar': True,
360
# 'code_font_size': '0.87em',
361
# 'sidebar_includehidden': True
362
# }
363
364
# # Add any paths that contain custom static files (such as style sheets) here,
365
# # relative to this directory. They are copied after the builtin static files,
366
# # so a file named "default.css" will overwrite the builtin "default.css".
367
html_static_path = ["_static"]
368
369
# # Custom sidebar templates, maps document names to template names.
370
# html_sidebars = {
371
# 'index': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html'],
372
# '**': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html']
373
# }
374
375
376
# -- Options for HTMLHelp output ------------------------------------------
377
378
# Output file base name for HTML help builder.
379
htmlhelp_basename = "PyTorchTutorialsdoc"
380
381
382
# -- Options for LaTeX output ---------------------------------------------
383
384
latex_elements = {
385
# The paper size ('letterpaper' or 'a4paper').
386
#
387
# 'papersize': 'letterpaper',
388
# The font size ('10pt', '11pt' or '12pt').
389
#
390
# 'pointsize': '10pt',
391
# Additional stuff for the LaTeX preamble.
392
#
393
# 'preamble': '',
394
# Latex figure (float) alignment
395
#
396
# 'figure_align': 'htbp',
397
}
398
399
# Grouping the document tree into LaTeX files. List of tuples
400
# (source start file, target name, title,
401
# author, documentclass [howto, manual, or own class]).
402
latex_documents = [
403
(
404
master_doc,
405
"PyTorchTutorials.tex",
406
"PyTorch Tutorials",
407
"Sasank, PyTorch contributors",
408
"manual",
409
),
410
]
411
412
413
# -- Options for manual page output ---------------------------------------
414
415
# One entry per manual page. List of tuples
416
# (source start file, name, description, authors, manual section).
417
man_pages = [(master_doc, "pytorchtutorials", "PyTorch Tutorials", [author], 1)]
418
419
420
# -- Options for Texinfo output -------------------------------------------
421
422
# Grouping the document tree into Texinfo files. List of tuples
423
# (source start file, target name, title, author,
424
# dir menu entry, description, category)
425
texinfo_documents = [
426
(
427
master_doc,
428
"PyTorchTutorials",
429
"PyTorch Tutorials",
430
author,
431
"PyTorchTutorials",
432
"One line description of project.",
433
"Miscellaneous",
434
),
435
]
436
437
html_css_files = [
438
"https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css",
439
]
440
441
442
def html_page_context(app, pagename, templatename, context, doctree):
443
# Check if the page is in gallery directories
444
for gallery_dir in sphinx_gallery_conf["gallery_dirs"]:
445
if pagename.startswith(gallery_dir):
446
# Get corresponding examples directory
447
examples_dir = sphinx_gallery_conf["examples_dirs"][
448
sphinx_gallery_conf["gallery_dirs"].index(gallery_dir)
449
]
450
451
# Calculate relative path within the gallery
452
rel_path = (
453
pagename[len(gallery_dir) + 1 :] if pagename != gallery_dir else ""
454
)
455
456
# Check for .py file in examples directory
457
py_path = os.path.join(app.srcdir, examples_dir, rel_path + ".py")
458
459
# If a .py file exists, this page was generated from Python
460
if os.path.exists(py_path):
461
context["display_github"] = False
462
return
463
464
# Enable for all other pages
465
context["display_github"] = True
466
467
468
def setup(app):
469
app.connect("source-read", handle_jinja_templates)
470
app.connect("html-page-context", html_page_context)
471
472