"""Build the self-contained Colab T4 notebook PLC_LLM_Bench_Colab.ipynb. Usage: python scripts/make_notebook.py """ from __future__ import annotations import json import pathlib ROOT = pathlib.Path(__file__).resolve().parents[1] def source_files() -> list[pathlib.Path]: files = [*sorted((ROOT / "plc_bench").glob("*.py")), *sorted((ROOT / "scripts").glob("*.py"))] return [*files, *sorted((ROOT / "tests").glob("*.py")), ROOT / "pyproject.toml"] def _chunk_text(text: str, max_bytes: int = 26_000) -> list[str]: """Split text along line boundaries into UTF-8 chunks under ``max_bytes``.""" chunks: list[str] = [] current: list[str] = [] current_bytes = 0 for line in text.splitlines(keepends=True): line_bytes = len(line.encode("utf-8")) if current and current_bytes + line_bytes > max_bytes: chunks.append("".join(current)) current = [line] current_bytes = line_bytes else: current.append(line) current_bytes += line_bytes if current: chunks.append("".join(current)) return chunks def cells() -> list[tuple[str, str]]: out: list[tuple[str, str]] = [ ( "markdown", "# PLC-LLM-Bench v0.2: Offline Industrial Automation LLM Benchmark (Colab & Kaggle)\n\n" "Evaluates **13 open-weight LLMs** (Tier 1: <=12 GB **RTX 5070 Ti Mobile** fit; Tier 2: 12–16 GB / MoE partial offload) " "on **30 custom Siemens TIA Portal SCL** tasks (5 categories) and **6 academic IEC 61131-3 ST** tasks.\n\n" "Pipeline: `llama.cpp` (`llama-server` CUDA `sm_75`, `q8_0` KV cache) -> SCL Dialect Linter -> " "SCL-to-IEC Normalizer -> `MatIEC iec2c` + `gcc` -> Multi-Scan PLC Simulator (`scl_interp.py`) -> Pass@2 Compiler Self-Repair.\n\n" "Works automatically on **Google Colab** (`/content` + optional Drive) and **Kaggle** (`/kaggle/working`).", ), ("code", "!nvidia-smi --query-gpu=name,memory.total,memory.free --format=csv\n!df -h /content /kaggle/working 2>/dev/null || df -h ."), ( "code", "import os, pathlib\n" "IS_KAGGLE = os.path.isdir('/kaggle/working')\n" "WORK_ROOT = pathlib.Path('/kaggle/working' if IS_KAGGLE else '/content')\n" "PROJECT_DIR = WORK_ROOT / 'plc-llm-bench'\n" "MATIEC_DIR = WORK_ROOT / 'matiec'\n" "LLAMA_DIR = WORK_ROOT / 'llama_bin'\n" "GGUF_CACHE = WORK_ROOT / 'gguf_cache'\n" "AUTOPLC_DIR = WORK_ROOT / 'AutoPLC'\n" "AGENTS4PLC_DIR = WORK_ROOT / 'Agents4PLC_release'\n" "USE_GDRIVE = (not IS_KAGGLE) # Set False on Colab to run solely in /content\n" "RESULTS_DIR = PROJECT_DIR / 'results'\n" "BIN_CACHE = WORK_ROOT / 'bin_cache'\n" "if USE_GDRIVE:\n" " try:\n" " from google.colab import drive\n" " drive.mount('/content/drive')\n" " RESULTS_DIR = pathlib.Path('/content/drive/MyDrive/plc-llm-bench/results')\n" " BIN_CACHE = pathlib.Path('/content/drive/MyDrive/plc-llm-bench/bin_t4')\n" " except Exception as exc:\n" " print('Drive mount skipped:', exc)\n" "RESULTS_DIR.mkdir(parents=True, exist_ok=True)\n" "BIN_CACHE.mkdir(parents=True, exist_ok=True)\n" "for d in ('plc_bench', 'scripts', 'tests'):\n" " (PROJECT_DIR / d).mkdir(parents=True, exist_ok=True)\n" "os.chdir(PROJECT_DIR)\n" "print(f'Workspace: {PROJECT_DIR} (Kaggle={IS_KAGGLE})')\n" "print(f'Results: {RESULTS_DIR}')\n" "!pip -q install -U huggingface_hub requests numpy matplotlib pytest", ), ( "markdown", "## Build / Restore MatIEC (`iec2c`) & `llama.cpp` (`llama-server` for T4 `sm_75`)", ), ( "code", "%%bash\n" "set -e\n" "WORK_ROOT=/content; [ -d /kaggle/working ] && WORK_ROOT=/kaggle/working\n" "apt-get -qq update && apt-get -qq install -y build-essential git autoconf automake libtool bison flex cmake ninja-build >/dev/null\n" "if [ ! -x \"$WORK_ROOT/matiec/iec2c\" ]; then\n" " git clone --depth=1 https://github.com/beremiz/matiec.git \"$WORK_ROOT/matiec\"\n" " cd \"$WORK_ROOT/matiec\" && autoreconf -i >/dev/null && ./configure >/dev/null && make -j$(nproc) >/dev/null\n" "fi\n" "ln -sf \"$WORK_ROOT/matiec/iec2c\" /usr/local/bin/iec2c\n" "echo 'MATIEC:' && /usr/local/bin/iec2c -h | head -n 3\n", ), ( "code", "import json, urllib.request, subprocess, pathlib, os\n" "target_server = pathlib.Path('/usr/local/bin/llama-server')\n" "if not target_server.is_file():\n" " req = urllib.request.Request(\n" " 'https://api.github.com/repos/ggml-org/llama.cpp/releases?per_page=10',\n" " headers={'User-Agent': 'plc-llm-bench'},\n" " )\n" " with urllib.request.urlopen(req, timeout=20) as resp:\n" " rels = json.loads(resp.read().decode())\n" " chosen = next(\n" " r for r in rels\n" " if any(a['name'].startswith('llama-') and 'bin-ubuntu-cuda-12.8-x64' in a['name'] for a in r.get('assets', []))\n" " and any(a['name'].startswith('cudart-') and 'bin-ubuntu-cuda-12.8-x64' in a['name'] for a in r.get('assets', []))\n" " )\n" " llama_url = next(a['browser_download_url'] for a in chosen['assets'] if a['name'].startswith('llama-') and 'bin-ubuntu-cuda-12.8-x64' in a['name'])\n" " cudart_url = next(a['browser_download_url'] for a in chosen['assets'] if a['name'].startswith('cudart-') and 'bin-ubuntu-cuda-12.8-x64' in a['name'])\n" " LLAMA_DIR.mkdir(parents=True, exist_ok=True)\n" " subprocess.run(f\"curl -fsSL -L '{llama_url}' -o /tmp/l.tar.gz && tar -xzf /tmp/l.tar.gz -C '{LLAMA_DIR}' && rm /tmp/l.tar.gz\", shell=True, check=True)\n" " subprocess.run(f\"curl -fsSL -L '{cudart_url}' -o /tmp/c.tar.gz && tar -xzf /tmp/c.tar.gz -C '{LLAMA_DIR}' && rm /tmp/c.tar.gz\", shell=True, check=True)\n" " srv = next(LLAMA_DIR.rglob('llama-server'))\n" " cudart_dir = next(LLAMA_DIR.rglob('libcudart.so.12')).parent\n" " for so in cudart_dir.glob('*.so*'):\n" " dst = srv.parent / so.name\n" " if not dst.exists():\n" " dst.symlink_to(so)\n" " target_server.write_text(f'#!/bin/bash\\nexport LD_LIBRARY_PATH={srv.parent}:${{LD_LIBRARY_PATH}}\\nexec {srv} \"$@\"\\n')\n" " target_server.chmod(0o755)\n" "!/usr/local/bin/llama-server --list-devices", ), ("markdown", "## Project Sources\n\nWrite `plc_bench`, `scripts`, and `tests` files."), ] for f in source_files(): if f.name == "make_notebook.py": continue rel = f.relative_to(ROOT).as_posix() txt = f.read_text(encoding="utf-8") if len(txt.encode("utf-8")) > 26_000: # Split oversized files across multiple cells to stay under Colab/Jupyter payload limits for idx, chunk in enumerate(_chunk_text(txt, max_bytes=26_000)): flag = "" if idx == 0 else "-a " out.append(("code", f"%%writefile {flag}{rel}\n" + chunk)) continue out.append(("code", f"%%writefile {rel}\n" + txt)) out += [ ("markdown", "## Pre-Flight Verification (`pytest`)"), ("code", "!python -m pytest -q"), ("markdown", "## Fetch Academic PLC Benchmarks (`AutoPLC` & `Agents4PLC_release`)"), ( "code", "%%bash\n" "set -e\n" "WORK_ROOT=/content; [ -d /kaggle/working ] && WORK_ROOT=/kaggle/working\n" "[ -d \"$WORK_ROOT/AutoPLC\" ] || git clone --depth=1 https://github.com/cangkui/AutoPLC.git \"$WORK_ROOT/AutoPLC\"\n" "[ -d \"$WORK_ROOT/Agents4PLC_release\" ] || git clone --depth=1 https://github.com/Luoji-zju/Agents4PLC_release.git \"$WORK_ROOT/Agents4PLC_release\"\n", ), ( "markdown", "## Run Benchmark\n\n" "Choose `MODE`: `'smoke'` (1 fast model, 3 tasks), `'tier1'` (8 models <=12 GB), `'tier2'` (5 models 12–16 GB / MoE), or `'all'`.", ), ( "code", "import os, pathlib, subprocess, time\n\n" "MODE = 'smoke' # Change to 'tier1', 'tier2', or 'all'\n" "os.environ['MATIEC_INCLUDE'] = str(MATIEC_DIR / 'lib')\n" "os.environ['PYTHONPATH'] = str(PROJECT_DIR) + ':' + os.environ.get('PYTHONPATH', '')\n" "ckpt = RESULTS_DIR / 'checkpoint.jsonl'\n" "cmd = [\n" " 'python', '-u', 'scripts/run_bench.py',\n" " '--checkpoint', str(ckpt),\n" " '--out-dir', str(RESULTS_DIR),\n" " '--llama-server', '/usr/local/bin/llama-server',\n" " '--cache-dir', str(GGUF_CACHE),\n" " '--autoplc-dir', str(AUTOPLC_DIR),\n" " '--agents4plc-dir', str(AGENTS4PLC_DIR),\n" "]\n" "if MODE == 'smoke':\n" " cmd += ['--smoke', '--models', 'qwen3.5-9b']\n" "elif MODE == 'tier1':\n" " cmd += ['--tier', '1']\n" "elif MODE == 'tier2':\n" " cmd += ['--tier', '2']\n\n" "log_file = PROJECT_DIR / 'bench.log'\n" "with open(log_file, 'w', encoding='utf-8') as lf:\n" " proc = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT, text=True, cwd=str(PROJECT_DIR))\n\n" "print(f\"Launched benchmark (PID {proc.pid}) in background.\")\n" "print(f\"Streaming {log_file} (polling up to 120s)...\\n\")\n" "t0 = time.time()\n" "last_pos = 0\n" "while time.time() - t0 < 120:\n" " if log_file.is_file():\n" " with open(log_file, 'r', encoding='utf-8', errors='ignore') as f:\n" " f.seek(last_pos)\n" " new_chunk = f.read()\n" " if new_chunk:\n" " print(new_chunk, end='', flush=True)\n" " last_pos = f.tell()\n" " if proc.poll() is not None:\n" " print(f\"\\n[DONE] Process finished with return code {proc.returncode}\")\n" " break\n" " time.sleep(3)", ), ("markdown", "## Leaderboard & Pareto Charts"), ( "code", "from IPython.display import Image, Markdown, display\n" "md_file = RESULTS_DIR / 'leaderboard.md'\n" "png_file = RESULTS_DIR / 'benchmark_charts.png'\n" "if md_file.is_file():\n" " display(Markdown(md_file.read_text(encoding='utf-8')))\n" "if png_file.is_file():\n" " display(Image(filename=str(png_file)))", ), ] return out def main() -> None: nb = { "nbformat": 4, "nbformat_minor": 5, "metadata": { "accelerator": "GPU", "colab": {"gpuType": "T4", "provenance": []}, "kernelspec": {"display_name": "Python 3", "name": "python3"}, "language_info": {"name": "python"}, }, "cells": [ { "cell_type": kind, "id": f"cell-{i:02d}", "metadata": {}, "source": src.splitlines(keepends=True), **({"outputs": [], "execution_count": None} if kind == "code" else {}), } for i, (kind, src) in enumerate(cells()) ], } out_nb = ROOT / "PLC_LLM_Bench_Colab.ipynb" out_nb.write_text(json.dumps(nb, indent=1), encoding="utf-8") print(f"Wrote {out_nb} ({len(nb['cells'])} cells)") if __name__ == "__main__": main()