interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / examples / python / stubs.py

128 lines · 4516 bytes Raw Blame History
1"""
2 This generates .pyi stubs for the cffi Python bindings generated by regenerate.py
3"""
4import sys, re, itertools
5sys.path.extend(['.', '..']) # for pycparser
6
7from pycparser import c_ast, parse_file, CParser
8import pycparser.plyparser
9from pycparser.c_ast import PtrDecl, TypeDecl, FuncDecl, EllipsisParam, IdentifierType, Struct, Enum, Typedef
10from typing import Tuple
11
12__c_type_to_python_type = {
13 'void': 'None', '_Bool': 'bool',
14 'char': 'int', 'short': 'int', 'int': 'int', 'long': 'int',
15 'ptrdiff_t': 'int', 'size_t': 'int',
16 'int8_t': 'int', 'uint8_t': 'int',
17 'int16_t': 'int', 'uint16_t': 'int',
18 'int32_t': 'int', 'uint32_t': 'int',
19 'int64_t': 'int', 'uint64_t': 'int',
20 'float': 'float', 'double': 'float',
21 'ggml_fp16_t': 'np.float16',
22}
23
24def format_type(t: TypeDecl):
25 if isinstance(t, PtrDecl) or isinstance(t, Struct):
26 return 'ffi.CData'
27 if isinstance(t, Enum):
28 return 'int'
29 if isinstance(t, TypeDecl):
30 return format_type(t.type)
31 if isinstance(t, IdentifierType):
32 assert len(t.names) == 1, f'Expected a single name, got {t.names}'
33 return __c_type_to_python_type.get(t.names[0]) or 'ffi.CData'
34 return t.name
35
36class PythonStubFuncDeclVisitor(c_ast.NodeVisitor):
37 def __init__(self):
38 self.sigs = {}
39 self.sources = {}
40
41 def get_source_snippet_lines(self, coord: pycparser.plyparser.Coord) -> Tuple[list[str], list[str]]:
42 if coord.file not in self.sources:
43 with open(coord.file, 'rt') as f:
44 self.sources[coord.file] = f.readlines()
45 source_lines = self.sources[coord.file]
46 ncomment_lines = len(list(itertools.takewhile(lambda i: re.search(r'^\s*(//|/\*)', source_lines[i]), range(coord.line - 2, -1, -1))))
47 comment_lines = [l.strip() for l in source_lines[coord.line - 1 - ncomment_lines:coord.line - 1]]
48 decl_lines = []
49 for line in source_lines[coord.line - 1:]:
50 decl_lines.append(line.rstrip())
51 if (';' in line) or ('{' in line): break
52 return (comment_lines, decl_lines)
53
54 def visit_Enum(self, node: Enum):
55 if node.values is not None:
56 for e in node.values.enumerators:
57 self.sigs[e.name] = f' @property\n def {e.name}(self) -> int: ...'
58
59 def visit_Typedef(self, node: Typedef):
60 pass
61
62 def visit_FuncDecl(self, node: FuncDecl):
63 ret_type = node.type
64 is_ptr = False
65 while isinstance(ret_type, PtrDecl):
66 ret_type = ret_type.type
67 is_ptr = True
68
69 fun_name = ret_type.declname
70 if fun_name.startswith('__'):
71 return
72
73 args = []
74 argnames = []
75 def gen_name(stem):
76 i = 1
77 while True:
78 new_name = stem if i == 1 else f'{stem}{i}'
79 if new_name not in argnames: return new_name
80 i += 1
81
82 for a in node.args.params:
83 if isinstance(a, EllipsisParam):
84 arg_name = gen_name('args')
85 argnames.append(arg_name)
86 args.append('*' + gen_name('args'))
87 elif format_type(a.type) == 'None':
88 continue
89 else:
90 arg_name = a.name or gen_name('arg')
91 argnames.append(arg_name)
92 args.append(f'{arg_name}: {format_type(a.type)}')
93
94 ret = format_type(ret_type if not is_ptr else node.type)
95
96 comment_lines, decl_lines = self.get_source_snippet_lines(node.coord)
97
98 lines = [f' def {fun_name}({", ".join(args)}) -> {ret}:']
99 if len(comment_lines) == 0 and len(decl_lines) == 1:
100 lines += [f' """{decl_lines[0]}"""']
101 else:
102 lines += [' """']
103 lines += [f' {c.lstrip("/* ")}' for c in comment_lines]
104 if len(comment_lines) > 0:
105 lines += ['']
106 lines += [f' {d}' for d in decl_lines]
107 lines += [' """']
108 lines += [' ...']
109 self.sigs[fun_name] = '\n'.join(lines)
110
111def generate_stubs(header: str):
112 """
113 Generates a .pyi Python stub file for the GGML API using C header files.
114 """
115
116 v = PythonStubFuncDeclVisitor()
117 v.visit(CParser().parse(header, "<input>"))
118
119 keys = list(v.sigs.keys())
120 keys.sort()
121
122 return '\n'.join([
123 '# auto-generated file',
124 'import ggml.ffi as ffi',
125 'import numpy as np',
126 'class lib:',
127 *[v.sigs[k] for k in keys]
128 ])