Text Generation
Transformers
Safetensors
English
Arabic
code
qwen3_5
image-text-to-text
qwen3.8
rootformer
coding
software-engineering
agentic
arabic-grammarian-algorithms
qata-al-waswasa
next-codewazn-prediction
vllm
bfloat16
conversational
Run this model with HF Jobs
Run enver/rootformer-code-v19.2-qwen38-nwp on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use enver/rootformer-code-v19.2-qwen38-nwp with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use enver/rootformer-code-v19.2-qwen38-nwp with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="enver/rootformer-code-v19.2-qwen38-nwp") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("enver/rootformer-code-v19.2-qwen38-nwp") model = AutoModelForMultimodalLM.from_pretrained("enver/rootformer-code-v19.2-qwen38-nwp", device_map="auto") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use enver/rootformer-code-v19.2-qwen38-nwp with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "enver/rootformer-code-v19.2-qwen38-nwp" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "enver/rootformer-code-v19.2-qwen38-nwp", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/enver/rootformer-code-v19.2-qwen38-nwp
- SGLang
How to use enver/rootformer-code-v19.2-qwen38-nwp with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "enver/rootformer-code-v19.2-qwen38-nwp" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "enver/rootformer-code-v19.2-qwen38-nwp", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "enver/rootformer-code-v19.2-qwen38-nwp" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "enver/rootformer-code-v19.2-qwen38-nwp", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use enver/rootformer-code-v19.2-qwen38-nwp with Docker Model Runner:
docker model run hf.co/enver/rootformer-code-v19.2-qwen38-nwp
File size: 21,133 Bytes
6b972c1 | 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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
nwp_v3_counterexample_engine.py
===============================
Pure-CPU engine for **`NWP-v3` (Next-CodeWazn Prediction v3: *Tawaqquf* Self-Test Quarantine +
Stage 18.8 True-Diction Fusion + *Al-Taṣghīr* Minimal-Counterexample Witness Judging)**!
Directly fixes the 4 root causes that left `40` already-solved `Oracle@8` tasks on the table in
Stage 19.2 (`506/615` selected vs `546/615` `Oracle@8`):
1. **Al-Azharī *Tawaqquf* Single-Witness Self-Test Quarantine (`AZ-01`, `Tahdhīb` L613–616)**:
When `>= 3` licit candidates pass public tests, any LLM-synthesized self-assertion (`tard`/`aks`)
passed by ONLY `1` candidate (`agree == 1`) is quarantined (`w = 0.10` instead of `1.00`) so a
coinciding hallucinated assertion can never override a multi-candidate consensus cluster.
2. **Stage 18.8 True-Diction Fusion (`khalil_code_wazn_calculator.py`)**:
Runs `score_candidate_true_diction` on every unique candidate (live `inspect.signature` `API_MUHMAL`
hard kills, mathematical law oracles, radix negative traps, unmemoized exponential recursion,
tuple-arity mismatches, input mutation checks) — recovering Stage 18.8's `154/164` `HumanEval+` edge!
3. **Al-Mubarrad *al-Taṣghīr* Minimal-Counterexample Multi-Witness Discovery (`MB-03`, `Muqtaḍab` L9863)**:
Fuses LLM probe calls with deterministic Al-Khalīl `root_probes` (`synthesize_deterministic_root_inputs`),
collects ALL concrete inputs `x*` where Candidate A and Candidate B disagree, sorts them **shortest-first**
(*al-Taṣghīr* downscaling to minimal form!), and presents up to `3` concrete `(call -> out_A vs out_B)`
witnesses to the symmetric judge!
4. **Al-Akhfash De Morgan (`AK-02`) + Al-Zajjājī Polarity (`ZH-02`) Symmetric Judge Prompt**:
Highlights negated disjunctions (`NOT(X) AND NOT(Y)`) and concrete input-output witnesses so the
symmetric `Judge(A,B)` + `Judge(B,A)` tournament traces the exact minimal counterexample!
"""
from __future__ import annotations
import ast
import concurrent.futures
import math
import re
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
ROOT = Path("/workspace/rootstar") if Path("/workspace/rootstar").exists() else Path(__file__).resolve().parent.parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from scripts.andalusian_al_farq_verifier import ( # noqa: E402
_run_candidate_probes,
extract_probe_calls_from_tests,
)
from scripts.andalusian_code_verifier import khalil_code_licit_check # noqa: E402
from scripts.eval_code_sandbox import _run_script_subprocess, extract_python_code # noqa: E402
from scripts.khalil_code_wazn_calculator import ( # noqa: E402
CodeRoot,
extract_code_root,
score_candidate_true_diction,
synthesize_deterministic_root_inputs,
)
from scripts.stage21_nwp_trace_engine import compile_ak02_negation_hint # noqa: E402
def normalize_ast_key(code: str) -> str:
try:
return ast.unparse(ast.parse(code))
except Exception:
return re.sub(r"\s+", " ", (code or "").strip())
def _format_probe_out(out_pair: Tuple[str, str]) -> str:
kind, val = out_pair
if kind == "OK":
return str(val)
if str(val).startswith("EXC:"):
return f"raises {val[4:]}"
return f"raises {val}"
def find_multi_counterexamples_mb03(
probe_calls: List[str],
sig_a: Optional[Tuple[Tuple[str, str], ...]],
sig_b: Optional[Tuple[Tuple[str, str], ...]],
code_root: Optional[CodeRoot] = None,
root_probes: Optional[List[Tuple[Any, ...]]] = None,
td_res_a: Optional[List[str]] = None,
td_res_b: Optional[List[str]] = None,
max_witnesses: int = 3,
) -> List[Dict[str, Any]]:
"""
MB-03 (*al-Taṣghīr Yarudd ilā al-Aṣl*):
Collects ALL concrete calls where Candidate A and Candidate B return different outputs
across BOTH LLM-extracted probe calls and deterministic Al-Khalīl `root_probes`, then
sorts them by expression length ascending (minimal counterexample first!) and returns up to `max_witnesses`.
"""
diffs: List[Dict[str, Any]] = []
seen_calls = set()
if sig_a is not None and sig_b is not None and len(sig_a) == len(probe_calls) and len(sig_b) == len(probe_calls):
for call_expr, oa, ob in zip(probe_calls, sig_a, sig_b):
if oa != ob and call_expr not in seen_calls:
seen_calls.add(call_expr)
diffs.append(
{
"call_expr": call_expr,
"out_a": oa,
"out_b": ob,
"source": "probe_call",
}
)
if (
code_root is not None
and code_root.entry_point
and root_probes
and td_res_a is not None
and td_res_b is not None
and len(td_res_a) == len(root_probes)
and len(td_res_b) == len(root_probes)
):
for inp, ra, rb in zip(root_probes, td_res_a, td_res_b):
if ra != rb:
arg_str = ", ".join(repr(x) for x in inp)
call_expr = f"{code_root.entry_point}({arg_str})"
if call_expr not in seen_calls:
seen_calls.add(call_expr)
oa = ("ERR", ra[4:]) if str(ra).startswith("EXC:") else ("OK", str(ra))
ob = ("ERR", rb[4:]) if str(rb).startswith("EXC:") else ("OK", str(rb))
diffs.append(
{
"call_expr": call_expr,
"out_a": oa,
"out_b": ob,
"source": "khalil_root_probe",
}
)
# MB-03 *al-Taṣghīr*: sort shortest/simplest concrete counterexample first!
diffs.sort(key=lambda d: (len(d["call_expr"]), 0 if d["source"] == "khalil_root_probe" else 1, d["call_expr"]))
return diffs[:max_witnesses]
def build_nwp_v3_counterexample_judge_prompt(
user_prompt: str,
code_a: str,
trace_a: str,
code_b: str,
trace_b: str,
counterexamples: Optional[List[Dict[str, Any]]] = None,
swapped: bool = False,
) -> str:
"""
Constructs the NWP-v3 Symmetric Pairwise Judge prompt combining:
- AK-02 De Morgan Negated Constraint Reminder
- MB-03 Minimal Concrete Counterexample Witnesses (`x* -> y_A vs y_B`)
- True-Diction + Public/Consensus Execution Summary
- ZH-02 Polarity Checklist (`[WAJIB]` positive + `[MUMTANI']` negated requirements)
"""
ak02_hint = compile_ak02_negation_hint(user_prompt)
ak02_blk = f"\nDe Morgan Constraint Guard [AK-02]: {ak02_hint}\n" if "AK-02" in ak02_hint else ""
ce_lines: List[str] = []
if counterexamples:
ce_lines.append("=== CONCRETE COUNTEREXAMPLE WITNESSES (Shortest First [MB-03 al-Taṣghīr]) ===")
ce_lines.append("Candidate A and Candidate B produce DIFFERENT outputs on these exact concrete calls:")
for idx, ce in enumerate(counterexamples[:3], start=1):
oa = ce["out_b"] if swapped else ce["out_a"]
ob = ce["out_a"] if swapped else ce["out_b"]
ce_lines.append(
f" Witness #{idx}: `{ce['call_expr']}`\n"
f" -> Candidate A output: `{_format_probe_out(oa)}`\n"
f" -> Candidate B output: `{_format_probe_out(ob)}`"
)
ce_lines.append(
"MANDATORY STEP: Inside `<think>`, trace Witness #1 step-by-step against the Specification to prove which output is right!\n"
)
ce_blk = "\n".join(ce_lines)
return (
f"Audit **Candidate A** vs **Candidate B** against EVERY requirement of the Specification below.\n\n"
f"=== SPECIFICATION ===\n{user_prompt}\n"
f"{ak02_blk}\n"
f"{ce_blk}\n"
f"=== CANDIDATE A ===\n```python\n{code_a[:3400]}\n```\n"
f"Verification Ledger A: {trace_a[:550]}\n\n"
f"=== CANDIDATE B ===\n```python\n{code_b[:3400]}\n```\n"
f"Verification Ledger B: {trace_b[:550]}\n\n"
f"Audit Checklist (Al-Sibr wa-l-Taqsīm + ZH-02 Polarity Protocol):\n"
f" 1. [MB-03 Counterexample Witness]: If Concrete Counterexample Witnesses are listed above, trace Witness #1 by hand and determine whether Candidate A or Candidate B produces the spec-mandated result.\n"
f" 2. [WAJIB Positive Contract]: Exact signature, return type, ordering, tie-breaking, and value semantics.\n"
f" 3. [MUMTANI' Negated & Edge Guards]: Empty/zero/negative boundaries, required exceptions (`Raises:`), non-mutation, and time complexity.\n"
f" 4. [Musta'mal API Truth]: Real Python 3 library signatures and return types.\n\n"
f"Complete your audit concisely INSIDE `<think>` (do NOT pick TIE unless both candidates are behaviorally identical). "
f"Immediately after `</think>`, your VERY FIRST LINE must be ONLY one of:\n"
f"VERDICT: A\nVERDICT: B\nVERDICT: TIE\n"
f"(followed optionally by ONE short sentence naming the decisive witness or bug)."
)
def evaluate_nwp_v3_matrix(
candidates: List[str],
cand_logprobs: List[float],
prompt_text: str,
public_tests: List[str],
tard_tests: List[str],
aks_tests: List[str],
*,
entry_point: Optional[str] = None,
code_root: Optional[CodeRoot] = None,
root_probes: Optional[List[Tuple[Any, ...]]] = None,
setup_code: str = "",
prompt_imports: str = "",
quarantine_single_witness: bool = True,
max_workers: int = 10,
timeout_sec: float = 2.5,
) -> Dict[str, Any]:
"""
NWP-v3 Unified Verification Matrix:
1. Static Licit Check + Stage 18.8 `score_candidate_true_diction` (live `inspect.signature` + deterministic `root_probes` + math laws).
2. Public doctests (`100.0` each) + `*al-Ṭard*` + `*al-ʿAks*` self-tests WITH `AZ-01` *Tawaqquf* single-witness quarantine!
3. Multi-witness `MB-03` *al-Taṣghīr* minimal counterexample discovery across LLM probe calls + deterministic `root_probes`!
"""
n_c = len(candidates)
codes = [extract_python_code(c) for c in candidates]
if code_root is None:
code_root = extract_code_root(prompt_text, entry_point=entry_point)
if root_probes is None:
root_probes = synthesize_deterministic_root_inputs(code_root)
licit_info = [khalil_code_licit_check(code, prompt_text, entry_point=entry_point) for code in codes]
static_ok = [li["is_licit"] for li in licit_info]
static_errs = [li["hard_issues"] for li in licit_info]
# Deduplicate unique code strings
u_map: Dict[str, int] = {}
c_to_u: List[int] = []
u_codes: List[str] = []
for code in codes:
if code not in u_map:
u_map[code] = len(u_codes)
u_codes.append(code)
c_to_u.append(u_map[code])
# Run Stage 18.8 True-Diction (AST + Live API + Deterministic Root Probes + Math Oracles) on unique valid candidates!
u_td: Dict[int, Dict[str, Any]] = {}
valid_us = [ui for ui in range(len(u_codes)) if any(static_ok[i] for i, u in enumerate(c_to_u) if u == ui)]
def _run_td(ui: int) -> Tuple[int, Dict[str, Any]]:
full_c = f"{prompt_imports}\n{setup_code}\n\n{u_codes[ui]}".strip() if (prompt_imports or setup_code) else u_codes[ui]
return ui, score_candidate_true_diction(full_c, prompt_text, code_root, probe_inputs=root_probes)
if valid_us:
with concurrent.futures.ThreadPoolExecutor(max_workers=min(max_workers, len(valid_us))) as ex:
for ui, td_res in ex.map(_run_td, valid_us):
u_td[ui] = td_res
# Apply Tier-1 True-Diction `is_licit` kills (e.g., live `inspect.signature` API_MUHMAL or return tuple arity mismatch)
api_muhmal_kills = 0
for ci in range(n_c):
if not static_ok[ci]:
continue
td_c = u_td.get(c_to_u[ci])
if td_c is not None and not td_c["is_licit"]:
static_ok[ci] = False
static_errs[ci] = list(td_c["ast"].get("hard_issues", ["TRUE_DICTION_MUHMAL"]))
api_muhmal_kills += 1
valid_us = [ui for ui in range(len(u_codes)) if any(static_ok[i] for i, u in enumerate(c_to_u) if u == ui)]
# Deduplicate tests while keeping source tag
seen_t = set()
all_tests: List[Tuple[str, str]] = []
for t in public_tests:
if t not in seen_t:
seen_t.add(t)
all_tests.append(("pub", t))
for t in tard_tests:
if t not in seen_t:
seen_t.add(t)
all_tests.append(("tard", t))
for t in aks_tests:
if t not in seen_t:
seen_t.add(t)
all_tests.append(("aks", t))
n_pub = sum(1 for k, _ in all_tests if k == "pub")
u_pass: Dict[Tuple[int, int], bool] = {}
u_first_err: Dict[int, str] = {}
u_pub_err: Dict[int, str] = {}
def _exec_t(u_idx: int, t_idx: int, t_kind: str, t_stmt: str) -> Tuple[int, int, str, bool, str]:
script = f"{prompt_imports}\n{setup_code}\n\n{u_codes[u_idx]}\n\n{t_stmt}\n"
ok, err = _run_script_subprocess(script, timeout_sec=timeout_sec)
return u_idx, t_idx, t_kind, ok, err
jobs = [(ui, ti, tk, ts) for ui in valid_us for ti, (tk, ts) in enumerate(all_tests)]
if jobs:
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as ex:
for ui, ti, tk, ok, err in ex.map(lambda j: _exec_t(*j), jobs):
u_pass[(ui, ti)] = ok
if not ok:
if tk == "pub" and ui not in u_pub_err:
u_pub_err[ui] = err
if ui not in u_first_err:
u_first_err[ui] = err
# Count how many candidates survive public tests
pub_survivors = sum(
1 for ci in range(n_c)
if static_ok[ci] and all(u_pass.get((c_to_u[ci], pi), False) for pi in range(n_pub))
)
# AZ-01 *Tawaqquf* Consensus Self-Test Weighting:
# Quarantine single-witness assertions (`agree == 1`) when `pub_survivors >= 3` so a lone hallucinated
# self-test cannot poison the score matrix!
test_w: List[float] = []
quarantined_assertions = 0
for ti, (tk, _) in enumerate(all_tests):
if tk == "pub":
test_w.append(100.0)
else:
agree = 0
for ci in range(n_c):
ui = c_to_u[ci]
if not static_ok[ci]:
continue
pub_all = all(u_pass.get((ui, pi), False) for pi in range(n_pub))
if pub_all and u_pass.get((ui, ti), False):
agree += 1
if agree == 0:
test_w.append(0.0)
elif quarantine_single_witness and agree == 1 and pub_survivors >= 3:
test_w.append(0.10)
quarantined_assertions += 1
else:
mult = 1.15 if (tk == "aks" and agree >= 2) else 1.0
test_w.append(mult * math.sqrt(agree))
# Execute LLM probe calls AND combine with deterministic `root_probes` for behavioral clustering!
probe_calls = extract_probe_calls_from_tests([ts for tk, ts in all_tests], entry_point)
u_probes: Dict[int, Optional[List[Tuple[str, str]]]] = {}
if probe_calls and len(valid_us) >= 2:
with concurrent.futures.ThreadPoolExecutor(max_workers=min(max_workers, len(valid_us))) as ex:
fmap = {
ex.submit(_run_candidate_probes, u_codes[ui], probe_calls, prompt_imports, setup_code, timeout_sec): ui
for ui in valid_us
}
for fut in concurrent.futures.as_completed(fmap):
u_probes[fmap[fut]] = fut.result()
# Build joint behavioral signature = (LLM probe outputs + deterministic Al-Khalīl root_probe outputs)!
sig_counts: Dict[Tuple[Any, ...], int] = {}
c_sigs: List[Optional[Tuple[Any, ...]]] = []
c_llm_sigs: List[Optional[Tuple[Tuple[str, str], ...]]] = []
c_td_results: List[List[str]] = []
for ci in range(n_c):
ui = c_to_u[ci]
td_c = u_td.get(ui, {})
td_res_list = list(td_c.get("probes", {}).get("results", []))
c_td_results.append(td_res_list)
if not static_ok[ci]:
c_sigs.append(None)
c_llm_sigs.append(None)
continue
p_all = all(u_pass.get((ui, pi), False) for pi in range(n_pub))
pr = u_probes.get(ui)
llm_sig = tuple(pr) if pr is not None else ()
c_llm_sigs.append(tuple(pr) if pr is not None else None)
if p_all and (pr is not None or td_res_list):
joint_sig = (llm_sig, tuple(td_res_list))
sig_counts[joint_sig] = sig_counts.get(joint_sig, 0) + 1
c_sigs.append(joint_sig)
else:
c_sigs.append(None)
scores: List[float] = []
pub_counts: List[int] = []
syn_counts: List[int] = []
td_scores: List[float] = []
for ci in range(n_c):
ui = c_to_u[ci]
if not static_ok[ci]:
scores.append(-1e6 + cand_logprobs[ci])
pub_counts.append(0)
syn_counts.append(0)
td_scores.append(-100.0)
continue
p_ok = sum(1 for pi in range(n_pub) if u_pass.get((ui, pi), False))
s_ok = sum(1 for ti in range(n_pub, len(all_tests)) if u_pass.get((ui, ti), False))
w_sum = sum(test_w[ti] for ti in range(len(all_tests)) if u_pass.get((ui, ti), False))
cl_sz = sig_counts.get(c_sigs[ci], 1) if c_sigs[ci] is not None else 1
cl_bonus = 1.5 * math.sqrt(cl_sz)
khalil_pen = licit_info[ci]["soft_penalty"] + licit_info[ci]["hadhf_cost"]
td_c = u_td.get(ui, {})
td_raw = float(td_c.get("score", 0.0))
td_pen = max(-25.0, min(0.0, td_raw))
td_scores.append(round(td_raw, 3))
score = w_sum + cl_bonus + 0.85 * td_pen + 0.65 * cand_logprobs[ci] - khalil_pen + (0.04 if ci == 0 else 0.0)
scores.append(score)
pub_counts.append(p_ok)
syn_counts.append(s_ok)
# Identify top-2 distinct behavioral clusters (both passing ALL public tests!) and extract MB-03 multi-witness counterexamples!
al_farq_query: Optional[Dict[str, Any]] = None
ranked_clusters: List[Tuple[float, Tuple[Any, ...], List[int]]] = []
by_sig: Dict[Tuple[Any, ...], List[int]] = {}
for ci, sig in enumerate(c_sigs):
if sig is not None:
by_sig.setdefault(sig, []).append(ci)
for sig, c_idxs in by_sig.items():
top_sc = max(scores[ci] for ci in c_idxs)
ranked_clusters.append((top_sc, sig, c_idxs))
ranked_clusters.sort(key=lambda x: x[0], reverse=True)
if len(ranked_clusters) >= 2:
sc_a, _sig_a, idxs_a = ranked_clusters[0]
sc_b, _sig_b, idxs_b = ranked_clusters[1]
rep_a = max(idxs_a, key=lambda c: scores[c])
rep_b = max(idxs_b, key=lambda c: scores[c])
if (sc_a - sc_b) <= 8.5:
witnesses = find_multi_counterexamples_mb03(
probe_calls=probe_calls,
sig_a=c_llm_sigs[rep_a],
sig_b=c_llm_sigs[rep_b],
code_root=code_root,
root_probes=root_probes,
td_res_a=c_td_results[rep_a],
td_res_b=c_td_results[rep_b],
max_witnesses=3,
)
if witnesses:
w0 = witnesses[0]
al_farq_query = {
"call_expr": w0["call_expr"],
"out_a": w0["out_a"],
"out_b": w0["out_b"],
"witnesses": witnesses,
"idxs_a": idxs_a,
"idxs_b": idxs_b,
"rep_a": rep_a,
"rep_b": rep_b,
"score_a": round(sc_a, 3),
"score_b": round(sc_b, 3),
}
best_idx = max(range(n_c), key=lambda i: scores[i])
best_u = c_to_u[best_idx]
needs_repair = (not static_ok[best_idx]) or (n_pub > 0 and pub_counts[best_idx] < n_pub)
repair_err = "; ".join(static_errs[best_idx]) if not static_ok[best_idx] else (u_pub_err.get(best_u) or u_first_err.get(best_u, ""))
if not repair_err and scores[best_idx] <= -1e5:
for ui in range(len(u_codes)):
td_c = u_td.get(ui, {})
hi = td_c.get("ast", {}).get("hard_issues", [])
if hi:
repair_err = "; ".join(hi[:2])
break
return {
"best_idx": best_idx,
"best_code": codes[best_idx],
"codes": codes,
"scores": [round(s, 3) for s in scores],
"td_scores": td_scores,
"pub_passed": pub_counts,
"syn_passed": syn_counts,
"n_pub": n_pub,
"n_syn": len(all_tests) - n_pub,
"num_clusters": len(ranked_clusters),
"quarantined_assertions": quarantined_assertions,
"api_muhmal_kills": api_muhmal_kills,
"al_farq_query": al_farq_query,
"needs_repair": needs_repair,
"repair_err": repair_err,
}
|