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