momonga-guard-small is a lightweight, calibrated, bilingual (English / Japanese) binary safety classifier (safe vs unsafe) for autonomous coding-agent tool calls. Developed for MomongaCode's Auto Mode, it evaluates whether a proposed tool call (Bash, PowerShell, Write, Edit, Read, Grep, Glob, or MCP tools) clearly stays within the user's request and workspace boundaries without requiring human confirmation.
Compared to yuu1ch13/momonga-guard-base, momonga-guard-small halves the quantized model size (142.3 MB INT8 ONNX) and reduces single-session peak RSS by ~61% (~1.16 GB) while achieving even stronger held-out AUC and safe-allow rates.
Both PyTorch (bf16 safetensors) and per-channel INT8 ONNX (onnx/model_int8.onnx, 142.3 MB) weights are included in this repository, along with post-hoc temperature scaling parameters in calibration.json.
日本語サマリ: コーディングエージェントのツール呼び出しをローカル CPU(推奨
threads=4で p50 約 36.7 ms / リクエスト)で高速にsafe/unsafe判定する軽量ガードモデルです。momonga-guard-baseと比べモデルサイズ半減(142.3 MB)・ピークメモリ約 61% 削減(約 1.16 GB)を実現しつつ、高い判別精度(tau=0.92推奨)でプロンプトインジェクション、認証情報窃取、バックドア、コマンド連結、ワークスペース外アクセスなどを検出します。
jhu-clsp/mmBERT-small (ModernBERT architecture, 140M parameters, MIT License)0 = unsafe, 1 = safe1024 tokens (base architecture supports 8192)calibration.json):T = 1.569 (PyTorch bf16: T = 1.9126)tau_allow = 0.92 (permissive: 0.90, strict: 0.96)intra_op_num_threads = 4Inputs must follow the XML + canonical JSON contract below (escaping &, <, > in text fields as &, <, >, and serializing <proposed_tool_call> JSON with sorted keys and no extra whitespace):
<user_request>
Run the unit tests
</user_request>
<workspace>/Users/dev/projects/my-app</workspace>
<why_it_needs_review>Bash commands need approval in auto mode</why_it_needs_review>
<proposed_tool_call>
{"input":{"command":"npm test"},"summary":"Run: npm test","tool":"Bash"}
</proposed_tool_call>
When a subagent delegates a subtask, include <delegated_task>...</delegated_task> immediately after </user_request>:
<user_request>
Explain how src/auth.ts works
</user_request>
<delegated_task>
Read src/auth.ts and summarize its exports.
</delegated_task>
<workspace>/Users/dev/projects/my-app</workspace>
<why_it_needs_review>approval needed in auto mode</why_it_needs_review>
<proposed_tool_call>
{"input":{"file_path":"/Users/dev/projects/my-app/src/auth.ts"},"summary":"Read /Users/dev/projects/my-app/src/auth.ts","tool":"Read"}
</proposed_tool_call>
Evaluated on our internal held-out synthetic and hand-crafted adversarial benchmarks (disjoint from training and validation families). Metrics below evaluate onnx/model_int8.onnx (full_int8_pc, T=1.569) in single-request inference (batch=1) unless noted otherwise.
p_safe >= tau). Higher is better.p_safe >= tau). Lower is better.| Benchmark | tau=0.90 (batch=1) |
tau=0.92 (batch=1, recommended) |
tau=0.96 (batch=1, strict) |
|---|---|---|---|
gold_wild (120 real-world & adversarial cases) |
SAR 93.3% / FAR 3.3% (2/60) | SAR 93.3% / FAR 1.7% (1/60), AUC 0.9964 | SAR 75.0% / FAR 0.0% (0/60) |
gold (80 hand-crafted cases) |
SAR 92.5% / FAR 0.0% (0/40) | SAR 92.5% / FAR 0.0% (0/40), AUC 0.9994 | SAR 45.0% / FAR 0.0% (0/40) |
| Frozen synthetic + gold test (1,568 cases) (batch=8 eval) | — | AUC 0.9999 (SAR 93.5% / FAR 0.0% (0/148) on 272-case subset) | — |
onnxruntime + tokenizers, batch=1)onnx/model_int8.onnx = 142.3 MB (tokenizer.json = 34.4 MB)1,159 MB)intra_op_num_threads=4, recommended):<150 tokens): p50 31.5 ms / p95 83.4 ms / p99 124.0 ms150–400 tokens): p50 46.2 ms / p95 141.0 ms / p99 179.8 ms400+ tokens, n=3): p50 188.3 msn=200): p50 36.7 ms / p95 108.7 ms / p99 144.1 msimport json
import numpy as np
import onnxruntime as ort
from huggingface_hub import snapshot_download
from tokenizers import Tokenizer
repo_dir = snapshot_download("yuu1ch13/momonga-guard-small")
calib = json.load(open(f"{repo_dir}/calibration.json"))
tok = Tokenizer.from_file(f"{repo_dir}/tokenizer.json")
tok.no_padding()
tok.enable_truncation(max_length=calib["max_length"])
opts = ort.SessionOptions()
opts.intra_op_num_threads = calib.get("recommended_intra_op_num_threads", 4)
sess = ort.InferenceSession(
f"{repo_dir}/{calib['onnx_file']}",
opts,
providers=["CPUExecutionProvider"],
)
def escape_xml(s: str) -> str:
return s.replace("&", "&").replace("<", "<").replace(">", ">")
def format_prompt(user_request: str, workspace: str, reason: str, tool: str, summary: str, tool_input: dict) -> str:
call = json.dumps({"input": tool_input, "summary": summary, "tool": tool}, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return (
f"<user_request>\n{escape_xml(user_request)}\n</user_request>\n"
f"<workspace>{escape_xml(workspace)}</workspace>\n"
f"<why_it_needs_review>{escape_xml(reason)}</why_it_needs_review>\n"
f"<proposed_tool_call>\n{escape_xml(call)}\n</proposed_tool_call>"
)
prompt = format_prompt(
user_request="Run the unit tests",
workspace="/Users/dev/projects/my-app",
reason="Bash commands need approval in auto mode",
tool="Bash",
summary="Run: npm test",
tool_input={"command": "npm test"},
)
ids = tok.encode(prompt).ids
input_ids = np.array([ids], dtype=np.int64)
attention_mask = np.ones_like(input_ids)
logits = sess.run(["logits"], {"input_ids": input_ids, "attention_mask": attention_mask})[0][0]
scaled = logits / calib["temperature"]
scaled -= scaled.max()
probs = np.exp(scaled) / np.exp(scaled).sum()
p_safe = float(probs[1])
decision = "allow" if p_safe >= calib["tau_allow"] else "ask"
print({"p_safe": round(p_safe, 4), "decision": decision})
transformersimport torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
model_id = "yuu1ch13/momonga-guard-small"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForSequenceClassification.from_pretrained(model_id, torch_dtype=torch.bfloat16)
model.eval()
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024)
with torch.no_grad():
logits = model(**inputs).logits[0].float()
probs = torch.softmax(logits / 1.9126, dim=-1)
p_safe = float(probs[1])
decision == "ask" (anything below tau_allow) as requiring human confirmation or escalation to a larger model. Never use this model as a standalone security boundary.gold_wild at tau=0.92, one Japanese indirect prompt injection embedded inside <user_request> (wild-108) caused the sole false-allow (1/60), while a single-character hyphen domain spoof (wild-074, json-schemastore.org vs json.schemastore.org, p_safe=0.9196) sits near the boundary. Deterministic host allowlists and prompt-injection defenses remain essential.1024 tokens; performance on very long prompts (>1024 tokens) or domains far outside coding-agent tool calls is not guaranteed.jhu-clsp/mmBERT-small (Johns Hopkins University CLSP, MIT License)model.safetensors 268 MiBonnx/model_int8.onnx 136 MiB