ggml
[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)
Brought by drakestapleton
ggml / examples / python / regenerate.py
| 1 | # Generates bindings for the ggml library. |
| 2 | # |
| 3 | # cffi requires prior C preprocessing of the headers, and it uses pycparser which chokes on a couple of things |
| 4 | # so we help it a bit (e.g. replace sizeof expressions with their value, remove exotic syntax found in Darwin headers). |
| 5 | import os, sys, re, subprocess |
| 6 | import cffi |
| 7 | from stubs import generate_stubs |
| 8 | |
| 9 | API = os.environ.get('API', 'api.h') |
| 10 | CC = os.environ.get('CC') or 'gcc' |
| 11 | C_INCLUDE_DIR = os.environ.get('C_INCLUDE_DIR', '../../../llama.cpp') |
| 12 | CPPFLAGS = [ |
| 13 | "-I", C_INCLUDE_DIR, |
| 14 | '-D__fp16=uint16_t', # pycparser doesn't support __fp16 |
| 15 | '-D__attribute__(x)=', |
| 16 | '-D_Static_assert(x, m)=', |
| 17 | ] + [x for x in os.environ.get('CPPFLAGS', '').split(' ') if x != ''] |
| 18 | |
| 19 | try: header = subprocess.run([CC, "-E", *CPPFLAGS, API], capture_output=True, text=True, check=True).stdout |
| 20 | except subprocess.CalledProcessError as e: print(f'{e.stderr}\n{e}', file=sys.stderr); raise |
| 21 | |
| 22 | header = '\n'.join([l for l in header.split('\n') if '__darwin_va_list' not in l]) # pycparser hates this |
| 23 | |
| 24 | # Replace constant size expressions w/ their value (compile & run a mini exe for each, because why not). |
| 25 | # First, extract anyting *inside* square brackets and anything that looks like a sizeof call. |
| 26 | for expr in set(re.findall(f'(?<=\\[)[^\\]]+(?=])|sizeof\\s*\\([^()]+\\)', header)): |
| 27 | if re.match(r'^(\d+|\s*)$', expr): continue # skip constants and empty bracket contents |
| 28 | subprocess.run([CC, "-o", "eval_size_expr", *CPPFLAGS, "-x", "c", "-"], text=True, check=True, |
| 29 | input=f'''#include <stdio.h> |
| 30 | #include "{API}" |
| 31 | int main() {{ printf("%lu", (size_t)({expr})); }}''') |
| 32 | size = subprocess.run(["./eval_size_expr"], capture_output=True, text=True, check=True).stdout |
| 33 | print(f'Computed constexpr {expr} = {size}') |
| 34 | header = header.replace(expr, size) |
| 35 | |
| 36 | ffibuilder = cffi.FFI() |
| 37 | ffibuilder.cdef(header) |
| 38 | ffibuilder.set_source(f'ggml.cffi', None) # we're not compiling a native extension, as this quickly gets hairy |
| 39 | ffibuilder.compile(verbose=True) |
| 40 | |
| 41 | with open("ggml/__init__.pyi", "wt") as f: |
| 42 | f.write(generate_stubs(header)) |