Skip to content

Commit

Permalink
更新文档
Browse files Browse the repository at this point in the history
  • Loading branch information
liuxinwei committed Jan 6, 2025
1 parent a202c71 commit f61b58b
Show file tree
Hide file tree
Showing 111 changed files with 799 additions and 143 deletions.
145 changes: 145 additions & 0 deletions doc/_ext/gallery_directive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
"""A directive to generate a gallery of images from structured data.
Generating a gallery of images that are all the same size is a common
pattern in documentation, and this can be cumbersome if the gallery is
generated programmatically. This directive wraps this particular use-case
in a helper-directive to generate it with a single YAML configuration file.
It currently exists for maintainers of the pydata-sphinx-theme,
but might be abstracted into a standalone package if it proves useful.
"""

from pathlib import Path
from typing import Any, ClassVar, Dict, List

from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.application import Sphinx
from sphinx.util import logging
from sphinx.util.docutils import SphinxDirective
from yaml import safe_load


logger = logging.getLogger(__name__)


TEMPLATE_GRID = """
`````{{grid}} {columns}
{options}
{content}
`````
"""

GRID_CARD = """
````{{grid-item-card}} {title}
{options}
{content}
````
"""


class GalleryGridDirective(SphinxDirective):
"""A directive to show a gallery of images and links in a Bootstrap grid.
The grid can be generated from a YAML file that contains a list of items, or
from the content of the directive (also formatted in YAML). Use the parameter
"class-card" to add an additional CSS class to all cards. When specifying the grid
items, you can use all parameters from "grid-item-card" directive to customize
individual cards + ["image", "header", "content", "title"].
Danger:
This directive can only be used in the context of a Myst documentation page as
the templates use Markdown flavored formatting.
"""

name = "gallery-grid"
has_content = True
required_arguments = 0
optional_arguments = 1
final_argument_whitespace = True
option_spec: ClassVar[dict[str, Any]] = {
# A class to be added to the resulting container
"grid-columns": directives.unchanged,
"class-container": directives.unchanged,
"class-card": directives.unchanged,
}

def run(self) -> List[nodes.Node]:
"""Create the gallery grid."""
if self.arguments:
# If an argument is given, assume it's a path to a YAML file
# Parse it and load it into the directive content
path_data_rel = Path(self.arguments[0])
path_doc, _ = self.get_source_info()
path_doc = Path(path_doc).parent
path_data = (path_doc / path_data_rel).resolve()
if not path_data.exists():
logger.info("Could not find grid data at %s.", path_data)
nodes.text("No grid data found at {path_data}.")
return
yaml_string = path_data.read_text()
else:
yaml_string = "\n".join(self.content)

# Use all the element with an img-bottom key as sites to show
# and generate a card item for each of them
grid_items = []
for item in safe_load(yaml_string):
# remove parameters that are not needed for the card options
title = item.pop("title", "")

# build the content of the card using some extra parameters
header = f"{item.pop('header')} \n^^^ \n" if "header" in item else ""
image = f"![image]({item.pop('image')}) \n" if "image" in item else ""
content = f"{item.pop('content')} \n" if "content" in item else ""

# optional parameter that influence all cards
if "class-card" in self.options:
item["class-card"] = self.options["class-card"]

loc_options_str = "\n".join(f":{k}: {v}" for k, v in item.items()) + " \n"

card = GRID_CARD.format(
options=loc_options_str, content=header + image + content, title=title
)
grid_items.append(card)

# Parse the template with Sphinx Design to create an output container
# Prep the options for the template grid
class_ = "gallery-directive" + f' {self.options.get("class-container", "")}'
options = {"gutter": 2, "class-container": class_}
options_str = "\n".join(f":{k}: {v}" for k, v in options.items())

# Create the directive string for the grid
grid_directive = TEMPLATE_GRID.format(
columns=self.options.get("grid-columns", "1 2 3 4"),
options=options_str,
content="\n".join(grid_items),
)

# Parse content as a directive so Sphinx Design processes it
container = nodes.container()
self.state.nested_parse([grid_directive], 0, container)

# Sphinx Design outputs a container too, so just use that
return [container.children[0]]


def setup(app: Sphinx) -> Dict[str, Any]:
"""Add custom configuration to sphinx app.
Args:
app: the Sphinx application
Returns:
the 2 parallel parameters set to ``True``.
"""
app.add_directive("gallery-grid", GalleryGridDirective)

return {
"parallel_read_safe": True,
"parallel_write_safe": True,
}
1 change: 1 addition & 0 deletions doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
'sphinx_copybutton', # 为代码块添加复制按钮。
"sphinx_comments", # 为 Sphinx 文档添加评论和注释功能。
"sphinx.ext.napoleon", # 支持 Google 和 Numpy 风格的文档字符串
"_ext.gallery_directive", # 自定义画廊指令
]

# 在此添加包含模板的任何路径,相对于此目录。
Expand Down
1 change: 0 additions & 1 deletion doc/test/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

```{toctree}
tutorials/index
frontend/index
faqs/index
dev/index
old/index
Expand Down
1 change: 0 additions & 1 deletion doc/test/tutorials/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,5 @@

```{toctree}
android/index
msc/index
aq/index
```
10 changes: 10 additions & 0 deletions doc/topics/gallery/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# TVM 长廊

```{gallery-grid}
:grid-columns: 1 2 2 3
- header: "{fas}`book;pst-color-primary` {daobook}`xgrammar` 中文文档"
content: "XGrammar 开源解决方案,旨在实现灵活、便携且快速的结构化生成。该项目的使命是将灵活的无开销结构化生成带到每一个角落。"
- header: "{fas}`book;pst-color-primary` {daobook}`mlc-llm` 中文文档"
content: "MLC LLM 是机器学习编译器和高性能部署引擎,专为大型语言模型设计。该项目的使命是让每个人都能在自己的平台上原生地开发、优化和部署 AI 模型。"
```
3 changes: 3 additions & 0 deletions doc/topics/index.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# 专题

```{toctree}
gallery/index
mlc/index
extension/index
register/index
other/index
```

115 changes: 115 additions & 0 deletions doc/topics/mlc/cc-jit-load.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# {func}`mlc.cc.jit_load`"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import mlc\n",
"import mlc.dataclasses as mlcd\n",
"import pytest\n",
"from mlc._cython import SYSTEM"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Executing command: /usr/bin/ccache /usr/bin/x86_64-linux-gnu-g++-11 -O2 -g -shared -fPIC -std=c++17 -DMLC_COMPILATION=1 -fvisibility=hidden -o main.so -I/media/pc/data/lxw/ai/mlc-python/include -I/media/pc/data/lxw/ai/mlc-python/3rdparty/dlpack/include _mlc_source_0.cc\n"
]
}
],
"source": [
"mlc.cc.jit_load(\"\"\"\n",
"#include <mlc/core/all.h>\n",
"#include <string>\n",
"\n",
"struct MyObj : public mlc::Object {\n",
"mlc::Str x;\n",
"int32_t y;\n",
"MyObj(mlc::Str x, int y) : x(x), y(y) {}\n",
"int32_t YPlusOne() const { return y + 1; }\n",
"MLC_DEF_DYN_TYPE(MyObj, Object, \"mlc.MyObj\");\n",
"};\n",
"\n",
"struct MyObjRef : public mlc::ObjectRef {\n",
"MLC_DEF_OBJ_REF(MyObjRef, MyObj, mlc::ObjectRef)\n",
" .Field(\"x\", &MyObj::x)\n",
" .FieldReadOnly(\"y\", &MyObj::y)\n",
" .StaticFn(\"__init__\", mlc::InitOf<MyObj, mlc::Str, int32_t>)\n",
" .MemFn(\"YPlusOne\", &MyObj::YPlusOne);\n",
"};\n",
"\"\"\")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"@mlcd.c_class(\"mlc.MyObj\")\n",
"class MyObj(mlc.Object):\n",
" x: str\n",
" y: int\n",
"\n",
" def YPlusOne(self) -> int:\n",
" return type(self)._C(b\"YPlusOne\", self)\n",
"\n",
"obj = MyObj(\"hello\", 42)\n",
"assert obj.x == \"hello\"\n",
"assert obj.y == 42\n",
"assert obj.YPlusOne() == 43\n",
"\n",
"obj.x = \"world\"\n",
"assert obj.x == \"world\"\n",
"with pytest.raises(TypeError):\n",
" obj.x = 42 # type: ignore[assignment]\n",
"with pytest.raises(AttributeError):\n",
" obj.y = 42\n",
"del obj"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "ai",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
6 changes: 6 additions & 0 deletions doc/topics/mlc/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# MLC

```{toctree}
mlc-python
cc-jit-load
```
Loading

0 comments on commit f61b58b

Please sign in to comment.