Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pytorch
GitHub Repository: pytorch/tutorials
Path: blob/main/conf.py
2096 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
sphinx_gallery_conf["ignore_pattern"] = (
267
r"/(?!" + re.escape(os.getenv("GALLERY_PATTERN")) + r")[^/]+$"
268
)
269
270
for i in range(len(sphinx_gallery_conf["examples_dirs"])):
271
gallery_dir = Path(sphinx_gallery_conf["gallery_dirs"][i])
272
source_dir = Path(sphinx_gallery_conf["examples_dirs"][i])
273
274
# Copy rst files from source dir to gallery dir
275
for f in source_dir.rglob("*.rst"):
276
f_dir = Path(f).parent
277
gallery_subdir_path = gallery_dir / f_dir.relative_to(source_dir)
278
gallery_subdir_path.mkdir(parents=True, exist_ok=True)
279
distutils.file_util.copy_file(f, gallery_subdir_path, update=True)
280
281
# Add any paths that contain templates here, relative to this directory.
282
templates_path = [
283
"_templates",
284
os.path.join(os.path.dirname(pytorch_sphinx_theme2.__file__), "templates"),
285
]
286
287
# The suffix(es) of source filenames.
288
# You can specify multiple suffix as a list of string:
289
#
290
# source_suffix = ['.rst', '.md']
291
source_suffix = ".rst"
292
293
# The master toctree document.
294
master_doc = "index"
295
296
# General information about the project.
297
project = "PyTorch Tutorials"
298
copyright = "2024, PyTorch"
299
author = "PyTorch contributors"
300
301
# The version info for the project you're documenting, acts as replacement for
302
# |version| and |release|, also used in various other places throughout the
303
# built documents.
304
#
305
# The short X.Y version.
306
version = "v" + str(torch.__version__)
307
# The full version, including alpha/beta/rc tags.
308
release = str(torch.__version__)
309
310
# The language for content autogenerated by Sphinx. Refer to documentation
311
# for a list of supported languages.
312
#
313
# This is also used if you do content translation via gettext catalogs.
314
# Usually you set "language" from the command line for these cases.
315
language = "en"
316
317
# List of patterns, relative to source directory, that match files and
318
# directories to ignore when looking for source files.
319
# This patterns also effect to html_static_path and html_extra_path
320
exclude_patterns = [
321
"_build",
322
"Thumbs.db",
323
".DS_Store",
324
"src/pytorch-sphinx-theme/docs*",
325
]
326
exclude_patterns += sphinx_gallery_conf["examples_dirs"]
327
exclude_patterns += ["*/index.rst"]
328
329
330
# Handling for HuggingFace Hub jinja templates
331
def handle_jinja_templates(app, docname, source):
332
if "huggingface_hub/templates" in docname:
333
# Replace Jinja templates with quoted strings
334
source[0] = re.sub(r"(\{\{.*?\}\})", r'"\1"', source[0])
335
336
337
# The name of the Pygments (syntax highlighting) style to use.
338
pygments_style = "sphinx"
339
340
# If true, `todo` and `todoList` produce output, else they produce nothing.
341
todo_include_todos = False
342
343
344
# -- Options for HTML output ----------------------------------------------
345
346
# The theme to use for HTML and HTML Help pages. See the documentation for
347
# a list of builtin themes.
348
#
349
# html_theme = 'alabaster'
350
351
# # Theme options are theme-specific and customize the look and feel of a theme
352
# # further. For a list of options available for each theme, see the
353
# # documentation.
354
# #
355
356
# html_theme_options = {
357
# 'page_width': '1000px',
358
# 'fixed_sidebar': True,
359
# 'code_font_size': '0.87em',
360
# 'sidebar_includehidden': True
361
# }
362
363
# # Add any paths that contain custom static files (such as style sheets) here,
364
# # relative to this directory. They are copied after the builtin static files,
365
# # so a file named "default.css" will overwrite the builtin "default.css".
366
html_static_path = ["_static"]
367
368
# # Custom sidebar templates, maps document names to template names.
369
# html_sidebars = {
370
# 'index': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html'],
371
# '**': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html']
372
# }
373
374
375
# -- Options for HTMLHelp output ------------------------------------------
376
377
# Output file base name for HTML help builder.
378
htmlhelp_basename = "PyTorchTutorialsdoc"
379
380
381
# -- Options for LaTeX output ---------------------------------------------
382
383
latex_elements = {
384
# The paper size ('letterpaper' or 'a4paper').
385
#
386
# 'papersize': 'letterpaper',
387
# The font size ('10pt', '11pt' or '12pt').
388
#
389
# 'pointsize': '10pt',
390
# Additional stuff for the LaTeX preamble.
391
#
392
# 'preamble': '',
393
# Latex figure (float) alignment
394
#
395
# 'figure_align': 'htbp',
396
}
397
398
# Grouping the document tree into LaTeX files. List of tuples
399
# (source start file, target name, title,
400
# author, documentclass [howto, manual, or own class]).
401
latex_documents = [
402
(
403
master_doc,
404
"PyTorchTutorials.tex",
405
"PyTorch Tutorials",
406
"Sasank, PyTorch contributors",
407
"manual",
408
),
409
]
410
411
412
# -- Options for manual page output ---------------------------------------
413
414
# One entry per manual page. List of tuples
415
# (source start file, name, description, authors, manual section).
416
man_pages = [(master_doc, "pytorchtutorials", "PyTorch Tutorials", [author], 1)]
417
418
419
# -- Options for Texinfo output -------------------------------------------
420
421
# Grouping the document tree into Texinfo files. List of tuples
422
# (source start file, target name, title, author,
423
# dir menu entry, description, category)
424
texinfo_documents = [
425
(
426
master_doc,
427
"PyTorchTutorials",
428
"PyTorch Tutorials",
429
author,
430
"PyTorchTutorials",
431
"One line description of project.",
432
"Miscellaneous",
433
),
434
]
435
436
html_css_files = [
437
"https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css",
438
]
439
440
441
def html_page_context(app, pagename, templatename, context, doctree):
442
# Check if the page is in gallery directories
443
for gallery_dir in sphinx_gallery_conf["gallery_dirs"]:
444
if pagename.startswith(gallery_dir):
445
# Get corresponding examples directory
446
examples_dir = sphinx_gallery_conf["examples_dirs"][
447
sphinx_gallery_conf["gallery_dirs"].index(gallery_dir)
448
]
449
450
# Calculate relative path within the gallery
451
rel_path = (
452
pagename[len(gallery_dir) + 1 :] if pagename != gallery_dir else ""
453
)
454
455
# Check for .py file in examples directory
456
py_path = os.path.join(app.srcdir, examples_dir, rel_path + ".py")
457
458
# If a .py file exists, this page was generated from Python
459
if os.path.exists(py_path):
460
context["display_github"] = False
461
return
462
463
# Enable for all other pages
464
context["display_github"] = True
465
466
467
def setup(app):
468
app.connect("source-read", handle_jinja_templates)
469
app.connect("html-page-context", html_page_context)
470
471