conf.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. #!/usr/bin/env python3
  2. #
  3. # PyTorch documentation build configuration file, created by
  4. # sphinx-quickstart on Fri Dec 23 13:31:47 2016.
  5. #
  6. # This file is execfile()d with the current directory set to its
  7. # containing dir.
  8. #
  9. # Note that not all possible configuration values are present in this
  10. # autogenerated file.
  11. #
  12. # All configuration values have a default; values that are commented out
  13. # serve to show the default.
  14. # If extensions (or modules to document with autodoc) are in another directory,
  15. # add these directories to sys.path here. If the directory is relative to the
  16. # documentation root, use os.path.abspath to make it absolute, like shown here.
  17. #
  18. # import os
  19. # import sys
  20. # sys.path.insert(0, os.path.abspath('.'))
  21. import os
  22. import sys
  23. import textwrap
  24. from copy import copy
  25. from pathlib import Path
  26. import pytorch_sphinx_theme
  27. import torchvision
  28. import torchvision.models as M
  29. from sphinx_gallery.sorting import ExplicitOrder
  30. from tabulate import tabulate
  31. sys.path.append(os.path.abspath("."))
  32. # -- General configuration ------------------------------------------------
  33. # Required version of sphinx is set from docs/requirements.txt
  34. # Add any Sphinx extension module names here, as strings. They can be
  35. # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
  36. # ones.
  37. extensions = [
  38. "sphinx.ext.autodoc",
  39. "sphinx.ext.autosummary",
  40. "sphinx.ext.doctest",
  41. "sphinx.ext.intersphinx",
  42. "sphinx.ext.todo",
  43. "sphinx.ext.mathjax",
  44. "sphinx.ext.napoleon",
  45. "sphinx.ext.viewcode",
  46. "sphinx.ext.duration",
  47. "sphinx_gallery.gen_gallery",
  48. "sphinx_copybutton",
  49. "beta_status",
  50. ]
  51. # We override sphinx-gallery's example header to prevent sphinx-gallery from
  52. # creating a note at the top of the renderred notebook.
  53. # https://github.com/sphinx-gallery/sphinx-gallery/blob/451ccba1007cc523f39cbcc960ebc21ca39f7b75/sphinx_gallery/gen_rst.py#L1267-L1271
  54. # This is because we also want to add a link to google collab, so we write our own note in each example.
  55. from sphinx_gallery import gen_rst
  56. gen_rst.EXAMPLE_HEADER = """
  57. .. DO NOT EDIT.
  58. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
  59. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
  60. .. "{0}"
  61. .. LINE NUMBERS ARE GIVEN BELOW.
  62. .. rst-class:: sphx-glr-example-title
  63. .. _sphx_glr_{1}:
  64. """
  65. class CustomGalleryExampleSortKey:
  66. # See https://sphinx-gallery.github.io/stable/configuration.html#sorting-gallery-examples
  67. # and https://github.com/sphinx-gallery/sphinx-gallery/blob/master/sphinx_gallery/sorting.py
  68. def __init__(self, src_dir):
  69. self.src_dir = src_dir
  70. transforms_subsection_order = [
  71. "plot_transforms_getting_started.py",
  72. "plot_transforms_illustrations.py",
  73. "plot_transforms_e2e.py",
  74. "plot_cutmix_mixup.py",
  75. "plot_custom_transforms.py",
  76. "plot_tv_tensors.py",
  77. "plot_custom_tv_tensors.py",
  78. ]
  79. def __call__(self, filename):
  80. if "gallery/transforms" in self.src_dir:
  81. try:
  82. return self.transforms_subsection_order.index(filename)
  83. except ValueError as e:
  84. raise ValueError(
  85. "Looks like you added an example in gallery/transforms? "
  86. "You need to specify its order in docs/source/conf.py. Look for CustomGalleryExampleSortKey."
  87. ) from e
  88. else:
  89. # For other subsections we just sort alphabetically by filename
  90. return filename
  91. sphinx_gallery_conf = {
  92. "examples_dirs": "../../gallery/", # path to your example scripts
  93. "gallery_dirs": "auto_examples", # path to where to save gallery generated output
  94. "subsection_order": ExplicitOrder(["../../gallery/transforms", "../../gallery/others"]),
  95. "backreferences_dir": "gen_modules/backreferences",
  96. "doc_module": ("torchvision",),
  97. "remove_config_comments": True,
  98. "ignore_pattern": "helpers.py",
  99. "within_subsection_order": CustomGalleryExampleSortKey,
  100. }
  101. napoleon_use_ivar = True
  102. napoleon_numpy_docstring = False
  103. napoleon_google_docstring = True
  104. # Add any paths that contain templates here, relative to this directory.
  105. templates_path = ["_templates"]
  106. # The suffix(es) of source filenames.
  107. # You can specify multiple suffix as a list of string:
  108. #
  109. source_suffix = {
  110. ".rst": "restructuredtext",
  111. }
  112. # The master toctree document.
  113. master_doc = "index"
  114. # General information about the project.
  115. project = "Torchvision"
  116. copyright = "2017-present, Torch Contributors"
  117. author = "Torch Contributors"
  118. # The version info for the project you're documenting, acts as replacement for
  119. # |version| and |release|, also used in various other places throughout the
  120. # built documents.
  121. # version: The short X.Y version.
  122. # release: The full version, including alpha/beta/rc tags.
  123. if os.environ.get("TORCHVISION_SANITIZE_VERSION_STR_IN_DOCS", None):
  124. # Turn 1.11.0aHASH into 1.11 (major.minor only)
  125. version = release = ".".join(torchvision.__version__.split(".")[:2])
  126. html_title = " ".join((project, version, "documentation"))
  127. else:
  128. version = f"main ({torchvision.__version__})"
  129. release = "main"
  130. # The language for content autogenerated by Sphinx. Refer to documentation
  131. # for a list of supported languages.
  132. #
  133. # This is also used if you do content translation via gettext catalogs.
  134. # Usually you set "language" from the command line for these cases.
  135. language = "en"
  136. # List of patterns, relative to source directory, that match files and
  137. # directories to ignore when looking for source files.
  138. # This patterns also effect to html_static_path and html_extra_path
  139. exclude_patterns = []
  140. # The name of the Pygments (syntax highlighting) style to use.
  141. pygments_style = "sphinx"
  142. # If true, `todo` and `todoList` produce output, else they produce nothing.
  143. todo_include_todos = True
  144. # -- Options for HTML output ----------------------------------------------
  145. # The theme to use for HTML and HTML Help pages. See the documentation for
  146. # a list of builtin themes.
  147. #
  148. html_theme = "pytorch_sphinx_theme"
  149. html_theme_path = [pytorch_sphinx_theme.get_html_theme_path()]
  150. # Theme options are theme-specific and customize the look and feel of a theme
  151. # further. For a list of options available for each theme, see the
  152. # documentation.
  153. #
  154. html_theme_options = {
  155. "collapse_navigation": False,
  156. "display_version": True,
  157. "logo_only": True,
  158. "pytorch_project": "docs",
  159. "navigation_with_keys": True,
  160. "analytics_id": "GTM-T8XT4PS",
  161. }
  162. html_logo = "_static/img/pytorch-logo-dark.svg"
  163. # Add any paths that contain custom static files (such as style sheets) here,
  164. # relative to this directory. They are copied after the builtin static files,
  165. # so a file named "default.css" will overwrite the builtin "default.css".
  166. html_static_path = ["_static"]
  167. # TODO: remove this once https://github.com/pytorch/pytorch_sphinx_theme/issues/125 is fixed
  168. html_css_files = [
  169. "css/custom_torchvision.css",
  170. ]
  171. # -- Options for HTMLHelp output ------------------------------------------
  172. # Output file base name for HTML help builder.
  173. htmlhelp_basename = "PyTorchdoc"
  174. autosummary_generate = True
  175. # -- Options for LaTeX output ---------------------------------------------
  176. latex_elements = {
  177. # The paper size ('letterpaper' or 'a4paper').
  178. #
  179. # 'papersize': 'letterpaper',
  180. # The font size ('10pt', '11pt' or '12pt').
  181. #
  182. # 'pointsize': '10pt',
  183. # Additional stuff for the LaTeX preamble.
  184. #
  185. # 'preamble': '',
  186. # Latex figure (float) alignment
  187. #
  188. # 'figure_align': 'htbp',
  189. }
  190. # Grouping the document tree into LaTeX files. List of tuples
  191. # (source start file, target name, title,
  192. # author, documentclass [howto, manual, or own class]).
  193. latex_documents = [
  194. (master_doc, "pytorch.tex", "torchvision Documentation", "Torch Contributors", "manual"),
  195. ]
  196. # -- Options for manual page output ---------------------------------------
  197. # One entry per manual page. List of tuples
  198. # (source start file, name, description, authors, manual section).
  199. man_pages = [(master_doc, "torchvision", "torchvision Documentation", [author], 1)]
  200. # -- Options for Texinfo output -------------------------------------------
  201. # Grouping the document tree into Texinfo files. List of tuples
  202. # (source start file, target name, title, author,
  203. # dir menu entry, description, category)
  204. texinfo_documents = [
  205. (
  206. master_doc,
  207. "torchvision",
  208. "torchvision Documentation",
  209. author,
  210. "torchvision",
  211. "One line description of project.",
  212. "Miscellaneous",
  213. ),
  214. ]
  215. # Example configuration for intersphinx: refer to the Python standard library.
  216. intersphinx_mapping = {
  217. "python": ("https://docs.python.org/3/", None),
  218. "torch": ("https://pytorch.org/docs/stable/", None),
  219. "numpy": ("https://numpy.org/doc/stable/", None),
  220. "PIL": ("https://pillow.readthedocs.io/en/stable/", None),
  221. "matplotlib": ("https://matplotlib.org/stable/", None),
  222. }
  223. # -- A patch that prevents Sphinx from cross-referencing ivar tags -------
  224. # See http://stackoverflow.com/a/41184353/3343043
  225. from docutils import nodes
  226. from sphinx import addnodes
  227. from sphinx.util.docfields import TypedField
  228. def patched_make_field(self, types, domain, items, **kw):
  229. # `kw` catches `env=None` needed for newer sphinx while maintaining
  230. # backwards compatibility when passed along further down!
  231. # type: (list, unicode, tuple) -> nodes.field # noqa: F821
  232. def handle_item(fieldarg, content):
  233. par = nodes.paragraph()
  234. par += addnodes.literal_strong("", fieldarg) # Patch: this line added
  235. # par.extend(self.make_xrefs(self.rolename, domain, fieldarg,
  236. # addnodes.literal_strong))
  237. if fieldarg in types:
  238. par += nodes.Text(" (")
  239. # NOTE: using .pop() here to prevent a single type node to be
  240. # inserted twice into the doctree, which leads to
  241. # inconsistencies later when references are resolved
  242. fieldtype = types.pop(fieldarg)
  243. if len(fieldtype) == 1 and isinstance(fieldtype[0], nodes.Text):
  244. typename = "".join(n.astext() for n in fieldtype)
  245. typename = typename.replace("int", "python:int")
  246. typename = typename.replace("long", "python:long")
  247. typename = typename.replace("float", "python:float")
  248. typename = typename.replace("type", "python:type")
  249. par.extend(self.make_xrefs(self.typerolename, domain, typename, addnodes.literal_emphasis, **kw))
  250. else:
  251. par += fieldtype
  252. par += nodes.Text(")")
  253. par += nodes.Text(" -- ")
  254. par += content
  255. return par
  256. fieldname = nodes.field_name("", self.label)
  257. if len(items) == 1 and self.can_collapse:
  258. fieldarg, content = items[0]
  259. bodynode = handle_item(fieldarg, content)
  260. else:
  261. bodynode = self.list_type()
  262. for fieldarg, content in items:
  263. bodynode += nodes.list_item("", handle_item(fieldarg, content))
  264. fieldbody = nodes.field_body("", bodynode)
  265. return nodes.field("", fieldname, fieldbody)
  266. TypedField.make_field = patched_make_field
  267. def inject_minigalleries(app, what, name, obj, options, lines):
  268. """Inject a minigallery into a docstring.
  269. This avoids having to manually write the .. minigallery directive for every item we want a minigallery for,
  270. as it would be easy to miss some.
  271. This callback is called after the .. auto directives (like ..autoclass) have been processed,
  272. and modifies the lines parameter inplace to add the .. minigallery that will show which examples
  273. are using which object.
  274. It's a bit hacky, but not *that* hacky when you consider that the recommended way is to do pretty much the same,
  275. but instead with templates using autosummary (which we don't want to use):
  276. (https://sphinx-gallery.github.io/stable/configuration.html#auto-documenting-your-api-with-links-to-examples)
  277. For docs on autodoc-process-docstring, see the autodoc docs:
  278. https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html
  279. """
  280. if what in ("class", "function"):
  281. lines.append(f".. minigallery:: {name}")
  282. lines.append(f" :add-heading: Examples using ``{name.split('.')[-1]}``:")
  283. # avoid heading entirely to avoid warning. As a bonud it actually renders better
  284. lines.append(" :heading-level: 9")
  285. lines.append("\n")
  286. def inject_weight_metadata(app, what, name, obj, options, lines):
  287. """This hook is used to generate docs for the models weights.
  288. Objects like ResNet18_Weights are enums with fields, where each field is a Weight object.
  289. Enums aren't easily documented in Python so the solution we're going for is to:
  290. - add an autoclass directive in the model's builder docstring, e.g.
  291. ```
  292. .. autoclass:: torchvision.models.ResNet34_Weights
  293. :members:
  294. ```
  295. (see resnet.py for an example)
  296. - then this hook is called automatically when building the docs, and it generates the text that gets
  297. used within the autoclass directive.
  298. """
  299. if getattr(obj, ".__name__", "").endswith(("_Weights", "_QuantizedWeights")):
  300. if len(obj) == 0:
  301. lines[:] = ["There are no available pre-trained weights."]
  302. return
  303. lines[:] = [
  304. "The model builder above accepts the following values as the ``weights`` parameter.",
  305. f"``{obj.__name__}.DEFAULT`` is equivalent to ``{obj.DEFAULT}``. You can also use strings, e.g. "
  306. f"``weights='DEFAULT'`` or ``weights='{str(list(obj)[0]).split('.')[1]}'``.",
  307. ]
  308. if obj.__doc__ != "An enumeration.":
  309. # We only show the custom enum doc if it was overridden. The default one from Python is "An enumeration"
  310. lines.append("")
  311. lines.append(obj.__doc__)
  312. lines.append("")
  313. for field in obj:
  314. meta = copy(field.meta)
  315. lines += [f"**{str(field)}**:", ""]
  316. lines += [meta.pop("_docs")]
  317. if field == obj.DEFAULT:
  318. lines += [f"Also available as ``{obj.__name__}.DEFAULT``."]
  319. lines += [""]
  320. table = []
  321. metrics = meta.pop("_metrics")
  322. for dataset, dataset_metrics in metrics.items():
  323. for metric_name, metric_value in dataset_metrics.items():
  324. table.append((f"{metric_name} (on {dataset})", str(metric_value)))
  325. for k, v in meta.items():
  326. if k in {"recipe", "license"}:
  327. v = f"`link <{v}>`__"
  328. elif k == "min_size":
  329. v = f"height={v[0]}, width={v[1]}"
  330. elif k in {"categories", "keypoint_names"} and isinstance(v, list):
  331. max_visible = 3
  332. v_sample = ", ".join(v[:max_visible])
  333. v = f"{v_sample}, ... ({len(v)-max_visible} omitted)" if len(v) > max_visible else v_sample
  334. elif k == "_ops":
  335. v = f"{v:.2f}"
  336. k = "GIPS" if obj.__name__.endswith("_QuantizedWeights") else "GFLOPS"
  337. elif k == "_file_size":
  338. k = "File size"
  339. v = f"{v:.1f} MB"
  340. table.append((str(k), str(v)))
  341. table = tabulate(table, tablefmt="rst")
  342. lines += [".. rst-class:: table-weights"] # Custom CSS class, see custom_torchvision.css
  343. lines += [".. table::", ""]
  344. lines += textwrap.indent(table, " " * 4).split("\n")
  345. lines.append("")
  346. lines.append(
  347. f"The inference transforms are available at ``{str(field)}.transforms`` and "
  348. f"perform the following preprocessing operations: {field.transforms().describe()}"
  349. )
  350. lines.append("")
  351. def generate_weights_table(module, table_name, metrics, dataset, include_patterns=None, exclude_patterns=None):
  352. weights_endswith = "_QuantizedWeights" if module.__name__.split(".")[-1] == "quantization" else "_Weights"
  353. weight_enums = [getattr(module, name) for name in dir(module) if name.endswith(weights_endswith)]
  354. weights = [w for weight_enum in weight_enums for w in weight_enum]
  355. if include_patterns is not None:
  356. weights = [w for w in weights if any(p in str(w) for p in include_patterns)]
  357. if exclude_patterns is not None:
  358. weights = [w for w in weights if all(p not in str(w) for p in exclude_patterns)]
  359. ops_name = "GIPS" if "QuantizedWeights" in weights_endswith else "GFLOPS"
  360. metrics_keys, metrics_names = zip(*metrics)
  361. column_names = ["Weight"] + list(metrics_names) + ["Params"] + [ops_name, "Recipe"] # Final column order
  362. column_names = [f"**{name}**" for name in column_names] # Add bold
  363. content = []
  364. for w in weights:
  365. row = [
  366. f":class:`{w} <{type(w).__name__}>`",
  367. *(w.meta["_metrics"][dataset][metric] for metric in metrics_keys),
  368. f"{w.meta['num_params']/1e6:.1f}M",
  369. f"{w.meta['_ops']:.2f}",
  370. f"`link <{w.meta['recipe']}>`__",
  371. ]
  372. content.append(row)
  373. column_widths = ["110"] + ["18"] * len(metrics_names) + ["18"] * 2 + ["10"]
  374. widths_table = " ".join(column_widths)
  375. table = tabulate(content, headers=column_names, tablefmt="rst")
  376. generated_dir = Path("generated")
  377. generated_dir.mkdir(exist_ok=True)
  378. with open(generated_dir / f"{table_name}_table.rst", "w+") as table_file:
  379. table_file.write(".. rst-class:: table-weights\n") # Custom CSS class, see custom_torchvision.css
  380. table_file.write(".. table::\n")
  381. table_file.write(f" :widths: {widths_table} \n\n")
  382. table_file.write(f"{textwrap.indent(table, ' ' * 4)}\n\n")
  383. generate_weights_table(
  384. module=M, table_name="classification", metrics=[("acc@1", "Acc@1"), ("acc@5", "Acc@5")], dataset="ImageNet-1K"
  385. )
  386. generate_weights_table(
  387. module=M.quantization,
  388. table_name="classification_quant",
  389. metrics=[("acc@1", "Acc@1"), ("acc@5", "Acc@5")],
  390. dataset="ImageNet-1K",
  391. )
  392. generate_weights_table(
  393. module=M.detection,
  394. table_name="detection",
  395. metrics=[("box_map", "Box MAP")],
  396. exclude_patterns=["Mask", "Keypoint"],
  397. dataset="COCO-val2017",
  398. )
  399. generate_weights_table(
  400. module=M.detection,
  401. table_name="instance_segmentation",
  402. metrics=[("box_map", "Box MAP"), ("mask_map", "Mask MAP")],
  403. dataset="COCO-val2017",
  404. include_patterns=["Mask"],
  405. )
  406. generate_weights_table(
  407. module=M.detection,
  408. table_name="detection_keypoint",
  409. metrics=[("box_map", "Box MAP"), ("kp_map", "Keypoint MAP")],
  410. dataset="COCO-val2017",
  411. include_patterns=["Keypoint"],
  412. )
  413. generate_weights_table(
  414. module=M.segmentation,
  415. table_name="segmentation",
  416. metrics=[("miou", "Mean IoU"), ("pixel_acc", "pixelwise Acc")],
  417. dataset="COCO-val2017-VOC-labels",
  418. )
  419. generate_weights_table(
  420. module=M.video, table_name="video", metrics=[("acc@1", "Acc@1"), ("acc@5", "Acc@5")], dataset="Kinetics-400"
  421. )
  422. def setup(app):
  423. app.connect("autodoc-process-docstring", inject_minigalleries)
  424. app.connect("autodoc-process-docstring", inject_weight_metadata)