okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-3v (aec86299d) into f-own-int: our own Qwen vision tower (mtmd stays the default)0479b72e9

main
9.7 KiB180 linesraw
1#!/usr/bin/env python3
2"""Verify third_party/strata-ggml, strata-gguf-py, strata-llama and stb against their manifests (UPSTREAM.md).   python tools/check_vendored.py [--upstream <llama.cpp dir>]
3
4The vendored ggml / ggml-cuda sources are frozen at the llama.cpp commit named in UPSTREAM.md.  The manifest lists every file with its
5kind and sha256 (text files are hashed with LF line ends, so a Windows checkout agrees with a Linux one):
6
7  upstream   identical to the file at the pinned commit
8  edited     a Strata edit of an upstream file (the edit is described in UPSTREAM.md); the row also holds the upstream sha256
9  added      a file that is Strata's own (not in llama.cpp)
10  copy       ggml/src/ggml-cuda-tq/X: a verbatim copy of its pristine counterpart (ggml-cuda/X; ggml-cuda-tq/include/X is include/X); the row holds the
11             counterpart's hash.  The trellis (Gyro) MMQ build compiles its headers from this folder, which is first on strata_mmq's include path,
12             so a header that includes mmq.cuh by name has to sit beside the patched mmq.cuh
13  patched    the same, with additions (checked here: every line of the counterpart is still there, in order; only lines were added)
14
15Checks: every listed file exists and has the listed hash; no file of the tree is missing from the list; the pin equals
16third_party/ggml/VERSION.txt; the LICENSE is there; every `edited` row names its upstream hash.  With --upstream <dir> the upstream
17hashes are also checked against that checkout (the files at the pin, e.g. `git archive` of the commit): `upstream` rows must equal the file
18there, `edited` rows must carry its hash.  Standard library only.  Exit 0 clean, 1 on any problem.
19"""
20import argparse
21import hashlib
22import os
23import re
24import sys
25
26ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
27TREE = os.path.join("third_party", "strata-ggml")
28IDENTITY = ()      # a tree that keeps llama.cpp's layout and has no file under another name (third_party/strata-llama): an empty map, every file `upstream`
29GGML_RENAMED = {"strata-quant-common.h": "ggml/src/ggml-common.h"}   # the one file of third_party/strata-ggml whose upstream name differs
30# every vendored tree: (folder, maps a path in the tree to the path in the llama.cpp checkout at the pin)
31GGUF_PY_MAP = (("gguf/", "gguf-py/gguf/"), ("converter/conversion/", "conversion/"), ("converter/convert_hf_to_gguf.py", "convert_hf_to_gguf.py"),
32               ("converter/LICENSE", "LICENSE"), ("LICENSE", "gguf-py/LICENSE"), ("pyproject.toml", "gguf-py/pyproject.toml"))
33STB_MAP = (("stb_image.h", "vendor/stb/stb_image.h"),)   # third_party/stb: the one header, from llama.cpp's vendor/stb
34BEGIN, END = "<!-- vendored-files:begin -->", "<!-- vendored-files:end -->"
35NOT_LISTED = {"UPSTREAM.md"}          # the manifest itself
36TEXT_SUFFIXES = {".c", ".cc", ".cpp", ".cu", ".cuh", ".h", ".hpp", ".txt", ".cmake", ".in", ".md", ".inc", ".py", ".toml", ".typed"}
37
38
39def sha(path):
40    with open(path, "rb") as f:
41        data = f.read()
42    if os.path.splitext(path)[1].lower() in TEXT_SUFFIXES or os.path.basename(path) == "LICENSE":
43        data = data.replace(b"\r\n", b"\n")
44    return hashlib.sha256(data).hexdigest()
45
46
47def counterpart(rel):
48    if rel.startswith("ggml/src/ggml-cuda-tq/include/"):
49        return "ggml/include/" + rel[len("ggml/src/ggml-cuda-tq/include/"):]
50    if rel.startswith("ggml/src/ggml-cuda-tq/") and "/template-instances/" not in rel:
51        return "ggml/src/ggml-cuda/" + rel[len("ggml/src/ggml-cuda-tq/"):]
52    return None
53
54
55def only_added(base, patched):
56    """True when `patched` is `base` with lines inserted (every base line occurs in patched, in order)."""
57    a = open(base, encoding="utf-8").read().replace(chr(13) + chr(10), chr(10)).split(chr(10))
58    b = open(patched, encoding="utf-8").read().replace(chr(13) + chr(10), chr(10)).split(chr(10))
59    j = 0
60    for line in a:
61        while j < len(b) and b[j] != line:
62            j += 1
63        if j == len(b):
64            return False
65        j += 1
66    return True
67
68
69def parse(manifest):
70    text = open(manifest, encoding="utf-8").read()
71    if BEGIN not in text or END not in text:
72        raise SystemExit("UPSTREAM.md: the %s block is missing" % BEGIN)
73    block = text.split(BEGIN, 1)[1].split(END, 1)[0]
74    rows = []
75    for line in block.splitlines():
76        line = line.strip()
77        if not line or line.startswith("```") or line.startswith("#"):
78            continue
79        parts = line.split()
80        if len(parts) < 4:
81            raise SystemExit("UPSTREAM.md: bad row: %r" % line)
82        kind, h, up, rel = parts[0], parts[1], parts[2], " ".join(parts[3:])
83        rows.append((kind, h, up, rel))
84    m = re.search(r"^pin:\s*([0-9a-f]{40})\s*$", text, re.M)
85    return rows, (m.group(1) if m else None)
86
87
88def upstream_rel(rel, upmap):
89    """The path of a tree file in the llama.cpp checkout (`upmap` None: the tree keeps llama.cpp's layout)."""
90    if upmap is None:
91        return GGML_RENAMED.get(rel, rel)
92    for here, there in upmap:
93        if here.endswith("/") and rel.startswith(here):
94            return there + rel[len(here):]
95        if rel == here:
96            return there
97    return rel
98
99
100def check_tree(root, tree_rel, upmap, upstream, problems):
101    """Check one vendored tree against its UPSTREAM.md; returns the one-line summary."""
102    tree = os.path.join(root, tree_rel)
103    rows, pin = parse(os.path.join(tree, "UPSTREAM.md"))
104    ver = os.path.join(root, "third_party", "ggml", "VERSION.txt")
105    if os.path.exists(ver):
106        vpin = open(ver, encoding="utf-8").read().split()[0]
107        if vpin != pin:
108            problems.append("%s: pin %s in UPSTREAM.md differs from third_party/ggml/VERSION.txt (%s)" % (tree_rel, pin, vpin))
109    if not os.path.exists(os.path.join(tree, "LICENSE")):
110        problems.append("%s: LICENSE is missing" % tree_rel)
111    listed = set()
112    for kind, h, up, rel in rows:
113        if kind not in ("upstream", "edited", "added", "copy", "patched"):
114            problems.append("%s: unknown kind %r" % (rel, kind))
115            continue
116        listed.add(rel)
117        p = os.path.join(tree, rel)
118        if not os.path.isfile(p):
119            problems.append("%s: listed but missing" % rel)
120            continue
121        if sha(p) != h:
122            problems.append("%s: sha256 differs from the manifest (%s)" % (rel, kind))
123        if kind == "upstream" and up != h:
124            problems.append("%s: an `upstream` row must carry its own hash as the upstream hash" % rel)
125        if kind == "edited" and (up == h or not re.fullmatch(r"[0-9a-f]{64}", up)):
126            problems.append("%s: an `edited` row needs the upstream hash, different from the file's" % rel)
127        if kind == "added" and up != "-":
128            problems.append("%s: an `added` row has `-` as the upstream hash" % rel)
129        if kind in ("copy", "patched"):
130            cp = counterpart(rel)
131            cpp = os.path.join(tree, cp) if cp else None
132            if not cpp or not os.path.isfile(cpp):
133                problems.append("%s: no counterpart in the tree for a `%s` row" % (rel, kind))
134            else:
135                if sha(cpp) != up:
136                    problems.append("%s: its counterpart %s differs from the hash in the row" % (rel, cp))
137                if kind == "copy" and up != h:
138                    problems.append("%s: a `copy` must equal its counterpart" % rel)
139                if kind == "patched" and (up == h or not only_added(cpp, p)):
140                    problems.append("%s: a `patched` copy must differ from %s by added lines only" % (rel, cp))
141        if upstream and kind in ("upstream", "edited", "copy", "patched"):
142            q = os.path.join(upstream, counterpart(rel) if kind in ("copy", "patched") else upstream_rel(rel, upmap))
143            if not os.path.isfile(q):
144                problems.append("%s: not in the upstream tree %s" % (rel, upstream))
145            elif sha(q) != up:
146                problems.append("%s: upstream hash in the manifest differs from %s" % (rel, q))
147    for d, dirs, files in os.walk(tree):
148        dirs[:] = [x for x in dirs if x != "__pycache__"]       # bytecode written by an import of the vendored package is not a file of the tree
149        for f in files:
150            rel = os.path.relpath(os.path.join(d, f), tree).replace(os.sep, "/")
151            if rel in NOT_LISTED or (rel == "LICENSE" and upmap is None):
152                continue
153            if rel not in listed:
154                problems.append("%s: in the tree but not in UPSTREAM.md" % rel)
155    n = {k: sum(1 for r in rows if r[0] == k) for k in ("upstream", "edited", "added", "copy", "patched")}
156    return "%s: %d files (%d upstream, %d edited, %d added, %d copy, %d patched), pin %s" % (
157        tree_rel.replace(os.sep, "/"), len(rows), n["upstream"], n["edited"], n["added"], n["copy"], n["patched"], (pin or "?")[:9])
158
159
160def main(argv=None):
161    ap = argparse.ArgumentParser()
162    ap.add_argument("--upstream", help="a llama.cpp tree at the pinned commit (file paths as in llama.cpp; third_party/strata-gguf-py maps as in its UPSTREAM.md)")
163    ap.add_argument("--root", default=ROOT)
164    a = ap.parse_args(argv)
165    problems = []
166    summary = [check_tree(a.root, TREE, None, a.upstream, problems),
167               check_tree(a.root, os.path.join("third_party", "strata-gguf-py"), GGUF_PY_MAP, a.upstream, problems),
168               check_tree(a.root, os.path.join("third_party", "strata-llama"), IDENTITY, a.upstream, problems),
169               check_tree(a.root, os.path.join("third_party", "stb"), STB_MAP, a.upstream, problems)]
170    for p in problems:
171        print("check_vendored: " + p)
172    if problems:
173        print("check_vendored: %d problem(s)" % len(problems))
174        return 1
175    print("check_vendored: ok - " + "; ".join(summary))
176    return 0
177
178
179if __name__ == "__main__":
180    sys.exit(main())