ビジョンモデルを含むLLMの単一関数Jevライクラッパー
A single function Jev-like wrapper for LLMs, including vision models (allanrbo.blogspot.com)
要約
この記事では、LLM(大規模言語モデル)の出力を分析するための新しいアプローチとして、Jevライクなラッパーを紹介しています。このラッパーは、プロンプトに特定の形式で質問を埋め込み、モデルのトークン確率(logprobs)を取得することで、単一トークンでの回答を強制し、分析を高速化します。さらに、この手法は画像入力に対応するビジョンモデルにも拡張可能であり、Webカメラの映像をリアルタイムで分析し、人物の有無、屋内/屋外、明るさなどを判断するデモンストレーションコードも提供されています。
全文翻訳
Jevとその周辺で登場しているセルフホスト可能なプロジェクト、例えばOpenJevやSemIfに興味を持ちました。それらについて読む中で、LLMのトークン確率を読み取るという便利なトリックを知りました。
これは一部の人々にとっては古いトリックのようです。例えば、OpenAIのlogprobsクックブックを参照してください。
基本的なアイデアは、以下のようなプロンプトを書くことだと考えています。
State: My order arrived broken and I want a refund.
Question: Which team should handle this?
[A] billing
[B] shipping
[C] returns
Answer with the letter of the best option only.
そして、互換性のあるChat CompletionsリクエストにいくつかのJSONリクエストパラメータを追加します。
{
"max_completion_tokens": 1,
"logprobs": true,
"top_logprobs": 20
}
LLM APIは、その文字と、代替トークンに対するモデルの対数確率を返します。
各質問について繰り返します。1トークンのみを生成するように強制することで、長い回答を避け、非常に高速にすることができますが、入力の処理には依然として時間がかかります。ただし、バックエンドがサポートしていれば、質問ごとに共有状態のプレフィックスをKVキャッシュできます。
面白いのは、これがビジョンモデルでも機能することです。Jevの文書化されたリクエストフォーマットでは、現在テキスト/JSONの状態のみが記述されています。私のローカル実験のために、画像用のattachmentsフィールドを追加しました。
私の例では、Webカメラのフレームをキャプチャし、base64エンコードされたJPEGを送信し、表を表示します。人影が見えるか、屋内か屋外か、そしてシーンの明るさはどうか? RTX 3090上のGemma 4 12Bでは、1フレームあたり約1フレーム/秒で、フレームあたり3つの質問が可能です。OpenAIのgpt-6-lunaでも約0.2 FPSでしたが、これはおそらく質問ごとに個別の接続コストを回避する努力をしなかったためでしょう。
専用のコンピュータビジョンモデルは間違いなくはるかに効率的ですが、私がここで気に入っているのはその柔軟性です。テキストで条件を記述するだけで変更できます。
以下はスタンドアロンのPython例です(OpenCVは、実際のコンピュータビジョンではなく、Webカメラへの便利なアクセスに使用されています)。
#!/usr/bin/env -S uv run --script
# /// script
# dependencies = ["opencv-python"]
# ///
"""Preview and score webcam frames with llama.cpp or OpenAI.
uv run webcam.py
uv run webcam.py https://api.openai.com/v1 gpt-6-luna
OpenAI reads OPENAI_API_KEY.
"""
import argparse
import base64
import concurrent.futures
import datetime
import json
import math
import mimetypes
import os
import pathlib
import time
import urllib.parse
import urllib.request
import cv2
# attachments is our custom addition to the Jev request format.
data = json.loads("""
{
"state": "Inspect this webcam frame. Judge only what is visibly present.",
"attachments": [],
"questions": {
"person": {
"type": "noul",
"instructions": "Is a person visible?"
},
"plant": {
"type": "noul",
"instructions": "Is a plant visible?"
},
"setting": {
"type": "choice",
"instructions": "Where is the camera?",
"criteria": {
"indoors": null,
"outdoors": null,
"unclear": null
}
},
"light": {
"type": "score",
"instructions": "How bright is the scene?",
"criteria": [
"dark",
"dim",
"bright"
]
}
}
}
""")
def score(data, url, model):
state = data["state"]
if not isinstance(state, str):
state = json.dumps(state)
# Attachments are our extension to the Jev-style request format:
# image file paths or base64 data URLs. Load them once for all questions.
images = []
for attachment in data.get("attachments", []):
if attachment.startswith("data:image/"):
images.append(attachment)
continue
path = pathlib.Path(attachment).expanduser()
mime_type, _ = mimetypes.guess_type(path)
if mime_type not in {"image/png", "image/jpeg", "image/webp", "image/gif"}:
raise ValueError(f"Unsupported image file: {path}")
encoded = base64.b64encode(path.read_bytes()).decode()
images.append(f"data:{mime_type};base64,{encoded}")
# Send the API key only to OpenAI.
is_openai = urllib.parse.urlsplit(url).hostname == "api.openai.com"
headers = {"Content-Type": "application/json"}
if is_openai:
headers["Authorization"] = "Bearer " + os.environ["OPENAI_API_KEY"]
answers = {}
for name, question in data["questions"].items():
# Represent choices, booleans, and ordinal levels as lettered options.
if question["type"] == "choice":
options = question["criteria"]
elif question["type"] == "noul":
options = {"true": None, "false": None} | question.get("criteria", {})
elif question["type"] == "score":
options = {str(i): description for i, description in enumerate(question["criteria"]) } # noqa
else:
raise ValueError(f"Unknown question type: {question['type']}")
if not 2 <= len(options) <= 20:
raise ValueError("Provide 2 to 20 criteria per question.")
letters = "ABCDEFGHIJKLMNOPQRST"[:len(options)]
# Ask for a single option letter, so its logprob represents that option.
instructions = question["instructions"]
if not isinstance(instructions, str):
instructions = json.dumps(instructions)
lines = [f"State:\n{state}\n\nQuestion: {instructions}\nOptions:"]
for letter, (key, description) in zip(letters, options.items()):
line = f"[{letter}] {key}"
if description is not None:
line += f": {description}"
lines.append(line)
prompt = "\n".join(lines) + "\n\nAnswer with the letter of the best option only."
# OpenAI needs Responses for enough alternatives; llama.cpp needs Chat for logprobs.
# top_p=1 avoids pruning alternatives.
if is_openai:
endpoint = "/responses"
content = [{"type": "input_text", "text": prompt}]
content.extend({"type": "input_image", "image_url": image} for image in images)
body = {
"model": model,
"input": [{"role": "user", "content": content}],
"reasoning": {"effort": "none"},
"max_output_tokens": 16,
"top_p": 1,
"top_logprobs": 20,
"include": ["message.output_text.logprobs"],
}
else:
endpoint = "/chat/completions"
content = [{"type": "text", "text": prompt}]
content.extend({"type": "image_url", "image_url": {"url": image}} for image in images)
body = {
"model": model,
"messages": [{"role": "user", "content": content}],
"max_completion_tokens": 1,
"temperature": 0,
"reasoning_effort": "none",
"logprobs": True,
"top_logprobs": 1024,
}
# Send the request and read the first output token's alternatives.
request = urllib.request.Request(
url.rstrip("/") + endpoint,
headers=headers,
data=json.dumps(body).encode(),
)
with urllib.request.urlopen(request) as response:
result = json.load(response)
if is_openai:
message = next(item for item in result["output"] if item["type"] == "message")
candidates = message["content"][0]["logprobs"][0]["top_logprobs"]
else:
candidates = result["choices"][0]["logprobs"]["content"][0]["top_logprobs"]
logprobs = {item["token"]: item["logprob"] for item in candidates}
# Normalize the returned option scores; missing options initially get zero.
missing = [letter for letter in letters if letter not in logprobs or logprobs[letter] <= -9999]
if len(missing) == len(letters):
raise ValueError("API did not return usable scores for any option")
peak = max(logprobs[letter] for letter in letters if letter not in missing)
weights = [math.exp(logprobs[letter] - peak) if letter not in missing else 0 for letter in letters]
total = sum(weights)
# An omitted token cannot outrank the last returned alternative.
# Allow zero only when their combined normalized probability is below 1e-6.
if missing:
cutoff = min(value for value in logprobs.values() if value > -9999)
missing_weight = len(missing) * math.exp(cutoff - peak)
if missing_weight / (total + missing_weight) >= 1e-6:
raise ValueError(f"API omitted non-negligible option scores for: {', '.join(missing)}")
probabilities = {key: weight / total for key, weight in zip(options, weights)}
# Return the winning choice, probability of true, or expected ordinal level.
if question["type"] == "choice":
answers[name] = {
"type": "choice",
"choice": max(probabilities, key=probabilities.get),
"probabilities": probabilities,
}
elif question["type"] == "noul":
answers[name] = {"type": "noul", "noul": probabilities["true"]}
else:
answers[name] = {
"type": "score",
"score": sum(int(key) * probability for key, probability in probabilities.items()),
"legend": options,
"probabilities": probabilities,
}
return {"answers": answers}
# Choose the server and model before opening the camera.
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("url", nargs="?", default="http://localhost:8060/v1")
parser.add_argument("model", nargs="?", default="gemma-4-12b")
args = parser.parse_args()
# Point OpenCV's bundled Qt at the installed system fonts.
os.environ["QT_QPA_FONTDIR"] = "/usr/share/fonts/truetype/noto"
# Open the default Linux webcam with a small capture buffer.
camera = cv2.VideoCapture(0, cv2.CAP_V4L2)
if not camera.isOpened():
raise RuntimeError("Could not open /dev/video0")
camera.set(cv2.CAP_PROP_BUFFERSIZE, 1)
print(f"Webcam -> {args.model}. Noul: yes %; score: value/max. Ctrl-C or Esc to stop.", flush=True)
print(f"{ 'time':<8}" + "".join(f"{name:>10}" for name in data["questions"]) + f"{ 'fps':>10}", flush=True)
# Preview continuously while a background worker scores one frame at a time.
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
pending = None
try:
while True:
ok, frame = camera.read()
if not ok:
raise RuntimeError("Could not read a webcam frame")
cv2.imshow("Webcam", frame)
if cv2.waitKey(1) == 27 or cv2.getWindowProperty("Webcam", cv2.WND_PROP_VISIBLE) < 1:
break
# Print a completed result, then submit the latest frame.
if pending is not None:
if not pending.done():
continue
result = pending.result()
columns = []
for name in data["questions"]:
answer = result["answers"][name]
if answer["type"] == "noul":
value = f"{answer['noul']:.1%}"
elif answer["type"] == "choice":
value = answer["choice"]
else:
value = f"{answer['score']:.2f}/{len(data['questions'][name]['criteria']) - 1}"
columns.append(f"{value:>10}")
columns.append(f"{1 / (time.perf_counter() - started):>10.2f}")
print(captured + "".join(columns), flush=True)
# Measure throughput for evaluated frames, including image encoding.
started = time.perf_counter()
captured = datetime.datetime.now().strftime("%H:%M:%S")
ok, jpeg = cv2.imencode(".jpg", frame)
if not ok:
raise RuntimeError("Could not encode the webcam frame")
image = "data:image/jpeg;base64," + base64.b64encode(jpeg.tobytes()).decode()
data["attachments"] = [image]
pending = executor.submit(score, data, args.url, args.model)
except KeyboardInterrupt:
print("\nStopped.")
finally:
camera.release()
cv2.destroyAllWindows()
executor.shutdown()
このスクリプトは、APIの違いを処理します。llama.cppはChat Completionsを使用し、OpenAIはResponsesを使用して代替案を表示させます。
llama.cpp経由でGemma 4 12B QATを実行しました。Linux上でNVIDIAドライバー、curl、zstd、uvがインストールされている場合:
# モデル(約7 GB)とマルチモーダルプロジェクター(約175 MB)。
mkdir -p ~/models/gemma-4-12b/
cd ~/models/gemma-4-12b/
curl -fL -C - -o gemma-4-12b-it-qat-q4_0.gguf https://huggingface.co/google/gemma-4-12B-it-qat-q4_0-gguf/resolve/main/gemma-4-12b-it-qat-q4_0.gguf
curl -fL -C - -o mmproj-gemma-4-12b-it-qat-q4_0.gguf https://huggingface.co/google/gemma-4-12B-it-qat-q4_0-gguf/resolve/main/mmproj-gemma-4-12b-it-qat-q4_0.gguf
# RTX 3090(CUDAアーキテクチャ86)用のスタンドアロンllama.cppバイナリ。
curl -fL -o llama.zst https://huggingface.co/buckets/ggml-org/install.sh/resolve/b11160/x86_64/linux/cuda/86/llama-app.zst
mkdir -p ~/bin/
zstd -d llama.zst -o ~/bin/llama
chmod +x ~/bin/llama
~/bin/llama serve --models-dir ~/models/ --port 8060
Pythonの例をwebcam.pyとして保存します。別のターミナルで、そのディレクトリから:
uv run webcam.py http://localhost:8060/v1 gemma-4-12b
# または、環境変数OPENAI_API_KEYを設定してOpenAIを使用します。
uv run webcam.py https://api.openai.com/v1 gpt-6-luna