Add measured SmolLM2 syntax reviewer and Member 1 evidence
myfileagent-python-ci/pipeline/head This commit looks good
myfileagent-python-ci/pipeline/head This commit looks good
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Constrained syntax reviewer for the SSW590 demonstration."""
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Constrained, auditable syntax review of one Python source file."""
|
||||
import argparse
|
||||
import ast
|
||||
from datetime import datetime, timezone
|
||||
import difflib
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
SHA_RE = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}", re.ASCII)
|
||||
MAX_BACKEND_BYTES = 1_000_000
|
||||
TIMEOUT_SECONDS = 120
|
||||
|
||||
|
||||
def _timestamp():
|
||||
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def backend(source):
|
||||
override = os.environ.get("REVIEWER_BACKEND_COMMAND")
|
||||
if not override:
|
||||
from .llama_adapter import propose
|
||||
return propose(source)
|
||||
command = json.loads(override)
|
||||
if not isinstance(command, list) or not command or not all(type(x) is str and x for x in command):
|
||||
raise ValueError("backend command must be a nonempty JSON string array")
|
||||
with tempfile.TemporaryFile(mode="w+b") as stdout, tempfile.TemporaryFile(mode="w+b") as stderr:
|
||||
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr,
|
||||
start_new_session=True)
|
||||
try:
|
||||
process.communicate(json.dumps({"source": source}).encode(), timeout=TIMEOUT_SECONDS)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.communicate()
|
||||
raise TimeoutError(f"backend exceeded {TIMEOUT_SECONDS} seconds") from exc
|
||||
if stdout.tell() > MAX_BACKEND_BYTES or stderr.tell() > MAX_BACKEND_BYTES:
|
||||
raise ValueError("backend output exceeded size limit")
|
||||
stdout.seek(0)
|
||||
if process.returncode:
|
||||
raise RuntimeError(f"backend exit {process.returncode}")
|
||||
return json.loads(stdout.read().decode("utf-8"))
|
||||
|
||||
|
||||
def review(input_path, source_commit, out_dir, propose=backend):
|
||||
output = Path(out_dir)
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
started = _timestamp()
|
||||
started_clock = time.monotonic()
|
||||
metadata = dict(source_commit=source_commit, model_id=None, status="error", summary="",
|
||||
diff="", input_tokens=None, output_tokens=None,
|
||||
schema_version=1, mode="fixture" if os.environ.get("REVIEWER_BACKEND_COMMAND") else "live",
|
||||
started_at=started, finished_at=None, elapsed_seconds=None)
|
||||
code = 3
|
||||
try:
|
||||
if type(source_commit) is not str or SHA_RE.fullmatch(source_commit) is None:
|
||||
raise ValueError("full lowercase source commit SHA required")
|
||||
original = Path(input_path).read_bytes()
|
||||
source = original.decode("utf-8")
|
||||
metadata["input_sha256"] = hashlib.sha256(original).hexdigest()
|
||||
try:
|
||||
ast.parse(source)
|
||||
except SyntaxError:
|
||||
response = propose(source)
|
||||
if not isinstance(response, dict):
|
||||
raise ValueError("backend response must be a JSON object")
|
||||
model_id = response.get("model_id")
|
||||
if type(model_id) is not str or not model_id.strip():
|
||||
raise ValueError("backend model_id required")
|
||||
metadata["model_id"] = model_id
|
||||
for key in ("input_tokens", "output_tokens"):
|
||||
count = response.get(key)
|
||||
if count is not None and (type(count) is not int or count < 0):
|
||||
raise ValueError(f"{key} must be a nonnegative integer or null")
|
||||
metadata[key] = count
|
||||
if "model_revision" in response:
|
||||
metadata["model_revision"] = response["model_revision"]
|
||||
raw = response.get("raw_response")
|
||||
if raw is not None:
|
||||
if type(raw) is not str or len(raw.encode("utf-8")) > MAX_BACKEND_BYTES:
|
||||
raise ValueError("raw_response must be bounded text")
|
||||
(output / "raw_response.txt").write_text(raw, encoding="utf-8")
|
||||
metadata["raw_response_file"] = "raw_response.txt"
|
||||
runtime_response = response.get("runtime_response")
|
||||
if runtime_response is not None:
|
||||
encoded = json.dumps(runtime_response, indent=2).encode("utf-8")
|
||||
if len(encoded) > MAX_BACKEND_BYTES:
|
||||
raise ValueError("runtime_response exceeded size limit")
|
||||
(output / "runtime_response.json").write_bytes(encoded + b"\n")
|
||||
metadata["runtime_response_file"] = "runtime_response.json"
|
||||
candidate = response.get("candidate")
|
||||
if type(candidate) is not str:
|
||||
raise ValueError("backend candidate must be text")
|
||||
expected = {"print(\"hello\"": "print(\"hello\")",
|
||||
"print(\"hello\"\n": "print(\"hello\")\n"}
|
||||
if source not in expected or candidate != expected[source]:
|
||||
metadata.update(status="rejected", summary="Proposal exceeds the permitted closing-parenthesis repair")
|
||||
code = 2
|
||||
else:
|
||||
ast.parse(candidate)
|
||||
metadata.update(status="corrected", summary="Added the missing closing parenthesis",
|
||||
diff="".join(difflib.unified_diff(source.splitlines(keepends=True),
|
||||
candidate.splitlines(keepends=True), fromfile="original.py", tofile="reviewed.py")))
|
||||
code = 0
|
||||
else:
|
||||
candidate = source
|
||||
metadata.update(status="unchanged", summary="Input parses; inference bypassed", mode="bypass")
|
||||
code = 0
|
||||
if code == 0:
|
||||
(output / "reviewed.py").write_bytes(original if metadata["status"] == "unchanged" else candidate.encode("utf-8"))
|
||||
except Exception as exc:
|
||||
(output / "reviewed.py").unlink(missing_ok=True)
|
||||
metadata.update(status="error", summary=f"{type(exc).__name__}: review could not complete", diff="",
|
||||
diagnostic=f"{type(exc).__name__}: {str(exc)[:240]}")
|
||||
code = 3
|
||||
metadata["finished_at"] = _timestamp()
|
||||
metadata["elapsed_seconds"] = round(time.monotonic() - started_clock, 6)
|
||||
(output / "review.json").write_text(json.dumps(metadata, indent=2) + "\n", encoding="utf-8")
|
||||
return code
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--input", required=True)
|
||||
parser.add_argument("--source-commit", required=True)
|
||||
parser.add_argument("--out-dir", required=True)
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
return review(args.input, args.source_commit, args.out_dir)
|
||||
except OSError as exc:
|
||||
print(f"review output unavailable: {type(exc).__name__}", file=sys.stderr)
|
||||
return 3
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Bounded one-process llama.cpp completion adapter for the hello syntax fixture."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
LOCK = Path(__file__).with_name("model-lock.json")
|
||||
PROMPT_TOKENS = re.compile(r"prompt eval time\s*=.*?/\s*(\d+) tokens")
|
||||
SAMPLED_TOKENS = re.compile(r"samplers time\s*=.*?/\s*(\d+) tokens")
|
||||
|
||||
|
||||
def _sha256(path):
|
||||
digest = hashlib.sha256()
|
||||
with Path(path).open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def propose(source):
|
||||
lock = json.loads(LOCK.read_text(encoding="utf-8"))
|
||||
model = Path(os.environ["REVIEWER_MODEL_PATH"])
|
||||
executable = Path(os.environ["REVIEWER_LLAMA_COMPLETION"])
|
||||
if not model.is_file():
|
||||
raise FileNotFoundError("model file missing")
|
||||
if _sha256(model) != lock["quantized_sha256"]:
|
||||
raise ValueError("model checksum mismatch")
|
||||
if not executable.is_file():
|
||||
raise FileNotFoundError("llama-completion executable missing")
|
||||
if source not in ('print("hello"', 'print("hello"\n'):
|
||||
raise ValueError("real-model adapter only supports the hello fixture")
|
||||
prompt = lock["prompt_template"].format(source_line=source.rstrip("\n"))
|
||||
command = [str(executable), "-m", str(model), "-p", prompt,
|
||||
"-n", str(lock["max_output_tokens"]), "-c", str(lock["context_tokens"]),
|
||||
"-b", str(lock["batch_tokens"]), "-ub", str(lock["microbatch_tokens"]),
|
||||
"-t", str(lock["threads"]), "-tb", str(lock["threads"]),
|
||||
"--temp", str(lock["temperature"]), "--seed", str(lock["seed"]),
|
||||
"--no-conversation", "--simple-io", "--no-display-prompt",
|
||||
"--no-warmup", "--color", "off", "-r", "\n"]
|
||||
try:
|
||||
result = subprocess.run(command, capture_output=True, timeout=30, check=False)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise TimeoutError("llama-completion exceeded 30 seconds") from exc
|
||||
if len(result.stdout) > 1_000_000 or len(result.stderr) > 1_000_000:
|
||||
raise ValueError("runtime output exceeded size limit")
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"llama-completion exited {result.returncode}")
|
||||
raw = result.stdout.decode("utf-8")
|
||||
runtime_log = result.stderr.decode("utf-8", errors="replace")
|
||||
prompt_match = PROMPT_TOKENS.search(runtime_log)
|
||||
sampled_match = SAMPLED_TOKENS.search(runtime_log)
|
||||
input_tokens = int(prompt_match.group(1)) if prompt_match else None
|
||||
output_tokens = (int(sampled_match.group(1)) - input_tokens
|
||||
if sampled_match and input_tokens is not None else None)
|
||||
if output_tokens is not None and output_tokens < 0:
|
||||
raise ValueError("runtime token counters inconsistent")
|
||||
log_path = os.environ.get("REVIEWER_RUNTIME_LOG")
|
||||
if log_path:
|
||||
Path(log_path).write_text(runtime_log, encoding="utf-8")
|
||||
# Only surrounding whitespace is removed. Internal text survives to the
|
||||
# reviewer's exact allowed-edit validator, and raw stdout is retained.
|
||||
candidate = raw.strip(" \t\r\n") + ("\n" if source.endswith("\n") else "")
|
||||
return {"candidate": candidate, "model_id": lock["base_model_id"],
|
||||
"model_revision": lock["base_model_revision"],
|
||||
"input_tokens": input_tokens, "output_tokens": output_tokens,
|
||||
"raw_response": raw,
|
||||
"runtime_response": {"prompt": prompt, "raw_stdout": raw,
|
||||
"prompt_eval_tokens": input_tokens,
|
||||
"sampler_total_tokens": int(sampled_match.group(1)) if sampled_match else None,
|
||||
"output_tokens_method": "sampler_total_tokens - prompt_eval_tokens",
|
||||
"runtime_log_counter_lines": [line for line in runtime_log.splitlines()
|
||||
if "common_perf_print:" in line and ("samplers time" in line or "prompt eval time" in line)]}}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"base_model_id": "HuggingFaceTB/SmolLM2-135M-Instruct",
|
||||
"base_model_revision": "12fd25f77366fa6b3b4b768ec3050bf629380bac",
|
||||
"license": "apache-2.0",
|
||||
"quantized_repo": "QuantFactory/SmolLM2-135M-Instruct-GGUF",
|
||||
"quantized_revision": "476854d00ede130660aba430d15f9347ad2e7d0e",
|
||||
"quantized_filename": "SmolLM2-135M-Instruct.Q4_0.gguf",
|
||||
"quantized_sha256": "f68203bfb98b1b1e8c64fac75fab10c4e36acac081609573b4df0fcc19c90dd9",
|
||||
"quantized_url": "https://huggingface.co/QuantFactory/SmolLM2-135M-Instruct-GGUF/resolve/476854d00ede130660aba430d15f9347ad2e7d0e/SmolLM2-135M-Instruct.Q4_0.gguf?download=true",
|
||||
"format": "GGUF",
|
||||
"quantization": "Q4_0",
|
||||
"runtime": "llama.cpp",
|
||||
"entrypoint": "llama-completion",
|
||||
"runtime_tag": "b12785",
|
||||
"runtime_commit": "55d482814bb3b985daa7bfa175c6d628fc27beac",
|
||||
"runtime_archive": "llama-b12785-bin-ubuntu-x64.tar.gz",
|
||||
"runtime_archive_sha256": "c52fdce909b3e55b2e763e9a8b08b2b006281ebc5b5c6c8ea91e5d2075c8fd27",
|
||||
"runtime_url": "https://github.com/ggml-org/llama.cpp/releases/download/b12785/llama-b12785-bin-ubuntu-x64.tar.gz",
|
||||
"architecture": "linux-amd64-cpu",
|
||||
"context_tokens": 64,
|
||||
"threads": 1,
|
||||
"parallel_slots": 1,
|
||||
"max_output_tokens": 8,
|
||||
"temperature": 0,
|
||||
"seed": 1,
|
||||
"prompt_template": "Input: print(\"hi\"\nOutput: print(\"hi\")\nInput: {source_line}\nOutput:",
|
||||
"stop": [
|
||||
"\n"
|
||||
],
|
||||
"memory_target_bytes": 250000000,
|
||||
"batch_tokens": 32,
|
||||
"microbatch_tokens": 32
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Download and checksum the pinned public GGUF model and llama.cpp CPU archive."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tarfile
|
||||
import urllib.request
|
||||
|
||||
LOCK = Path(__file__).with_name("model-lock.json")
|
||||
|
||||
|
||||
def digest(path):
|
||||
value = hashlib.sha256()
|
||||
with Path(path).open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
value.update(chunk)
|
||||
return value.hexdigest()
|
||||
|
||||
|
||||
def fetch(url, target, expected):
|
||||
if target.is_file() and digest(target) == expected:
|
||||
return
|
||||
part = target.with_name(target.name + ".part")
|
||||
part.unlink(missing_ok=True)
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "ssw590-member1"}), timeout=60) as source, part.open("wb") as dest:
|
||||
shutil.copyfileobj(source, dest, 1024 * 1024)
|
||||
if digest(part) != expected:
|
||||
raise ValueError(f"checksum mismatch: {target.name}")
|
||||
part.replace(target)
|
||||
finally:
|
||||
part.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--dest", type=Path, required=True, help="directory outside Git for model/runtime files")
|
||||
args = parser.parse_args()
|
||||
lock = json.loads(LOCK.read_text())
|
||||
args.dest.mkdir(parents=True, exist_ok=True)
|
||||
model = args.dest / lock["quantized_filename"]
|
||||
archive = args.dest / lock["runtime_archive"]
|
||||
fetch(lock["quantized_url"], model, lock["quantized_sha256"])
|
||||
fetch(lock["runtime_url"], archive, lock["runtime_archive_sha256"])
|
||||
with tarfile.open(archive) as bundle:
|
||||
members = bundle.getmembers()
|
||||
root_name = "llama-" + lock["runtime_tag"]
|
||||
if any(member.name != root_name and not member.name.startswith(root_name + "/") for member in members):
|
||||
raise ValueError("unexpected runtime archive layout")
|
||||
bundle.extractall(args.dest, filter="data")
|
||||
server = args.dest / f"llama-{lock['runtime_tag']}" / lock["entrypoint"]
|
||||
if not server.is_file():
|
||||
raise FileNotFoundError("runtime entrypoint missing from verified archive")
|
||||
print(f"REVIEWER_MODEL_PATH={model}")
|
||||
print(f"REVIEWER_LLAMA_COMPLETION={server}")
|
||||
print("Install libgomp1 in the execution image and ensure its directory is on the loader path.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user