"""Export the PLC-LLM-Bench dataset package for Hugging Face and Kaggle.""" from __future__ import annotations import argparse import csv import json import pathlib import shutil import sys ROOT = pathlib.Path(__file__).resolve().parents[1] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) from plc_bench.scl_normalizer import scl_to_iec from plc_bench.tasks_scl import SCL_TASKS DATASET_DESCRIPTION = """# PLC-LLM-Bench (v0.2): Siemens TIA Portal SCL & IEC 61131-3 ST Benchmark **PLC-LLM-Bench** is a verified, multi-scan industrial automation benchmark for evaluating open-weight Large Language Models (LLMs) on **Siemens TIA Portal SCL** and **IEC 61131-3 Structured Text (ST)** code generation. ## Context & Motivation Industrial PLC engineering requires deterministic scan-cycle logic (timers, edge triggers, safety interlocks, anti-windup PID control, grid droop curves, and Modbus bit packing) — domains where standard Python/C++ coding benchmarks fail to predict real-world reliability. This dataset provides **30 verified multi-scan SCL tasks** alongside **468 empirical T4 GPU evaluations across 13 open-weight LLMs** (Tier 1 <=12 GB VRAM for mobile/edge GPUs like the RTX 5070 Ti Mobile; Tier 2 12–16 GB / MoE). ## Three-Layer Verification Pipeline 1. **Layer 1 — TIA Portal SCL Dialect Linter (`lint_scl`)**: Scores structural adherence (`FUNCTION_BLOCK`, double-quoted names, `{ S7_Optimized_Access := 'TRUE' }`, `#var` local prefixing, balanced `VAR*`/`END_VAR`). 2. **Layer 2 — SCL-to-IEC Normalizer & Native Compiler (`scl_to_iec` + `MatIEC iec2c` + `gcc`)**: Lowers TIA Portal SCL sugar into strict IEC 61131-3 ST and compiles to C via `MatIEC iec2c` and `gcc`, including 1-turn **Pass@2 compiler self-repair**. 3. **Layer 3 — Deterministic Multi-Scan PLC Simulator (`SCLFunctionBlock`)**: Executes generated function blocks over multi-scan time steps (`TON`/`TOF`/`TP`/`IEC_TIMER`, `R_TRIG`/`F_TRIG`, `CTU`/`CTD`, `SR`/`RS`, `ARRAY[lo..hi]`, `VAR_IN_OUT`, bitwise operations). ## Task Categories (30 Verified Tasks — 6 per Category) - **Timers & State Machines (`SCL-SM-01..06`)**: DOL motor starter, star-delta dead-time, conveyor jam watchdog, lead/lag pumps, batch sequencer, PackML state machine. - **Process & Analog Control (`SCL-PC-01..06`)**: 4–20 mA NAMUR NE43 scaling, EMA filter, anti-windup PID, ramp/slew limiter, split-range heating/cooling, 4-level alarm hysteresis. - **Energy, BESS & Grid (`SCL-EN-01..06`)**: LFSM frequency-watt droop, BESS SoC/thermal safety guard, grid synchrocheck, Modbus register mapping, PV/BESS dispatch allocation, Q(V) volt-var droop. - **Debug & Refactoring (`SCL-BF-01..06`)**: Edge-trigger pulse counter fix, fail-safe reset priority fix, ladder-to-SCL refactor, divide-by-zero flow ratio hardening, PI enable reset fix, contact debounce fix. - **Advanced Arrays, Motion & Voting (`SCL-AD-01..06`)**: 4-sample ring buffer moving average, runtime-balanced 3-pump selector, axis homing sequencer, Modbus CRC-16 (`0xA001`), 2oo3 analog voter, cascade control loop. ## Provenance & Methodology All 30 custom Siemens SCL tasks and reference solutions were authored and verified against native `MatIEC iec2c` + `gcc` and multi-scan unit tests. All 13 models were benchmarked on an NVIDIA Tesla T4 GPU (`llama.cpp` `llama-server`, `q8_0` KV cache) over the 36-task v0.1 evaluation suite (20 custom SCL + 16 academic AutoPLC/Agents4PLC ST tasks = 468 evaluations) and re-scored with the v0.2 transpiler and simulator. ## Licensing & Commercial Use - **Open Research & Community License**: Released under **CC-BY-NC-SA-4.0** (Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International). Academic researchers, students, and non-commercial practitioners may freely use, evaluate, and share derivatives with attribution to **Iulian Amaricai / CTRL ALT DELIGHTED S.R.L.** - **Commercial Licensing & Enterprise Integration**: Commercial use — including training or fine-tuning proprietary commercial LLMs, commercial product evaluation, or integrating private industrial SCL/IEC 61131-3/AAS Digital Twin benchmark suites — requires a separate commercial license from **CTRL ALT DELIGHTED S.R.L.** (Romania; creators of *TwinForge AI* and *NexusControl Studio*). """ TASK_CSV_FIELDS: list[dict[str, str]] = [ {"name": "task_id", "type": "string", "description": "Unique benchmark task identifier (e.g. SCL-SM-01, SCL-AD-06)."}, {"name": "category", "type": "string", "description": "Industrial automation domain category (one of 5 categories, 6 tasks each)."}, {"name": "block_name", "type": "string", "description": "Expected Siemens TIA Portal FUNCTION_BLOCK identifier (e.g. FB_PID_AntiWindup)."}, {"name": "prompt", "type": "string", "description": "Natural-language engineering specification and I/O contract given to the LLM."}, {"name": "reference_scl", "type": "string", "description": "Verified reference implementation in Siemens TIA Portal SCL dialect."}, {"name": "reference_iec_st", "type": "string", "description": "Normalized strict IEC 61131-3 Structured Text compiled by MatIEC iec2c + gcc."}, ] LEADERBOARD_CSV_FIELDS: list[dict[str, str]] = [ {"name": "model_name", "type": "string", "description": "Short benchmark identifier for the evaluated open-weight LLM."}, {"name": "tier", "type": "integer", "description": "Hardware VRAM tier: 1 (<=12 GB full GPU fit) or 2 (12-16 GB / MoE offload)."}, {"name": "params_label", "type": "string", "description": "Model parameter count and architecture label (dense vs. active MoE parameters)."}, {"name": "quant_file", "type": "string", "description": "Exact GGUF quantized checkpoint filename evaluated via llama-server."}, {"name": "offload_mode", "type": "string", "description": "GPU layer offload mode used during Colab T4 inference (e.g. full_gpu)."}, {"name": "tasks_total", "type": "integer", "description": "Total number of benchmark tasks evaluated for this model (36 in v0.1 run)."}, {"name": "custom_tasks", "type": "integer", "description": "Number of custom multi-scan Siemens SCL tasks evaluated (20 in v0.1 run)."}, {"name": "academic_tasks", "type": "integer", "description": "Number of academic AutoPLC/Agents4PLC ST compile tasks evaluated (16)."}, {"name": "scl_lint_pct", "type": "number", "description": "Mean Pass@1 Siemens TIA Portal SCL dialect compliance score (0-100%)."}, {"name": "compile_p1_pct", "type": "number", "description": "Overall MatIEC iec2c + gcc compilation pass rate on Pass@1 across all tasks (%)."}, {"name": "compile_p2_pct", "type": "number", "description": "Overall MatIEC iec2c + gcc compilation pass rate after Pass@2 repair (%)."}, {"name": "custom_compile_p1_pct", "type": "number", "description": "MatIEC iec2c + gcc compilation pass rate on Pass@1 for custom SCL tasks (%)."}, {"name": "custom_compile_p2_pct", "type": "number", "description": "MatIEC iec2c + gcc compilation pass rate after Pass@2 repair for custom SCL tasks (%)."}, {"name": "func_p1_pct", "type": "number", "description": "Zero-shot (Pass@1) multi-scan functional unit test pass rate on custom SCL tasks (%)."}, {"name": "func_p2_pct", "type": "number", "description": "1-turn compiler self-repair (Pass@2) multi-scan functional pass rate (%)."}, {"name": "acad_compile_p1_pct", "type": "number", "description": "Pass@1 MatIEC compilation pass rate on the 16-task academic ST subset (%)."}, {"name": "acad_compile_p2_pct", "type": "number", "description": "Pass@2 MatIEC compilation pass rate on the 16-task academic ST subset (%)."}, {"name": "avg_gen_tps", "type": "number", "description": "Average token generation throughput on NVIDIA Tesla T4 (tokens/second)."}, {"name": "avg_prompt_tps", "type": "number", "description": "Average prompt prefill throughput on NVIDIA Tesla T4 (tokens/second)."}, {"name": "peak_vram_gb", "type": "number", "description": "Peak measured GPU VRAM footprint during inference (GiB)."}, {"name": "rtx5070ti_fit", "type": "string", "description": "Deployment fit classification for an NVIDIA GeForce RTX 5070 Ti Mobile (12 GB VRAM)."}, {"name": "composite_score", "type": "number", "description": "Weighted offline industrial developer score (0-100) combining Pass@1, Pass@2, compile, lint, and speed."}, ] KAGGLE_METADATA: dict[str, object] = { "title": "PLC-LLM-Bench: Siemens SCL & IEC 61131 Benchmark", "subtitle": "30 Multi-Scan Siemens TIA Portal SCL Tasks & 13-Model LLM Leaderboard", "id": "iulianamaricai/siemens-scl-iec61131-benchmark", "isPrivate": False, "licenses": [{"name": "CC-BY-NC-SA-4.0"}], "keywords": [ "programming", "computer science", "energy", "engineering", "nlp", ], "expectedUpdateFrequency": "quarterly", "userSpecifiedSources": ( "Curated and verified by Iulian Amaricai (CTRL ALT DELIGHTED S.R.L.) using " "MatIEC iec2c + gcc and deterministic multi-scan PLC simulation; 468 LLM evaluations " "executed on NVIDIA Tesla T4 with llama.cpp." ), "image": "benchmark_charts.png", "description": DATASET_DESCRIPTION.strip(), "resources": [ { "path": "plc_scl_tasks.csv", "description": "Tabular CSV catalog of all 30 verified Siemens TIA Portal SCL benchmark tasks with prompts, reference SCL, and normalized IEC 61131-3 ST.", "schema": {"fields": TASK_CSV_FIELDS}, }, { "path": "leaderboard_summary.csv", "description": "Tabular CSV leaderboard summarizing v0.2 re-scored accuracy, compilation, lint, speed, and VRAM metrics across 13 open-weight LLMs (468 evaluations).", "schema": {"fields": LEADERBOARD_CSV_FIELDS}, }, { "path": "plc_scl_tasks.jsonl", "description": "JSON Lines (JSONL) version of the 30 verified Siemens SCL tasks for direct ingestion by LLM evaluation harnesses and Hugging Face Datasets.", }, { "path": "leaderboard_summary.json", "description": "Machine-readable JSON summary of the 13-model empirical leaderboard re-scored with the v0.2 MatIEC transpiler and multi-scan PLC simulator.", }, { "path": "leaderboard.md", "description": "Formatted Markdown leaderboard tables covering the main 13-model custom SCL ranking and the 16-task AutoPLC/Agents4PLC academic compile subset.", }, { "path": "benchmark_charts.png", "description": "Side-by-side Pass@1 vs. Pass@2 functional accuracy bar chart and VRAM-vs-Accuracy Pareto frontier plot relative to the 12 GB RTX 5070 Ti Mobile limit.", }, ], } def export_dataset( out_dir: pathlib.Path, results_dir: pathlib.Path, ) -> list[pathlib.Path]: """Export SCL tasks, CSV/JSON/Markdown leaderboards, charts, and Kaggle metadata to ``out_dir``.""" out_dir.mkdir(parents=True, exist_ok=True) written: list[pathlib.Path] = [] task_records: list[dict[str, str]] = [] for task in SCL_TASKS: task_records.append( { "task_id": task.task_id, "category": task.category, "block_name": task.block_name, "prompt": task.prompt, "reference_scl": task.reference_scl, "reference_iec_st": scl_to_iec(task.reference_scl), } ) tasks_jsonl = out_dir / "plc_scl_tasks.jsonl" with tasks_jsonl.open("w", encoding="utf-8", newline="\n") as handle: for record in task_records: handle.write(json.dumps(record, ensure_ascii=False) + "\n") written.append(tasks_jsonl) tasks_csv = out_dir / "plc_scl_tasks.csv" with tasks_csv.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=[f["name"] for f in TASK_CSV_FIELDS]) writer.writeheader() writer.writerows(task_records) written.append(tasks_csv) artifact_map = ( ("summary.json", "leaderboard_summary.json"), ("leaderboard.md", "leaderboard.md"), ("benchmark_charts.png", "benchmark_charts.png"), ) for src_name, dst_name in artifact_map: src = results_dir / src_name if not src.is_file(): raise FileNotFoundError( f"Expected benchmark report file at {src}; run scripts/run_bench.py or scripts/rescore_checkpoint.py first." ) dst = out_dir / dst_name shutil.copy2(src, dst) written.append(dst) summary_rows = json.loads((results_dir / "summary.json").read_text(encoding="utf-8")) leaderboard_csv = out_dir / "leaderboard_summary.csv" lb_fieldnames = [f["name"] for f in LEADERBOARD_CSV_FIELDS] with leaderboard_csv.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=lb_fieldnames, extrasaction="ignore") writer.writeheader() writer.writerows(summary_rows) written.append(leaderboard_csv) metadata_path = out_dir / "dataset-metadata.json" metadata_path.write_text( json.dumps(KAGGLE_METADATA, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", ) written.append(metadata_path) return written def main() -> None: parser = argparse.ArgumentParser( description="Export PLC-LLM-Bench dataset files for Hugging Face and Kaggle." ) parser.add_argument( "--out-dir", type=pathlib.Path, default=ROOT / "dataset", help="Destination directory for exported dataset files.", ) parser.add_argument( "--results-dir", type=pathlib.Path, default=ROOT / "results", help="Directory containing summary.json, leaderboard.md, and benchmark_charts.png.", ) args = parser.parse_args() written = export_dataset(args.out_dir, args.results_dir) print(f"Exported {len(SCL_TASKS)} SCL tasks and {len(written)} dataset files to {args.out_dir}:") for path in written: print(f" - {path.name} ({path.stat().st_size:,} bytes)") if __name__ == "__main__": main()