Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pytorch
GitHub Repository: pytorch/tutorials
Path: blob/main/conf.py
1674 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
html_additional_pages = {
162
"404": "404.html",
163
}
164
165
# -- Sphinx-gallery configuration --------------------------------------------
166
167
sphinx_gallery_conf = {
168
"examples_dirs": [
169
"beginner_source",
170
"intermediate_source",
171
"advanced_source",
172
"recipes_source",
173
"unstable_source",
174
],
175
"gallery_dirs": ["beginner", "intermediate", "advanced", "recipes", "unstable"],
176
"filename_pattern": re.compile(SPHINX_SHOULD_RUN),
177
"promote_jupyter_magic": True,
178
"backreferences_dir": None,
179
"write_computation_times": True,
180
"download_all_examples": False,
181
"show_signature": False,
182
"first_notebook_cell": (
183
"# For tips on running notebooks in Google Colab, see\n"
184
"# https://pytorch.org/tutorials/beginner/colab\n"
185
"%matplotlib inline"
186
),
187
"ignore_pattern": r"_torch_export_nightly_tutorial.py",
188
"pypandoc": {
189
"extra_args": ["--mathjax", "--toc"],
190
"filters": [".jenkins/custom_pandoc_filter.py"],
191
},
192
}
193
194
html_baseurl = "https://pytorch.org/tutorials/" # needed for sphinx-sitemap
195
sitemap_locales = [None]
196
sitemap_excludes = [
197
"search.html",
198
"genindex.html",
199
]
200
sitemap_url_scheme = "{link}"
201
202
html_theme_options = {
203
"navigation_with_keys": False,
204
"analytics_id": "GTM-T8XT4PS",
205
"logo": {
206
"text": "",
207
},
208
"icon_links": [
209
{
210
"name": "X",
211
"url": "https://x.com/PyTorch",
212
"icon": "fa-brands fa-x-twitter",
213
},
214
{
215
"name": "GitHub",
216
"url": "https://github.com/pytorch/tutorials",
217
"icon": "fa-brands fa-github",
218
},
219
{
220
"name": "Discourse",
221
"url": "https://dev-discuss.pytorch.org/",
222
"icon": "fa-brands fa-discourse",
223
},
224
{
225
"name": "PyPi",
226
"url": "https://pypi.org/project/torch/",
227
"icon": "fa-brands fa-python",
228
},
229
],
230
"use_edit_page_button": True,
231
"header_links_before_dropdown": 9,
232
"navbar_start": ["pytorch_version"],
233
"navbar_center": "navbar-nav",
234
"display_version": True,
235
"pytorch_project": "tutorials",
236
}
237
238
theme_variables = pytorch_sphinx_theme2.get_theme_variables()
239
240
html_context = {
241
"theme_variables": theme_variables,
242
"display_github": True,
243
"github_url": "https://github.com",
244
"github_user": "pytorch",
245
"github_repo": "tutorials",
246
"feedback_url": "https://github.com/pytorch/tutorials",
247
"github_version": "main",
248
"doc_path": ".",
249
"library_links": theme_variables.get("library_links", []),
250
#"pytorch_project": "tutorials",
251
}
252
253
254
if os.getenv("GALLERY_PATTERN"):
255
# GALLERY_PATTERN is to be used when you want to work on a single
256
# tutorial. Previously this was fed into filename_pattern, but
257
# if you do that, you still end up parsing all of the other Python
258
# files which takes a few seconds. This strategy is better, as
259
# ignore_pattern also skips parsing.
260
# See https://github.com/sphinx-gallery/sphinx-gallery/issues/721
261
# for a more detailed description of the issue.
262
sphinx_gallery_conf["ignore_pattern"] = (
263
r"/(?!" + re.escape(os.getenv("GALLERY_PATTERN")) + r")[^/]+$"
264
)
265
266
for i in range(len(sphinx_gallery_conf["examples_dirs"])):
267
gallery_dir = Path(sphinx_gallery_conf["gallery_dirs"][i])
268
source_dir = Path(sphinx_gallery_conf["examples_dirs"][i])
269
270
# Copy rst files from source dir to gallery dir
271
for f in source_dir.rglob("*.rst"):
272
f_dir = Path(f).parent
273
gallery_subdir_path = gallery_dir / f_dir.relative_to(source_dir)
274
gallery_subdir_path.mkdir(parents=True, exist_ok=True)
275
distutils.file_util.copy_file(f, gallery_subdir_path, update=True)
276
277
# Add any paths that contain templates here, relative to this directory.
278
templates_path = [
279
"_templates",
280
os.path.join(os.path.dirname(pytorch_sphinx_theme2.__file__), "templates"),
281
]
282
283
# The suffix(es) of source filenames.
284
# You can specify multiple suffix as a list of string:
285
#
286
# source_suffix = ['.rst', '.md']
287
source_suffix = ".rst"
288
289
# The master toctree document.
290
master_doc = "index"
291
292
# General information about the project.
293
project = "PyTorch Tutorials"
294
copyright = "2024, PyTorch"
295
author = "PyTorch contributors"
296
297
# The version info for the project you're documenting, acts as replacement for
298
# |version| and |release|, also used in various other places throughout the
299
# built documents.
300
#
301
# The short X.Y version.
302
version = "v" + str(torch.__version__)
303
# The full version, including alpha/beta/rc tags.
304
release = str(torch.__version__)
305
306
# The language for content autogenerated by Sphinx. Refer to documentation
307
# for a list of supported languages.
308
#
309
# This is also used if you do content translation via gettext catalogs.
310
# Usually you set "language" from the command line for these cases.
311
language = "en"
312
313
# List of patterns, relative to source directory, that match files and
314
# directories to ignore when looking for source files.
315
# This patterns also effect to html_static_path and html_extra_path
316
exclude_patterns = [
317
"_build",
318
"Thumbs.db",
319
".DS_Store",
320
"src/pytorch-sphinx-theme/docs*",
321
]
322
exclude_patterns += sphinx_gallery_conf["examples_dirs"]
323
exclude_patterns += ["*/index.rst"]
324
325
326
# Handling for HuggingFace Hub jinja templates
327
def handle_jinja_templates(app, docname, source):
328
if "huggingface_hub/templates" in docname:
329
# Replace Jinja templates with quoted strings
330
source[0] = re.sub(r"(\{\{.*?\}\})", r'"\1"', source[0])
331
332
333
# The name of the Pygments (syntax highlighting) style to use.
334
pygments_style = "sphinx"
335
336
# If true, `todo` and `todoList` produce output, else they produce nothing.
337
todo_include_todos = False
338
339
340
# -- Options for HTML output ----------------------------------------------
341
342
# The theme to use for HTML and HTML Help pages. See the documentation for
343
# a list of builtin themes.
344
#
345
# html_theme = 'alabaster'
346
347
# # Theme options are theme-specific and customize the look and feel of a theme
348
# # further. For a list of options available for each theme, see the
349
# # documentation.
350
# #
351
352
# html_theme_options = {
353
# 'page_width': '1000px',
354
# 'fixed_sidebar': True,
355
# 'code_font_size': '0.87em',
356
# 'sidebar_includehidden': True
357
# }
358
359
# # Add any paths that contain custom static files (such as style sheets) here,
360
# # relative to this directory. They are copied after the builtin static files,
361
# # so a file named "default.css" will overwrite the builtin "default.css".
362
html_static_path = ["_static"]
363
364
# # Custom sidebar templates, maps document names to template names.
365
# html_sidebars = {
366
# 'index': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html'],
367
# '**': ['sidebarlogo.html', 'globaltoc.html', 'searchbox.html', 'sourcelink.html']
368
# }
369
370
371
# -- Options for HTMLHelp output ------------------------------------------
372
373
# Output file base name for HTML help builder.
374
htmlhelp_basename = "PyTorchTutorialsdoc"
375
376
377
# -- Options for LaTeX output ---------------------------------------------
378
379
latex_elements = {
380
# The paper size ('letterpaper' or 'a4paper').
381
#
382
# 'papersize': 'letterpaper',
383
# The font size ('10pt', '11pt' or '12pt').
384
#
385
# 'pointsize': '10pt',
386
# Additional stuff for the LaTeX preamble.
387
#
388
# 'preamble': '',
389
# Latex figure (float) alignment
390
#
391
# 'figure_align': 'htbp',
392
}
393
394
# Grouping the document tree into LaTeX files. List of tuples
395
# (source start file, target name, title,
396
# author, documentclass [howto, manual, or own class]).
397
latex_documents = [
398
(
399
master_doc,
400
"PyTorchTutorials.tex",
401
"PyTorch Tutorials",
402
"Sasank, PyTorch contributors",
403
"manual",
404
),
405
]
406
407
408
# -- Options for manual page output ---------------------------------------
409
410
# One entry per manual page. List of tuples
411
# (source start file, name, description, authors, manual section).
412
man_pages = [(master_doc, "pytorchtutorials", "PyTorch Tutorials", [author], 1)]
413
414
415
# -- Options for Texinfo output -------------------------------------------
416
417
# Grouping the document tree into Texinfo files. List of tuples
418
# (source start file, target name, title, author,
419
# dir menu entry, description, category)
420
texinfo_documents = [
421
(
422
master_doc,
423
"PyTorchTutorials",
424
"PyTorch Tutorials",
425
author,
426
"PyTorchTutorials",
427
"One line description of project.",
428
"Miscellaneous",
429
),
430
]
431
432
html_css_files = [
433
"https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css",
434
]
435
436
437
def html_page_context(app, pagename, templatename, context, doctree):
438
# Check if the page is in gallery directories
439
for gallery_dir in sphinx_gallery_conf["gallery_dirs"]:
440
if pagename.startswith(gallery_dir):
441
# Get corresponding examples directory
442
examples_dir = sphinx_gallery_conf["examples_dirs"][
443
sphinx_gallery_conf["gallery_dirs"].index(gallery_dir)
444
]
445
446
# Calculate relative path within the gallery
447
rel_path = (
448
pagename[len(gallery_dir) + 1 :] if pagename != gallery_dir else ""
449
)
450
451
# Check for .py file in examples directory
452
py_path = os.path.join(app.srcdir, examples_dir, rel_path + ".py")
453
454
# If a .py file exists, this page was generated from Python
455
if os.path.exists(py_path):
456
context["display_github"] = False
457
return
458
459
# Enable for all other pages
460
context["display_github"] = True
461
462
463
def setup(app):
464
app.connect("source-read", handle_jinja_templates)
465
app.connect("html-page-context", html_page_context)
466
467