update_doc.py 6.44 KB
Newer Older
Merve Noyan's avatar
Merve Noyan committed
1
2
import subprocess
import argparse
3
import ast
4
5
import json
import os
Merve Noyan's avatar
Merve Noyan committed
6

7
8
TEMPLATE = """
# Supported Models and Hardware
Merve Noyan's avatar
Merve Noyan committed
9

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Text Generation Inference enables serving optimized models on specific hardware for the highest performance. The following sections list which models are hardware are supported.

## Supported Models

SUPPORTED_MODELS

If the above list lacks the model you would like to serve, depending on the model's pipeline type, you can try to initialize and serve the model anyways to see how well it performs, but performance isn't guaranteed for non-optimized models:

```python
# for causal LMs/text-generation models
AutoModelForCausalLM.from_pretrained(<model>, device_map="auto")`
# or, for text-to-text generation models
AutoModelForSeq2SeqLM.from_pretrained(<model>, device_map="auto")
```

If you wish to serve a supported model that already exists on a local folder, just point to the local folder.

```bash
text-generation-launcher --model-id <PATH-TO-LOCAL-BLOOM>
```
"""
Merve Noyan's avatar
Merve Noyan committed
31
32


33
def check_cli(check: bool):
34
35
36
    output = subprocess.check_output(["text-generation-launcher", "--help"]).decode(
        "utf-8"
    )
37

38
    wrap_code_blocks_flag = "<!-- WRAP CODE BLOCKS -->"
39
40
41
42
43
44
45
46
    final_doc = f"# Text-generation-launcher arguments\n\n{wrap_code_blocks_flag}\n\n"

    lines = output.split("\n")

    header = ""
    block = []
    for line in lines:
        if line.startswith("  -") or line.startswith("      -"):
OlivierDehaene's avatar
OlivierDehaene committed
47
            rendered_block = "\n".join(block)
48
49
50
51
52
53
            if header:
                final_doc += f"## {header}\n```shell\n{rendered_block}\n```\n"
            else:
                final_doc += f"```shell\n{rendered_block}\n```\n"
            block = []
            tokens = line.split("<")
OlivierDehaene's avatar
OlivierDehaene committed
54
            if len(tokens) > 1:
55
56
57
58
59
60
61
                header = tokens[-1][:-1]
            else:
                header = line.split("--")[-1]
            header = header.upper().replace("-", "_")

        block.append(line)

OlivierDehaene's avatar
OlivierDehaene committed
62
    rendered_block = "\n".join(block)
63
64
    final_doc += f"## {header}\n```shell\n{rendered_block}\n```\n"
    block = []
Merve Noyan's avatar
Merve Noyan committed
65
66

    filename = "docs/source/basic_tutorials/launcher.md"
67
    if check:
Merve Noyan's avatar
Merve Noyan committed
68
69
70
71
72
73
        with open(filename, "r") as f:
            doc = f.read()
            if doc != final_doc:
                tmp = "launcher.md"
                with open(tmp, "w") as g:
                    g.write(final_doc)
74
75
76
                diff = subprocess.run(
                    ["diff", tmp, filename], capture_output=True
                ).stdout.decode("utf-8")
Merve Noyan's avatar
Merve Noyan committed
77
                print(diff)
78
                raise Exception(
79
                    "Cli arguments Doc is not up-to-date, run `python update_doc.py` in order to update it"
80
                )
Merve Noyan's avatar
Merve Noyan committed
81
82
83
84
    else:
        with open(filename, "w") as f:
            f.write(final_doc)

85

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def check_supported_models(check: bool):
    filename = "server/text_generation_server/models/__init__.py"
    with open(filename, "r") as f:
        tree = ast.parse(f.read())

    enum_def = [
        x for x in tree.body if isinstance(x, ast.ClassDef) and x.name == "ModelType"
    ][0]
    _locals = {}
    _globals = {}
    exec(f"import enum\n{ast.unparse(enum_def)}", _globals, _locals)
    ModelType = _locals["ModelType"]
    list_string = ""
    for data in ModelType:
        list_string += f"- [{data.value['name']}]({data.value['url']})"
        if data.value.get("multimodal", None):
            list_string += " (Multimodal)"
        list_string += "\n"

    final_doc = TEMPLATE.replace("SUPPORTED_MODELS", list_string)

    filename = "docs/source/supported_models.md"
    if check:
        with open(filename, "r") as f:
            doc = f.read()
            if doc != final_doc:
                tmp = "supported.md"
                with open(tmp, "w") as g:
                    g.write(final_doc)
                diff = subprocess.run(
                    ["diff", tmp, filename], capture_output=True
                ).stdout.decode("utf-8")
                print(diff)
                raise Exception(
                    "Supported models is not up-to-date, run `python update_doc.py` in order to update it"
                )
    else:
        with open(filename, "w") as f:
            f.write(final_doc)


127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def get_openapi_schema():
    try:
        output = subprocess.check_output(["text-generation-router", "print-schema"])
        return json.loads(output)
    except subprocess.CalledProcessError as e:
        print(f"Error running text-generation-router print-schema: {e}")
        raise SystemExit(1)
    except json.JSONDecodeError:
        print("Error: Invalid JSON received from text-generation-router print-schema")
        raise SystemExit(1)


def check_openapi(check: bool):
    new_openapi_data = get_openapi_schema()
    filename = "docs/openapi.json"
    tmp_filename = "openapi_tmp.json"

    with open(tmp_filename, "w") as f:
        json.dump(new_openapi_data, f, indent=2)

    if check:
        diff = subprocess.run(
            [
                "diff",
                # allow for trailing whitespace since it's not significant
                # and the precommit hook will remove it
                "--ignore-trailing-space",
                tmp_filename,
                filename,
            ],
            capture_output=True,
158
        ).stdout.decode("utf-8")
159
160
161
162
163
164
165
166
167
168
169
        os.remove(tmp_filename)

        if diff:
            print(diff)
            raise Exception(
                "OpenAPI documentation is not up-to-date, run `python update_doc.py` in order to update it"
            )

    else:
        os.rename(tmp_filename, filename)
        print("OpenAPI documentation updated.")
170
171
172
173
174
175
176
177
178
179
    errors = subprocess.run(
        [
            "swagger-cli",
            # allow for trailing whitespace since it's not significant
            # and the precommit hook will remove it
            "validate",
            filename,
        ],
        capture_output=True,
    ).stderr.decode("utf-8")
180
181
182
    # The openapi specs fails on `exclusive_minimum` which is expected to be a boolean where
    # utoipa outputs a value instead: https://github.com/juhaku/utoipa/issues/969
    if not errors.startswith("Swagger schema validation failed."):
183
184
185
186
187
        print(errors)
        raise Exception(
            f"OpenAPI documentation is invalid, `swagger-cli validate` showed some error:\n {errors}"
        )
    return True
188
189


190
191
192
193
194
195
196
197
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--check", action="store_true")

    args = parser.parse_args()

    check_cli(args.check)
    check_supported_models(args.check)
198
    check_openapi(args.check)
199
200


Merve Noyan's avatar
Merve Noyan committed
201
202
if __name__ == "__main__":
    main()