Da li sam ja dobar AI model (Yes/No)
Mala napomena: sledi tekst o tzv. "decision" AI modelima i upotrebi istih na privatnim računarima. Sadrži testove, izveštaje i na kraju Python skriptu za svakodnevno korišćenje. Ako vas ne interesuje ovakva tematika predlažem da ne čitate dalje.
Moram da priznam da me lokalni AI modeli nisu interesovali ni najmanje do sad. Hteo sam da ih probam, radio sam testove, dao sam im šansu ali na kraju krajeva sam imao dosta proste zadatke da obavim pa mi je Claude u pregledaču bio mnogo prostije i pouzdanije rešenje od tamo nekih lokalnih modela koji imaju milijarde parametara i na koje čekam dugo da bih dobio neki odgovor koji je možda često glup i besmislen do bola. Tačnije, nisam bio zainteresovan sve dok nisam pročitao o "Microsoft-Decision-1" i "Gemini Decision 1" modelima a onda naleteo i na jev.
Nisam nikakav AI ekspert niti neki vrsni poznavalac, volim da čačkam i testiram ali do sada nisam našao nijedan razlog da koristim bilo koji lokalni LLM svakodnevno i da mi procesor izgori. "Decision" modeli i jev su prvi put da sam pomislio "hmmm, možda ovo i nije tako loše?"
Šta je "decision" model? #
Na GitHub strani jevosa imamo sledeći opis
jevos: an open-source alternative to Jev and Microsoft-Decision-1. Yes/no decisions, choices and scores with probabilities, on your laptop's CPU.
To praktično znači da uz minimum resursa imate jako male modele koji mogu da daju odgovore "Da" ili "Ne". Postoje i "decision" modeli od 27 milijardi parametara ali oni su za ozbiljne i skupe grafičke kartice a ne za moj OptiPlex.
Zanimljivost: jevos-v4 mi je u početku vraćao prazne odgovore a Claude je, kopajući po samoj gguf datoteci, otkrio da model uopšte ne piše tekst već daje samo jedan broj.
Napominjem da još uvek nisam siguran kako ćemo ovo prevesti na naš jezik pa koristim navodnike u ovom tekstu za "decision".
Šta je svrha ovako malih modela? #
jevos-v4-q4_k_m.gguf je 619 MB, pokreće se poprilično brzo i daje prihvatljive odgovore (a verovatno će da pokida više u budućnosti). No, odmah ću reći da svrha nije dobijanje odgovora na sledeća pitanja:
- koliko je udaljena planeta Zemlja od Meseca?
- da li Beograd ima više stanovnika u 2026. u odnosu na 2004. godinu ako ograničimo pitanje na strogi centar grada?
- ako imam 4 gladna stanovnika u Sečuanu, koliko kilograma špageta se dnevno pripremi u Bolonji?
Jači opšti LLM modeli čak umeju da budu vickasti i da daju neki odgovor na neka nelogična pitanja pa gledajte ovaj odgovor Claude Opus 5.5 (M) modela na poslednje pitanje:
Između to dvoje nema nikakve veze. Četiri gladna stanovnika Sečuana ne utiču na to šta se kuva u Bolonji, pa se odgovor ne može izračunati. To je kao da pitate koliko je star kapetan ako brod plovi 20 čvorova.
Inače, odgovor je "Kapetan je star 42 godine" pošto je odgovor uvek "42" :)
Testovi brzine "decision" modela #
Za testove sam koristio dva modela:
jevos-v4(Q4_K_M) - "decision" model, 882 M parametara, 619 MB, razume samo engleskiGemma 4 E4B(Q4_0) - običan model, 7,46 B parametara, 4,6 GB, razume i srpski
Iako Gemma nije "decision" model, delovalo mi je zanimljivo da testiram jev uporedo sa nekim modelom koji je brz, pristupačan a dovoljno moćan.
Na mom računaru sam dobio sledeće llama-bench brojke:
$ llama-bench -m jevos-v4-q4_k_m.gguf -ngl 0 -t 3 -p 512 -n 0 -r 1
ggml_vulkan: Found 1 Vulkan devices:
ggml_vulkan: 0 = Intel(R) HD Graphics 630 (KBL GT2) (Intel open-source Mesa driver) | uma: 1 | fp16: 1 | bf16: 0 | fp4: 0 | warp size: 32 | shared memory: 49152 | int dot: 0 | matrix cores: none
| model | size | params | backend | ngl | threads | test | t/s |
| ------------------------------ | ---------: | ---------: | ---------- | --: | ------: | --------------: | -------------------: |
| llama ?B Q4_K - Medium | 585.71 MiB | 882.43 M | Vulkan | 0 | 3 | pp512 | 108.25 ± 0.00 |
build: unknown (10975)
$ llama-bench -m gemma-4-E4B-it-Q4_0.gguf -ngl 0 -t 3 -p 512 -n 0 -r 1
ggml_vulkan: Found 1 Vulkan devices:
ggml_vulkan: 0 = Intel(R) HD Graphics 630 (KBL GT2) (Intel open-source Mesa driver) | uma: 1 | fp16: 1 | bf16: 0 | fp4: 0 | warp size: 32 | shared memory: 49152 | int dot: 0 | matrix cores: none
| model | size | params | backend | ngl | threads | test | t/s |
| ------------------------------ | ---------: | ---------: | ---------- | --: | ------: | --------------: | -------------------: |
| gemma4 E4B Q4_0 | 4.26 GiB | 7.46 B | Vulkan | 0 | 3 | pp512 | 12.15 ± 0.00 |
build: unknown (10975)
Ovde je bitan samo pp512 tj. brzina čitanja. U prvom tekstu je glavni broj bio tg128 (brzina pisanja) ali ovde modeli pišu jedan token ili ništa pa se tg128 ni ne meri. Jevos čita oko 9 puta brže od Gemme. Sa druge strane, Gemma verovatno zna koliko stanovnika ima Sečuan pa treba to uzeti u obzir.
Umetnost postavljanja pravih pitanja #
"Decision" modeli nemaju toliko parametara da mogu da daju prostoproširene odgovore na gorenavedena pitanja. Međutim, zanimljiv mi je taj minimalizam sa Da/Ne kombinacijama ako se postavljaju korisna pitanja.
Relativno korisna pitanja #
Evo par primera pitanja na koja možete dobiti relativno korisne Da/Ne odgovore:
- da li sam u poslednjih 90 dana trenirao noge više nego ruke?
- da li je ovaj oglas za prodavanje robe čitljiv i razumljiv?
- da li je u poslednja tri dana pucao
nirizbog "gpu reseta"?
Očigledno je da morate da pošaljete neke podatke da bi model doneo odluku pa tako za prvi primer treba da date listu svih vežbi, dana kada ste trenirali, serija i ponavljanja po seriji. Mali modeli dobro čitaju, a loše računaju pa je pametnije da sabiranje uradi skripta a da se model pita samo za rezultat. Za niri pitanje vam treba da pokrenete program sa logovanjem poput niri 2> ~/niri.log ili dmesg jer se reseti grafike na FreeBSD-u često vide u kernel logu.
Neko bi pomislio da su ovakvi modeli poprilično beskorisni i to je donekle tačno dok ne probate da postavite prava pitanja.
Apsolutno korisna pitanja #
Hajde da damo primere mnogo težih a korisnijih pitanja:
- ako damo modelu pristup svim blog tekstovima, možemo da pitamo "Da li je autor anonimizovan u svim tekstovima?" ili "Da li se u blog tekstovima pominje adresa ili država stanovanja autora?"
- ako damo modelu pristup medicinskim dokumentima i analizama lokalno, možemo da proverimo da li ima napretka u poslednjih 45 dana
- ako damo podatke o svim incidentima IT sistema u poslednjih 90 dana, možemo da pitamo da li smo rizična meta s obzirom na industriju u kojoj smo ili ne.
Kod brojeva, datuma i pitanja za koja treba znanje o svetu modeli mogu lako da pogreše pa su sve ovo ideje iz mojih testova a ne gotova rešenja.
Kako to izgleda u praksi #
Za pitanja sam koristio malu skriptu koju je napisao Claude. Ima smisla da skriptu, kojom se postavljaju pitanja AI modelu, napiše baš AI zar ne?
Skripta pokrene model, postavi pitanje i odmah ga ugasi. quick je jevos, a second je Gemma.
Beleške iz mog dnevnika treninga #
Jedna beleška je na srpskom:
2026-11-17 Carry: 24+32kg
2026-11-06 Reverse Lunge: Bol u desnom kolenu
Odgovor jevos i Gemma modela:
$ jq -r '.log[] | .date as $d | .entries[] | select(.note) | "\($d) \(.name): \(.note)"' iron-log-2026-11-19.json | ask-ai.py --both "Do these notes mention pain or an injury?"
question: Do these notes mention pain or an injury?
text: 71 chars from stdin
answer: quick no 0.06 [5s]
answer: second yes 0.98 [36s]
Jevos ne zna šta znači reč "bol" jer razume samo engleski dok Gemma zna.
Provera /var/log/messages #
Sistemski log, poslednjih 40 linija. Jedno pitanje sa odgovorom "da", jedno kontrolno sa odgovorom "ne":
$ tail -n 40 /var/log/messages | ask-ai.py -e "Does this log show a GPU hang or a GPU reset?"
question: Does this log show a GPU hang or a GPU reset?
text: 3,864 chars from stdin
answer: quick yes 0.93 [27s]
$ tail -n 40 /var/log/messages | ask-ai.py -e "Does this log show a disk, memory or USB error?"
question: Does this log show a disk, memory or USB error?
text: 3,864 chars from stdin
answer: quick no 0.10 [26s]
Među tih 40 linija su i ove:
Nov 26 22:53:40 bucket kernel: drmn0: [drm] GPU HANG: ecode 9:1:8ed17ff2, in llama-server [103396]
Nov 26 22:53:40 bucket kernel: drmn0: [drm] llama-server[103396] context reset due to GPU hang
Moj mikroblog #
Za ove potrebe ćemo koristiti moj (mikro)blog na računaru koji uređujem godinama, kroz alat koji se zove mistat (nije javno objavljen). Napominjem da meni lično ovakva pitanja deluju kao "prava" zarad ispitivanja modela.
Možete da koristite i AI za formiranje pitanja ako nemate mašte a želite da se poigrate.
Upit 1 (jevos) #
Tekst koji sam pisao je:
[Windows Only] - Just create a .txt file, add
.LOGat the top and save it. Next time you open it onNotepad, it will automatically add a timestamp.#til
AI upit i tačan odgovor jevos modela:
$ mistat info ef1d1f0b | ask-ai.py "Will this tip work on FreeBSD?"
question: Will this tip work on FreeBSD?
text: 443 chars from stdin
answer: quick no 0.07 [7s]
Upit 2 (jevos) #
Tekst koji sam pisao je:
Please be careful when revoking tokens. It looks like the payload installs a dead-man's switch at ~/.local/bin/gh-token-monitor.sh as a systemd user service (Linux) / LaunchAgent com.user.gh-token-monitor(macOS). It polls api.github.com/user with the stolen token every 60s, and if the token is revoked (HTTP 40x), it runs rm -rf ~/.
https://github.com/TanStack/router/issues/7383#issuecomment-4425225340
AI upit i neodređen odgovor jevos modela:
$ mistat info b9b2cc33 | ask-ai.py "Is this a warning about malware?"
question: Is this a warning about malware?
text: 689 chars from stdin
answer: quick unsure 0.50 [8s]
Ako sam ja dobro razumeo, 0.50 znači da je model pola-pola tj. bukvalno neodređen (50% Da i 50% Ne).
Upit 3 (Gemma) #
Tekst koji sam pisao je:
Ne pomaže što su mi danas stigle one podloške za podizanje nagiba pod nogama. Vrh stvar, oseti se kod goblet čučnja. Kod rumunskog manje, treba mi par nedelja uzoraka.
AI upit i tačan odgovor Gemma modela:
$ mistat info a089b968 | ask-ai.py -2 "Is this post about exercise or working out?"
question: Is this post about exercise or working out?
text: 452 chars from stdin
answer: second yes 0.98 [48s]
Upit 4 (Gemma) #
Tekst koji sam pisao je:
Upravo je jedan gost u podcastu objasnio srz zivota:
The more low tech are your tools, the more hi tech you are.
Ido Portal, 20. jun 2022.
The Science & Practice of Movement, Huberman Lab podcast
AI upit i tačan odgovor Gemma modela:
$ mistat info 5ea076e7 | ask-ai.py -2 "Does this post reveal where the author lives, a private person's real name, or when the author is away from home?"
question: Does this post reveal where the author lives, a private person's real name, or when the author is away from home?
text: 466 chars from stdin
answer: second no 0.00 [48s]
Upit 5 (jev i Gemma) #
Pre objave posta na mikroblogu mogu da proverim da li odajem previše informacija. Napravio sam test sa sledećim unosom:
I lived in Kragujevac but not anymore
I onda pitao oba modela (jev i Gemmu) za mišljenje da li taj unos odaje previše informacija
$ mistat info d61feae5 | ask-ai.py --both "Does this post reveal where the author lives, a private person's real name, or when the author is away from home?"
question: Does this post reveal where the author lives, a private person's real name, or when the author is away from home?
text: 288 chars from stdin
answer: quick yes 0.67 [7s]
answer: second no 0.10 [43s]
Izgleda da je Gemma shvatila pitanje doslovno ("gde autor živi") pa je odgovorila "ne", dok je jevos (doduše, sa tek 0.67 sigurnosti tj. 67%) shvatio da post ipak odaje previše.
Očigledno je da pitanje treba pažljivo napisati, npr. "where the author lives or has lived" ili tako nešto.
Za kraj #
Vi kao korisnik znate da li to ima smisla i da li nalazite svrhu. Meni se dopada ideja prostih modela koji su mali, brzi i mogu da budu korisni ali je pitanje koliko ste maštoviti.
Za razliku od svih LLM eksperimenata, ovaj mi ima smisla zato što štedi resurse a pruža nešto korisno. Možda nije najprecizniji sistem u ovom momentu ali se pitam da li će zaživeti dovoljno da se nastavi razvoj na ovako malim modelima kako bih mogao više da se igram.
Da li je zabavan vikend projekat? Da. Da li ću koristiti "decision" modele često? Videćemo.
Dodatak: ask-ai.py skripta #
Ukoliko ste se pitali šta je Claude Opus AI napisao da bi ispitivao druge AI modele, evo te skripte:
ask-ai.py
#!/usr/bin/env python3
r"""ask-ai -- ask a local model a yes/no question about a text.
ask-ai.py "Question?" [FILE ...] the text comes from the files...
some-command | ask-ai.py "Question?" ...or from stdin
ask-ai.py -2 "Question?" < text the second opinion instead
ask-ai.py --both "Question?" < text both, one after the other
w3m -dump page.html | ask-ai.py "..." HTML: give it the text, not the markup
Prints the question, what it read, and one answer line per model:
answer: quick no 0.07 [5s]
The number is P(yes), how sure the model is that the answer is yes.
Exit code: 0 = yes, 1 = no, 2 = unsure or error. With --both: 0 or 1 only
when both agree. So it works in sh: if ask-ai.py -q "..." < f; then ...; fi
The model starts for the question and stops right after (also on Ctrl+C,
kill or an error). It refuses to start while another llama-server runs:
one model at a time. Writes nothing but a server log in $XDG_RUNTIME_DIR.
Python stdlib only; needs llama-server (llama.cpp) and the model files.
WHEN IT HELPS (and when it does not)
Good : is X said in this text, tone, intent, "does this give too much
away", short to medium text (a page or two).
Bad : numbers, sums, dates ("is 5 days within 30?"), "did anything
change" (that is diff), world facts with no text (it guesses),
HTML drawn by JavaScript (there is no text to read).
Rule : small models read well and count badly. Do the numbers in code
(grep, awk, diff), then ask about the result.
RECIPES (sh)
# before `mistat build`: does a post give too much away? (needs Serbian: -2)
zubi() {
q="Does this post reveal where the author lives, a private person's real name,"
q="$q or when the author is away from home?"
mistat info "${1:-last}" | ask-ai.py -2 "$q" && echo "^ worth a second look before mistat build"
}
# before a commit: anything that looks like a secret in the diff?
git diff --cached | ask-ai.py "Does this diff add a password, token or private key?"
# the kernel's last words (FreeBSD: /var/log/messages, or doas dmesg).
# Logs: the newest lines are at the bottom, so -e keeps the end if it is cut.
tail -n 40 /var/log/messages | ask-ai.py -e "Does this log show a GPU hang or a GPU reset?"
# RSS: keep a headline only if it is your kind of thing (uses the exit code)
printf '%s\n' "$title" | ask-ai.py -q "Is this about FreeBSD, old hardware or privacy?" \
&& printf '%s\n' "$title"
# a message you are about to send: does it sound angry?
ask-ai.py -2 "Does this message sound angry or rude?" draft.txt
"""
import argparse
import json
import math
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
def _env(k, default=""):
"""An environment variable, where empty counts as unset."""
return os.environ.get(k) or default
# =============================================================================
# CONFIG
# Everything you would ever change lives here. The code below never names a
# model: it only knows ROLES (quick, second) and KINDS (decision, chat).
# =============================================================================
# Where the .gguf files are.
MODELS_DIR = Path(_env("ASK_AI_MODELS_DIR", "~/Downloads/llm-models")).expanduser()
# The roles. To try another model, change "file" (and "kind" if it is a
# different sort of model). Add a role by adding an entry; `-m NAME` picks it.
#
# file the .gguf file in MODELS_DIR
# kind "decision" a yes/no model that outputs ONE number and no text
# (jevos). See DECISION MODELS below.
# "chat" any ordinary instruct model (Gemma, Qwen, Llama...).
# It is made to write one token after "Answer:", and
# P(yes) = P(yes) / (P(yes) + P(no)).
# gpu layers on the GPU: "0" = CPU only. On this machine the CPU is as
# fast as the HD 630 for this job, and the iGPU sometimes returns
# garbage, so everything is on the CPU.
# row decision models only: which row of the output layer holds the
# answer. "auto" finds it (reads the layer once, a few seconds);
# a number skips that, e.g. "38" for jevos-v4.
# about one line for --help: what it is and what it is good at.
ROLES = {
"quick": {
"file": "jevos-v4-q4_k_m.gguf", "kind": "decision", "gpu": "0", "row": "auto",
"about": "jevos-v4, 0.9B decision model: fast (seconds), English only",
},
"second": {
"file": "gemma-4-E4B-it-Q4_0.gguf", "kind": "chat", "gpu": "0",
"about": "Gemma 4 E4B, ordinary model: slower (about a minute), reads Serbian too",
},
}
DEFAULT_ROLE = _env("ASK_AI_ROLE", "quick") # used when no -m / -2 / --both
SECOND_ROLE = "second" # what -2 means
# Verdicts. P(yes) above YES = "yes"; within UNSURE of 0.5 = "unsure".
YES = float(_env("ASK_AI_YES", "0.5"))
UNSURE = float(_env("ASK_AI_UNSURE", "0.15"))
# Longer texts are cut to this many tokens (and it says so).
# (3000 tokens = about 5 minutes). Allowed: 100 .. 7000.
MAX_TOKENS = min(7000, max(100, int(_env("ASK_AI_MAX_TOKENS", "3000"))))
# llama-server and how it runs.
LLAMA_SERVER = _env("ASK_AI_LLAMA_SERVER", "llama-server")
THREADS = _env("ASK_AI_THREADS", "3") # leave one core for everything else
NICE = int(_env("ASK_AI_NICE", "10")) # lower priority than your other work
HOST, PORT = "127.0.0.1", int(_env("ASK_AI_PORT", "8080")) # never beyond this machine
START_TIMEOUT = int(_env("ASK_AI_START_TIMEOUT", "300")) # seconds to load a model
LOG = Path(f"{_env('XDG_RUNTIME_DIR', '/tmp')}/ask-ai-llama.log")
# =============================================================================
# DECISION MODELS -- how a one-number model (jevos) is read
#
# jevos is a normal llama-architecture network whose output layer was cut to
# a single live row: every other row is zeros. So it cannot write; it gives
# one number z for the last token, and P(yes) = sigmoid(z).
# llama-server is started in embedding mode, which returns the network's final
# hidden state h (1536 numbers for jevos). This script reads the live row w
# straight from the .gguf file and computes z = h . w itself.
# The prompt format ("State: ... Question: ...") was found by trying several
# against jevos's own README examples; it got all of them right.
# =============================================================================
DECISION_PROMPT = ("<|im_start|>user\nState: {text}\nQuestion: {question}<|im_end|>\n"
"<|im_start|>assistant\n<think>\n\n</think>\n\n")
# The prompt for chat models. The answer is started for the model ("Answer:"),
# so its first token is yes or no instead of "Based on the text...".
# The language hint matters: without it Gemma missed the Serbian note
# "Bol u desnom kolenu" (knee pain) that it caught when the hint was there.
CHAT_SYSTEM = ("Answer a yes/no question about the text. The text may be in Serbian "
"or English. Judge only from the text itself.")
CHAT_USER = "{text}\n\n=====\nQuestion: {question}\nAnswer with one word: yes or no."
CHAT_USER_NO_TEXT = "Question: {question}\nAnswer with one word: yes or no."
YES_WORDS = ("yes", "ye", "y", "da") # first tokens counted as yes ("ye", "y": a word
NO_WORDS = ("no", "n", "ne") # split into pieces; "da"/"ne": Serbian)
# =============================================================================
# helpers
# =============================================================================
def die(msg):
"""Print to stderr and exit 2 (= error). Inside a `with Model`, the server
is still stopped: sys.exit raises, and the with-block cleans up."""
print(msg, file=sys.stderr)
sys.exit(2)
def log_tail(n=12):
"""The last lines of the server log, for error messages."""
try:
return "".join(LOG.read_text(errors="replace").splitlines(True)[-n:])
except OSError:
return "(no log)"
def post(url, body, timeout=1800):
"""POST JSON, return the JSON answer. Any failure ends the run with the
server's own error message and the end of its log."""
req = urllib.request.Request(url, json.dumps(body).encode(), {"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.load(r)
except urllib.error.HTTPError as ex:
try:
why = json.loads(ex.read() or b"{}").get("error", {}).get("message", "")
except (ValueError, AttributeError):
why = ""
die(f"llama-server answered HTTP {ex.code}: {why or '(no message)'}\nlog ({LOG}):\n{log_tail()}")
except (urllib.error.URLError, OSError) as ex:
die(f"llama-server not reachable ({ex})")
# =============================================================================
# reading a decision model's live output row from the .gguf file
# GGUF layout: magic "GGUF", version, tensor count, key count, then the keys
# (metadata), then the tensor descriptions, then the tensor data, aligned.
# The output layer is "output.weight", stored as Q8_0: blocks of 32 values,
# each block = a 2-byte half-float scale + 32 signed bytes (value = scale * q).
# =============================================================================
def _output_layer(path):
"""-> (open file positioned nowhere special, width, height, data offset)"""
f = open(path, "rb")
rd = lambda fmt: struct.unpack(fmt, f.read(struct.calcsize(fmt)))[0]
rs = lambda: f.read(rd("<Q")).decode("utf-8", "replace")
sizes = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}
def skip(t): # skip one metadata value of type t
if t == 8: # string
f.seek(rd("<Q"), 1)
elif t == 9: # array: element type, count, elements
it, n = rd("<I"), rd("<Q")
if it in sizes:
f.seek(sizes[it] * n, 1)
else:
for _ in range(n):
skip(it)
else: # a number or a bool
f.seek(sizes[t], 1)
if f.read(4) != b"GGUF":
die(f"{path}: not a GGUF file")
_, ntensors, nkeys = rd("<I"), rd("<Q"), rd("<Q")
align = 32
for _ in range(nkeys):
key, t = rs(), rd("<I")
if key == "general.alignment" and t == 4:
align = rd("<I")
else:
skip(t)
info = {}
for _ in range(ntensors):
name = rs()
dims = [rd("<Q") for _ in range(rd("<I"))]
info[name] = (dims, rd("<I"), rd("<Q")) # shape, type, offset
data_start = f.tell() + (-f.tell()) % align
dims, ttype, off = info.get("output.weight", ([], -1, 0))
if ttype != 8 or len(dims) != 2:
die(f"{path.name}: no Q8_0 output.weight; not a decision model like jevos "
f"(use kind \"chat\" for it)")
return f, dims[0], dims[1], data_start + off
def decision_row(path, row):
"""The live output row as floats. row: "auto" or a number."""
f, width, height, start = _output_layer(path)
rb = width // 32 * 34 # bytes per row
with f:
if row == "auto":
zero, live = bytes(rb), []
f.seek(start)
for r in range(height): # ~200 MB for jevos: a few seconds
if f.read(rb) != zero:
live.append(r)
if len(live) > 1:
break
if len(live) != 1:
die(f"{path.name}: {'no' if not live else 'more than one'} live output row; "
f"not a one-number decision model (use kind \"chat\")")
row = live[0]
f.seek(start + int(row) * rb)
raw = f.read(rb)
vals = []
for i in range(0, rb, 34):
scale = struct.unpack("<e", raw[i:i + 2])[0]
vals += [scale * q for q in struct.unpack("<32b", raw[i + 2:i + 34])]
if not any(vals):
die(f'{path.name}: output row {row} is all zeros; set "row": "auto"')
return vals
# =============================================================================
# one llama-server, for exactly as long as a `with Model(role)` block runs
# =============================================================================
class Model:
def __init__(self, role):
if role not in ROLES:
die(f"unknown model {role!r}; known: {', '.join(ROLES)}")
cfg = ROLES[role]
self.role, self.kind = role, cfg["kind"]
self.path = MODELS_DIR / cfg["file"]
self.gpu, self.row_cfg = cfg.get("gpu", "0"), cfg.get("row", "auto")
self.proc, self.row = None, None
self.base = f"http://{HOST}:{PORT}"
if self.kind not in ("decision", "chat"):
die(f"{role}: unknown kind {self.kind!r} (decision or chat)")
def __enter__(self):
try:
return self._start()
except BaseException: # Ctrl+C or kill while loading: stop it too
self.__exit__()
raise
def _start(self):
if not self.path.is_file() or self.path.stat().st_size == 0:
die(f"model file missing or empty: {self.path}")
# one model at a time: never next to another llama-server
try:
pids = subprocess.run(["pgrep", "-x", Path(LLAMA_SERVER).name],
capture_output=True, text=True).stdout.split()
except OSError:
pids = []
if pids:
die(f"another llama-server is running (pid {' '.join(pids)}): one model at a time")
with socket.socket() as s:
s.settimeout(0.5)
if s.connect_ex((HOST, PORT)) == 0:
die(f"something already listens on {HOST}:{PORT}; set ASK_AI_PORT")
common = ["-m", str(self.path), "-t", THREADS, "-ngl", self.gpu, "-np", "1",
"--host", HOST, "--port", str(PORT)]
if self.kind == "decision":
self.row = decision_row(self.path, self.row_cfg)
# embedding mode reads the whole prompt in one batch, so the batch
# must hold the text limit plus the question: round up to 1 KiB
ctx = str(-(-(MAX_TOKENS + 1024) // 1024) * 1024)
cmd = [LLAMA_SERVER, *common, "-c", ctx, "-b", ctx, "-ub", ctx,
"--embeddings", "--pooling", "last"]
else:
# small batches: on the HD 630 one long GPU job gets reset
# (ErrorDeviceLost); harmless on the CPU
cmd = [LLAMA_SERVER, *common, "-c", "8192", "-b", "128", "-ub", "128", "--jinja"]
with open(LOG, "w") as log:
try:
self.proc = subprocess.Popen(
cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT,
start_new_session=True, # our Ctrl+C is ours to handle, not sent twice
preexec_fn=(lambda: os.nice(NICE)) if NICE else None)
except OSError as ex:
die(f"cannot run {LLAMA_SERVER}: {ex}")
t0 = time.monotonic()
while True: # /health: 503 while loading, 200 when ready
if self.proc.poll() is not None:
self.proc = None
die(f"llama-server exited while loading {self.path.name}:\n{log_tail()}")
try:
with urllib.request.urlopen(self.base + "/health", timeout=2) as r:
if r.status == 200:
return self
except (urllib.error.URLError, OSError):
pass
if time.monotonic() - t0 > START_TIMEOUT:
die(f"{self.path.name} did not load in {START_TIMEOUT}s")
time.sleep(0.5)
def __exit__(self, *exc):
p, self.proc = self.proc, None
if p and p.poll() is None:
p.terminate()
try:
p.wait(timeout=15)
except subprocess.TimeoutExpired:
p.kill()
p.wait()
# --- text length, in this model's own tokens -----------------------------
def ntokens(self, s):
return len(post(self.base + "/tokenize", {"content": s}).get("tokens", []))
def fit(self, text, keep_end=False):
"""Cut text to MAX_TOKENS. keep_end: keep the END instead of the start
(logs: the newest lines are at the bottom). -> (text, kept, total)"""
total = self.ntokens(text) if text else 0
if total <= MAX_TOKENS:
return text, total, total
cut, n = text, total
for _ in range(4): # shrink by the measured ratio until it fits
keep = int(len(cut) * MAX_TOKENS / n * 0.97)
cut = cut[-keep:] if keep_end else cut[:keep]
n = self.ntokens(cut)
if n <= MAX_TOKENS:
break
return cut, n, total
# --- the question ---------------------------------------------------------
def p_yes(self, text, question):
"""-> (P(yes) or None, what the model wanted to say when None)"""
if self.kind == "decision":
prompt = DECISION_PROMPT.format(text=text, question=question)
d = post(self.base + "/embedding", {"content": prompt, "embd_normalize": -1})
h = d[0]["embedding"] if isinstance(d, list) else d["embedding"]
while h and isinstance(h[0], list): # [[...], ...]: the last token's
h = h[-1]
if len(h) != len(self.row):
die(f"{self.role}: hidden state has {len(h)} numbers, the output row {len(self.row)}")
z = sum(a * b for a, b in zip(h, self.row))
return 1 / (1 + math.exp(-max(-60.0, min(60.0, z)))), ""
user = (CHAT_USER if text else CHAT_USER_NO_TEXT).format(text=text, question=question)
r = post(self.base + "/v1/chat/completions", {
"messages": [{"role": "system", "content": CHAT_SYSTEM},
{"role": "user", "content": user},
{"role": "assistant", "content": "Answer:"}], # started for it
"temperature": 0, "max_tokens": 1, "logprobs": True, "top_logprobs": 20,
"chat_template_kwargs": {"enable_thinking": False}}) # no "thinking"
try:
tops = r["choices"][0]["logprobs"]["content"][0]["top_logprobs"]
except (KeyError, IndexError, TypeError):
die("llama-server returned no logprobs (too old a build?)")
y = n = 0.0
for t in tops:
w = t["token"].strip().strip(".,!*:\"'").lower()
if w in YES_WORDS:
y += math.exp(t["logprob"])
elif w in NO_WORDS:
n += math.exp(t["logprob"])
if y + n == 0: # neither: often garbage, e.g. '<unused5>'
return None, ", ".join(repr(t["token"]) for t in tops[:3])
return y / (y + n), ""
def verdict(p):
if p is None or abs(p - 0.5) < UNSURE:
return "unsure"
return "yes" if p > YES else "no"
# =============================================================================
# main
# =============================================================================
def main():
roles = "\n".join(f" {r:8} {c['about']}" for r, c in ROLES.items())
ap = argparse.ArgumentParser(
prog="ask-ai", formatter_class=argparse.RawDescriptionHelpFormatter,
description=__doc__.split("\n\nWHEN")[0],
epilog=f"models (edit ROLES at the top of the script):\n{roles}\n"
f" default: {DEFAULT_ROLE}, -2: {SECOND_ROLE}")
ap.add_argument("question")
ap.add_argument("files", nargs="*", help="the text to judge (default: stdin)")
ap.add_argument("-2", "--second", action="store_true", help="ask the second opinion")
ap.add_argument("--both", action="store_true", help="ask both, one after the other")
ap.add_argument("-m", "--model", help=f"any model by name: {', '.join(ROLES)}")
ap.add_argument("-e", "--end", action="store_true",
help="if the text is too long, keep its end, not its start (logs)")
ap.add_argument("-q", "--quiet", action="store_true", help="no output, only the exit code")
a = ap.parse_args()
if a.both:
roles_to_ask = [DEFAULT_ROLE, SECOND_ROLE] if DEFAULT_ROLE != SECOND_ROLE else [DEFAULT_ROLE]
elif a.second:
roles_to_ask = [SECOND_ROLE]
else:
roles_to_ask = [a.model or DEFAULT_ROLE]
for r in roles_to_ask: # a typo fails before anything is read
if r not in ROLES:
die(f"unknown model {r!r}; known: {', '.join(ROLES)}")
# the text: files, else stdin, else none (then the model answers from what
# it knows, which a decision model can barely do)
if a.files:
try:
text = "\n\n".join(Path(f).read_text(encoding="utf-8", errors="replace") for f in a.files)
except OSError as ex:
die(str(ex))
elif not sys.stdin.isatty():
text = sys.stdin.read()
if not text.strip():
# a pipe that brought nothing (the command before | failed):
# never let a model guess about an empty text
die("no text on stdin (did the command before | fail?)")
else:
text = ""
text = text.strip()
# closing the terminal or `kill` stops the model too
signal.signal(signal.SIGTERM, lambda *_: sys.exit(2))
signal.signal(signal.SIGHUP, lambda *_: sys.exit(2))
if not a.quiet:
src = ", ".join(Path(f).name for f in a.files) if a.files else "stdin"
print(f"question: {a.question}")
print(f"text: {len(text):,} chars from {src}" if text else "text: none")
answers = []
for role in roles_to_ask:
t0 = time.monotonic()
with Model(role) as m:
t, kept, total = m.fit(text, a.end)
if kept < total and not a.quiet:
print(f" cut to the {'last' if a.end else 'first'} {kept:,} of {total:,} "
f"tokens for {role} (ASK_AI_MAX_TOKENS={MAX_TOKENS})")
p, wanted = m.p_yes(t, a.question)
v = verdict(p)
answers.append(v)
if not a.quiet:
num = f"{p:.2f}" if p is not None else f"- (wanted to say: {wanted})"
print(f"answer: {role:8} {v:7} {num} [{time.monotonic() - t0:.0f}s]")
# exit code: yes/no only when every model asked agrees
return 0 if set(answers) == {"yes"} else 1 if set(answers) == {"no"} else 2
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(2)