Spaces:
Sleeping
Sleeping
Add interactive C* ZeroGPU demo
Browse files
README.md
CHANGED
|
@@ -1,13 +1,22 @@
|
|
| 1 |
---
|
| 2 |
title: PLSemanticsBench
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
-
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: PLSemanticsBench
|
| 3 |
+
emoji: π§
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: yellow
|
| 6 |
sdk: gradio
|
| 7 |
+
python_version: 3.12.12
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
+
suggested_hardware: zero-a10g
|
| 10 |
+
license: mit
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# PLSemanticsBench interactive demo
|
| 14 |
+
|
| 15 |
+
This Space powers the βTry it yourselfβ panel on the
|
| 16 |
+
[PLSemanticsBench project page](https://engineeringsoftware.github.io/PLSemanticsBench/).
|
| 17 |
+
It accepts a standard C* program, applies the selected benchmark intervention,
|
| 18 |
+
loads the corresponding formal semantics from the
|
| 19 |
+
[PLSemanticsBench dataset](https://huggingface.co/datasets/EngineeringSoftware/PLSemanticsBench),
|
| 20 |
+
and runs `deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` on ZeroGPU.
|
| 21 |
+
|
| 22 |
+
The named Gradio API endpoint is `/predict`.
|
app.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 9 |
+
import gradio as gr
|
| 10 |
+
import torch
|
| 11 |
+
from datasets import load_dataset
|
| 12 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 13 |
+
|
| 14 |
+
from cstar import (
|
| 15 |
+
DATASET_ID,
|
| 16 |
+
INTERVENTIONS,
|
| 17 |
+
SemanticsSpec,
|
| 18 |
+
build_predstate_prompt,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
MODEL_ID = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
| 22 |
+
DEFAULT_PROGRAM = """int a;
|
| 23 |
+
int b;
|
| 24 |
+
int ans;
|
| 25 |
+
a = 10;
|
| 26 |
+
b = 3;
|
| 27 |
+
ans = (a + b);"""
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _load_semantics() -> dict[tuple[str, str], SemanticsSpec]:
|
| 31 |
+
specs: dict[tuple[str, str], SemanticsSpec] = {}
|
| 32 |
+
for formalization in ("S", "K"):
|
| 33 |
+
standard_split = load_dataset(
|
| 34 |
+
DATASET_ID,
|
| 35 |
+
"predstate",
|
| 36 |
+
split=f"{formalization}_Standard_Human_Written",
|
| 37 |
+
)
|
| 38 |
+
standard = standard_split[0]
|
| 39 |
+
specs[(formalization, "Standard")] = SemanticsSpec(
|
| 40 |
+
syntax=standard["syntax"],
|
| 41 |
+
semantics=standard["semantics"],
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
nonstandard_split_name = f"{formalization}_NonStandard_Human_Written"
|
| 45 |
+
nonstandard_split = load_dataset(
|
| 46 |
+
DATASET_ID,
|
| 47 |
+
"predstate",
|
| 48 |
+
split=nonstandard_split_name,
|
| 49 |
+
)
|
| 50 |
+
for intervention in ("KeywordSwap", "KeywordObf"):
|
| 51 |
+
record = next(
|
| 52 |
+
(
|
| 53 |
+
row
|
| 54 |
+
for row in nonstandard_split
|
| 55 |
+
if row["mutation-pattern"] == intervention
|
| 56 |
+
),
|
| 57 |
+
None,
|
| 58 |
+
)
|
| 59 |
+
if record is None:
|
| 60 |
+
raise RuntimeError(
|
| 61 |
+
f"{intervention} is missing from {nonstandard_split_name}."
|
| 62 |
+
)
|
| 63 |
+
specs[(formalization, intervention)] = SemanticsSpec(
|
| 64 |
+
syntax=record["syntax"],
|
| 65 |
+
semantics=record["semantics"],
|
| 66 |
+
)
|
| 67 |
+
return specs
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
SEMANTICS_SPECS = _load_semantics()
|
| 71 |
+
TOKENIZER = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 72 |
+
MODEL = AutoModelForCausalLM.from_pretrained(
|
| 73 |
+
MODEL_ID,
|
| 74 |
+
torch_dtype=torch.bfloat16,
|
| 75 |
+
).to("cuda")
|
| 76 |
+
MODEL.eval()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _extract_answer(response: str) -> str:
|
| 80 |
+
matches = re.findall(r"<answer>.*?</answer>", response, flags=re.DOTALL)
|
| 81 |
+
return matches[-1].strip() if matches else response.strip()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@spaces.GPU(duration=30)
|
| 85 |
+
def predict(
|
| 86 |
+
program: str,
|
| 87 |
+
intervention: str,
|
| 88 |
+
formalization: str,
|
| 89 |
+
) -> tuple[str, str, str, str]:
|
| 90 |
+
"""Run one benchmark-style PredState request on ZeroGPU."""
|
| 91 |
+
started = time.perf_counter()
|
| 92 |
+
prompt, transformed_program = build_predstate_prompt(
|
| 93 |
+
program=program,
|
| 94 |
+
intervention=intervention,
|
| 95 |
+
formalization=formalization,
|
| 96 |
+
specs=SEMANTICS_SPECS,
|
| 97 |
+
)
|
| 98 |
+
messages = [{"role": "user", "content": prompt}]
|
| 99 |
+
model_inputs = TOKENIZER.apply_chat_template(
|
| 100 |
+
messages,
|
| 101 |
+
add_generation_prompt=True,
|
| 102 |
+
return_tensors="pt",
|
| 103 |
+
).to("cuda")
|
| 104 |
+
|
| 105 |
+
with torch.inference_mode():
|
| 106 |
+
generated = MODEL.generate(
|
| 107 |
+
model_inputs,
|
| 108 |
+
max_new_tokens=512,
|
| 109 |
+
do_sample=False,
|
| 110 |
+
pad_token_id=TOKENIZER.eos_token_id,
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
response = TOKENIZER.decode(
|
| 114 |
+
generated[0, model_inputs.shape[-1] :],
|
| 115 |
+
skip_special_tokens=True,
|
| 116 |
+
).strip()
|
| 117 |
+
answer = _extract_answer(response)
|
| 118 |
+
elapsed = time.perf_counter() - started
|
| 119 |
+
run_details = (
|
| 120 |
+
f"{MODEL_ID} Β· {intervention} Β· {formalization} Β· {elapsed:.1f}s"
|
| 121 |
+
)
|
| 122 |
+
return answer, response, transformed_program, run_details
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
with gr.Blocks(title="PLSemanticsBench Β· Try C*") as demo:
|
| 126 |
+
gr.Markdown(
|
| 127 |
+
"""
|
| 128 |
+
# Try C* under counterfactual semantics
|
| 129 |
+
|
| 130 |
+
Enter a standard C* program. The app applies the selected PLSemanticsBench
|
| 131 |
+
intervention, supplies the corresponding formal semantics to the model, and
|
| 132 |
+
asks it to predict the final state.
|
| 133 |
+
"""
|
| 134 |
+
)
|
| 135 |
+
with gr.Row():
|
| 136 |
+
intervention_input = gr.Radio(
|
| 137 |
+
choices=list(INTERVENTIONS),
|
| 138 |
+
value="Standard",
|
| 139 |
+
label="Semantic intervention",
|
| 140 |
+
)
|
| 141 |
+
formalization_input = gr.Dropdown(
|
| 142 |
+
choices=["Small-step (S)", "K semantics"],
|
| 143 |
+
value="Small-step (S)",
|
| 144 |
+
label="Formalization",
|
| 145 |
+
)
|
| 146 |
+
program_input = gr.Code(
|
| 147 |
+
value=DEFAULT_PROGRAM,
|
| 148 |
+
language="c",
|
| 149 |
+
label="Standard C* program",
|
| 150 |
+
lines=12,
|
| 151 |
+
)
|
| 152 |
+
run_button = gr.Button("Run model", variant="primary")
|
| 153 |
+
answer_output = gr.Code(label="Predicted final state", language="html")
|
| 154 |
+
with gr.Accordion("Program after intervention", open=True):
|
| 155 |
+
transformed_output = gr.Code(language="c")
|
| 156 |
+
with gr.Accordion("Raw model output", open=False):
|
| 157 |
+
raw_output = gr.Textbox(lines=10)
|
| 158 |
+
details_output = gr.Textbox(label="Run details", interactive=False)
|
| 159 |
+
|
| 160 |
+
run_button.click(
|
| 161 |
+
fn=predict,
|
| 162 |
+
inputs=[program_input, intervention_input, formalization_input],
|
| 163 |
+
outputs=[
|
| 164 |
+
answer_output,
|
| 165 |
+
raw_output,
|
| 166 |
+
transformed_output,
|
| 167 |
+
details_output,
|
| 168 |
+
],
|
| 169 |
+
api_name="predict",
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
demo.queue(default_concurrency_limit=1).launch()
|
cstar.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""C* source transformations and prompt construction for the interactive demo."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Mapping
|
| 8 |
+
|
| 9 |
+
DATASET_ID = "EngineeringSoftware/PLSemanticsBench"
|
| 10 |
+
MAX_PROGRAM_CHARS = 6_000
|
| 11 |
+
|
| 12 |
+
INTERVENTIONS = {
|
| 13 |
+
"Standard": {},
|
| 14 |
+
"KeywordSwap": {
|
| 15 |
+
"+": "-",
|
| 16 |
+
"-": "+",
|
| 17 |
+
"*": "/",
|
| 18 |
+
"/": "*",
|
| 19 |
+
"<": ">",
|
| 20 |
+
">": "<",
|
| 21 |
+
"<=": ">=",
|
| 22 |
+
">=": "<=",
|
| 23 |
+
"==": "!=",
|
| 24 |
+
"!=": "==",
|
| 25 |
+
"&&": "||",
|
| 26 |
+
"||": "&&",
|
| 27 |
+
},
|
| 28 |
+
"KeywordObf": {
|
| 29 |
+
"+": "π",
|
| 30 |
+
"-": "π",
|
| 31 |
+
"*": "π",
|
| 32 |
+
"/": "π",
|
| 33 |
+
"%": "π",
|
| 34 |
+
"=": "π",
|
| 35 |
+
"<": "π³",
|
| 36 |
+
">": "π",
|
| 37 |
+
"<=": "π·",
|
| 38 |
+
">=": "π",
|
| 39 |
+
"==": "π",
|
| 40 |
+
"!=": "π",
|
| 41 |
+
"&&": "π",
|
| 42 |
+
"||": "π»",
|
| 43 |
+
"!": "π°",
|
| 44 |
+
"break": "πΎ",
|
| 45 |
+
"if": "πΈ",
|
| 46 |
+
"else": "π",
|
| 47 |
+
"while": "π",
|
| 48 |
+
"halt": "π±",
|
| 49 |
+
"continue": "π²",
|
| 50 |
+
},
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
FORMALIZATIONS = {
|
| 54 |
+
"Small-step (S)": "S",
|
| 55 |
+
"K semantics": "K",
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
_TOKEN_PATTERN = re.compile(
|
| 59 |
+
r"""
|
| 60 |
+
"(?:\\.|[^"\\])*" | # string literal
|
| 61 |
+
'(?:\\.|[^'\\])*' | # character literal
|
| 62 |
+
//[^\n]* | # line comment
|
| 63 |
+
/\*.*?\*/ | # block comment
|
| 64 |
+
<=|>=|==|!=|&&|\|\| | # multi-character operators
|
| 65 |
+
[+\-*/%=<>!] | # single-character operators
|
| 66 |
+
[A-Za-z_][A-Za-z0-9_]* # identifiers and keywords
|
| 67 |
+
""",
|
| 68 |
+
re.DOTALL | re.MULTILINE | re.VERBOSE,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@dataclass(frozen=True)
|
| 73 |
+
class SemanticsSpec:
|
| 74 |
+
syntax: str
|
| 75 |
+
semantics: str
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def validate_program(program: str) -> str:
|
| 79 |
+
program = program.strip()
|
| 80 |
+
if not program:
|
| 81 |
+
raise ValueError("Enter a C* program before running the model.")
|
| 82 |
+
if len(program) > MAX_PROGRAM_CHARS:
|
| 83 |
+
raise ValueError(
|
| 84 |
+
f"Keep the program under {MAX_PROGRAM_CHARS:,} characters for this demo."
|
| 85 |
+
)
|
| 86 |
+
return program
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def transform_program(program: str, intervention: str) -> str:
|
| 90 |
+
"""Apply the benchmark's lexical intervention to standard C* source."""
|
| 91 |
+
try:
|
| 92 |
+
replacements = INTERVENTIONS[intervention]
|
| 93 |
+
except KeyError as exc:
|
| 94 |
+
raise ValueError(f"Unknown semantic intervention: {intervention}") from exc
|
| 95 |
+
|
| 96 |
+
if not replacements:
|
| 97 |
+
return program
|
| 98 |
+
|
| 99 |
+
def replace_token(match: re.Match[str]) -> str:
|
| 100 |
+
token = match.group(0)
|
| 101 |
+
if token.startswith(('"', "'", "//", "/*")):
|
| 102 |
+
return token
|
| 103 |
+
return replacements.get(token, token)
|
| 104 |
+
|
| 105 |
+
return _TOKEN_PATTERN.sub(replace_token, program)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def build_predstate_prompt(
|
| 109 |
+
*,
|
| 110 |
+
program: str,
|
| 111 |
+
intervention: str,
|
| 112 |
+
formalization: str,
|
| 113 |
+
specs: Mapping[tuple[str, str], SemanticsSpec],
|
| 114 |
+
) -> tuple[str, str]:
|
| 115 |
+
"""Build the benchmark-style PredState prompt and transformed source."""
|
| 116 |
+
program = validate_program(program)
|
| 117 |
+
try:
|
| 118 |
+
formalization_key = FORMALIZATIONS[formalization]
|
| 119 |
+
except KeyError as exc:
|
| 120 |
+
raise ValueError(f"Unknown formalization: {formalization}") from exc
|
| 121 |
+
|
| 122 |
+
transformed_program = transform_program(program, intervention)
|
| 123 |
+
try:
|
| 124 |
+
spec = specs[(formalization_key, intervention)]
|
| 125 |
+
except KeyError as exc:
|
| 126 |
+
raise ValueError(
|
| 127 |
+
f"No semantics found for {formalization} / {intervention}."
|
| 128 |
+
) from exc
|
| 129 |
+
|
| 130 |
+
if formalization_key == "S":
|
| 131 |
+
formalization_intro = f"""Here is the C* syntax in EBNF:
|
| 132 |
+
```
|
| 133 |
+
{spec.syntax}
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
Here is the complete small-step operational semantics:
|
| 137 |
+
```
|
| 138 |
+
{spec.semantics}
|
| 139 |
+
```"""
|
| 140 |
+
termination_note = (
|
| 141 |
+
"Execution finishes at one of the terminal configurations "
|
| 142 |
+
"β©Ξ΅, Ο, Οβͺ, β©halt, Ο, Οβͺ, or β©ERROR, Ο, Οβͺ."
|
| 143 |
+
)
|
| 144 |
+
else:
|
| 145 |
+
formalization_intro = f"""Here is the complete K-framework formalization:
|
| 146 |
+
```
|
| 147 |
+
{spec.semantics}
|
| 148 |
+
```"""
|
| 149 |
+
termination_note = ""
|
| 150 |
+
|
| 151 |
+
prompt = f"""You are an interpreter for C*. Use only the supplied formal
|
| 152 |
+
semantics, even when a symbol conflicts with its conventional meaning. Assume
|
| 153 |
+
the supplied rules are correct.
|
| 154 |
+
|
| 155 |
+
{formalization_intro}
|
| 156 |
+
|
| 157 |
+
Here is the C* program:
|
| 158 |
+
```
|
| 159 |
+
{transformed_program}
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
Predict the values of every declared variable after execution.
|
| 163 |
+
{termination_note}
|
| 164 |
+
- If execution does not terminate, return <answer>##timeout##</answer>.
|
| 165 |
+
- If execution has an error or undefined behavior, return <answer>##error##</answer>.
|
| 166 |
+
- Otherwise, put every variable in its own XML tag inside <answer>.
|
| 167 |
+
|
| 168 |
+
Return only the <answer> XML block. Do not include reasoning or commentary."""
|
| 169 |
+
|
| 170 |
+
return prompt, transformed_program
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
datasets>=4.0,<5
|
| 2 |
+
spaces>=0.45
|
| 3 |
+
torch==2.8.0
|
| 4 |
+
transformers>=4.51,<6
|