Spaces:
Paused
Paused
File size: 4,338 Bytes
3b4fb97 b4ee86a 7ab0dce b4ee86a 3b4fb97 b4ee86a 3b4fb97 b4ee86a 3b4fb97 b4ee86a 3b4fb97 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 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 | """Verifica patches contra o binario real do llama.cpp.
Motivo: o patcher usa `if "--flag" in help_txt` como guarda. Isso evita
crash, mas NAO avisa quando a flag/env simplesmente nao existe -- o patch
vira no-op silencioso. Foi assim que um bug passou: `LLAMA_ARG_TEMP` nao
existe no build b10985, entao a temperatura nunca era aplicada.
Este script confere, ANTES de subir, que toda flag e toda env var em
**codigo vivo** existe no binario pinado.
Uso:
python verify_against_binary.py app.py
python verify_against_binary.py app.py --lib /caminho/libllama-common.so
"""
import ast
import pathlib
import re
import sys
import tarfile
import urllib.request
TAG = "b10985"
ASSET = f"llama-{TAG}-bin-ubuntu-x64.tar.gz"
URL = (f"https://github.com/ggml-org/llama.cpp/releases/download/{TAG}/{ASSET}")
CACHE = pathlib.Path("./.llama-dist")
def get_lib(path=None):
if path:
return pathlib.Path(path).read_bytes().decode("latin-1")
lib = CACHE / f"llama-{TAG}" / "libllama-common.so.0.4.1"
if not lib.is_file():
CACHE.mkdir(parents=True, exist_ok=True)
tgz = CACHE / ASSET
print(f"baixando {TAG} (~17 MB)...")
urllib.request.urlretrieve(URL, tgz)
with tarfile.open(tgz) as tf:
try:
tf.extractall(CACHE, filter="data")
except TypeError:
tf.extractall(CACHE)
if not lib.is_file():
sys.exit(f"nao encontrei {lib}")
return lib.read_bytes().decode("latin-1")
def live_strings(src):
"""Strings que realmente chegam ao subprocess/env (ignora comentarios)."""
tree = ast.parse(src)
envs, flags = set(), set()
for node in ast.walk(tree):
if isinstance(node, ast.Constant) and isinstance(node.value, str):
envs.update(re.findall(r"LLAMA_ARG_[A-Z0-9_]+", node.value))
flags.update(re.findall(r"--[a-z0-9-]+", node.value))
return envs, flags
# Flags que nao pertencem ao llama.cpp -- nao devem ser cobradas.
IGNORE = {"--format", "--query-gpu", "--version", "--help", "--dry-run",
"--fit", "--mlock"}
# Valores de opcao que o app passa e que precisam existir no build.
# Checar so o nome da flag nao basta: `--spec-type banana` passaria na
# verificacao de flag e falharia em runtime.
OPTION_VALUES = {
"--spec-type": ["ngram-map-k4v", "ngram-map-k", "ngram-simple",
"ngram-mod", "ngram-cache", "draft-simple", "none"],
"--load-mode": ["auto", "none", "mmap", "mlock", "mmap+mlock", "dio"],
"--rope-scaling": ["none", "linear", "yarn"],
}
def main():
if len(sys.argv) < 2:
print(__doc__)
return 2
src = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8")
libarg = None
if "--lib" in sys.argv:
libarg = sys.argv[sys.argv.index("--lib") + 1]
lib = get_lib(libarg)
envs, flags = live_strings(src)
bad_env = sorted(e for e in envs if e not in lib)
bad_fl = sorted(f for f in flags - IGNORE if f not in lib)
# valores de opcao: so cobra se a flag correspondente estiver no codigo
bad_vals = []
for flag, values in OPTION_VALUES.items():
if flag not in src:
continue
for v in values:
if v not in lib:
bad_vals.append(f"{flag}={v}")
print(f"env vars em codigo vivo: {len(envs)}")
for e in sorted(envs):
print(f" [{'OK' if e in lib else 'FALHA'}] {e}")
print(f"flags em codigo vivo: {len(flags - IGNORE)}")
for f in sorted(flags - IGNORE):
print(f" [{'OK' if f in lib else 'nao no lib'}] {f}")
checked = sum(len(v) for k, v in OPTION_VALUES.items() if k in src)
print(f"valores de opcao checados: {checked}")
if bad_vals:
print(f" [FALHA] valores invalidos: {bad_vals}")
if bad_env:
print(f"\n[FALHA] env vars inexistentes no build: {bad_env}")
print(" -> esses patches seriam NO-OP silencioso.")
return 1
if bad_vals:
print(f"\n[FALHA] valores de opcao invalidos: {bad_vals}")
print(" -> o servidor recusaria a flag no boot.")
return 1
if bad_fl:
print(f"\n[AVISO] flags nao encontradas (podem ser de outros programas): {bad_fl}")
print("\n[OK] nenhuma env var invalida em codigo vivo")
return 0
if __name__ == "__main__":
sys.exit(main())
|