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 / regenerate.py

42 lines · 2144 bytes Raw Blame History
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).
5import os, sys, re, subprocess
6import cffi
7from stubs import generate_stubs
8
9API = os.environ.get('API', 'api.h')
10CC = os.environ.get('CC') or 'gcc'
11C_INCLUDE_DIR = os.environ.get('C_INCLUDE_DIR', '../../../llama.cpp')
12CPPFLAGS = [
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
19try: header = subprocess.run([CC, "-E", *CPPFLAGS, API], capture_output=True, text=True, check=True).stdout
20except subprocess.CalledProcessError as e: print(f'{e.stderr}\n{e}', file=sys.stderr); raise
21
22header = '\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.
26for 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
36ffibuilder = cffi.FFI()
37ffibuilder.cdef(header)
38ffibuilder.set_source(f'ggml.cffi', None) # we're not compiling a native extension, as this quickly gets hairy
39ffibuilder.compile(verbose=True)
40
41with open("ggml/__init__.pyi", "wt") as f:
42 f.write(generate_stubs(header))