8 Downloads Updated 2 days ago
ollama run jwtiyar/cement-expert:v5
Updated 2 days ago
2 days ago
8345504bfb00 · 4.7GB
Note: This is a personal training and fine-tuning hobby project exploring how far a compact, locally runnable 4B–7B open-weight model can go in cement engineering when paired with deterministic chemistry and retrieval tools.
End-to-end toolkit for building math-verified cement engineering datasets, fine-tuning open-weight 4B–7B LLMs (Qwen3-4B v3, Qwen2.5-7B-Instruct v4/v5 via Unsloth 4-bit QLoRA + TRL/PEFT + GGUF Q4_K_M for Ollama), and routing queries through deterministic physics.py chemistry, verified ASTM/BS EN standard tables, and BM25 textbook RAG.
unsloth/Qwen2.5-7B-Instruct-bnb-4bit fine-tuned with 4-bit QLoRA (LORA_R=32, LORA_ALPHA=32, 3 epochs), exported to GGUF (Q4_K_M) for Ollama (cement-expert:v5), and optionally paired with physics.py and cement_router.py (BM25 RAG + STANDARDS_TABLE)..gguf):
72.0% / 0.811 F1 vs 8.0% on base): Flags strength inversions (2D >= 28D), impossible oxide mass balances, negative Bogue phases, and Blaine vs. %R,80 contradictions.96.1%): Reliably structures physics.py calls for LSF, SM, AM, Bogue phases, liquid phase, and 4×4 raw-mix solving.4/4 on abstention traps and 0 prompt/system leaks (8 leaks on base).physics.py + cement_router.py:
2.12 / 5 standalone vs 4.67 / 5 with cement_router.py) and open-ended process troubleshooting. Users can easily set up both physics.py and cement_router.py locally (see Quick Start below).Historical plant spreadsheets (ALL_CEMENT_DATA.csv and latest_daily_results.txt) contain real-world laboratory measurement drift, flat-banded 28-day entries, and instrument contradictions (such as high Blaine paired with coarse 80 µm sieve residue and low strength). Training an LLM directly on those logs would bake faulty physics into the model weights.
Instead, this repository reads only the textbook/standard/manual files in cement_app/knowledge_base/ (read-only) and combines them with synthetic, mathematically verified chemistry, raw-mix, and lab-QC audit datasets:
ALL_CEMENT_DATA.csv, .xlsx/.xls files, latest_daily_results.txt, and rag_index.pkl are strictly excluded.cement_llm_trainer.physics.%R,80 contradictions.cement-llm-trainer/
├── pyproject.toml
├── requirements-local.txt # Lightweight CPU dependencies (pypdf, scipy, numpy, pytest)
├── requirements-gpu.txt # Cloud GPU training dependencies (unsloth, trl, peft)
├── src/cement_llm_trainer/
│ ├── __init__.py
│ ├── physics.py # FLS chemistry, 4x4 raw-mix solver, lab QC auditor
│ ├── corpus.py # Clean PDF/PPTX/TXT extractor, deduplicator, segmenter
│ └── sft_generator.py # Deterministic ChatML SFT + eval benchmark builder
├── scripts/
│ ├── extract_corpus.py # Builds data/cpt_corpus.jsonl + data/corpus_manifest.json
│ ├── ocr_handbooks.py # Resumable OCR for scanned Duda & Alsop PDFs
│ ├── build_sft_dataset.py # Builds train/val SFT splits & eval_benchmark.jsonl
│ ├── generate_kb_sft.py # Generates grounded textbook Q&A pairs (kb_sft*.jsonl)
│ ├── build_v5_targeted_sft.py # Generates v5 targeted ASTM/BS EN & diagnostic SFT pairs
│ ├── train_qlora.py # Portable Unsloth QLoRA trainer + GGUF/Modelfile export
│ ├── ask_rag.py # BM25 textbook/standards RAG CLI over 45 docs
│ ├── cement_router.py # Unified router: physics.py + STANDARDS_TABLE + BM25 RAG + Ollama
│ ├── eval_model.py # Held-out Ollama benchmark evaluator (supports --router)
│ ├── eval_comprehensive.py # 5-suite benchmark (base, v3, v4, v5, v5_router)
│ ├── eval_code_checks.py # Deterministic binary Pass/Fail checks for known failure modes
│ ├── build_error_discovery_data.py # KMeans + 2D PCA trace clustering & diverse sampling
│ ├── error_discovery_server.py # Zero-dependency HTTP server for Error Discovery UI
│ └── scan_failure_modes.py # Depth scanner across all traces for 6 failure modes
├── notebooks/
│ ├── train_colab.ipynb # v1/v2 Colab/Kaggle QLoRA notebook
│ ├── train_colab_v3_qwen3_4b.ipynb # v3 Qwen3-4B notebook
│ ├── train_colab_v4_qwen25_7b.ipynb # v4 Qwen2.5-7B-Instruct notebook
│ ├── train_colab_v5_qwen25_7b.ipynb # v5 Qwen2.5-7B-Instruct notebook (Kaggle T4 x2 + GGUF)
│ └── export_v4_gguf_from_ckpt.ipynb # Standalone GGUF Q4_K_M export helper
├── review_ui/ # Trace review web UI (`server.py`, `index.html`)
├── error_discovery_data/ # Error Discovery UI (`index.html`), annotations, taxonomy
└── tests/ # 15 pytest tests + UI smoke test (`smoke_review_ui.mjs`)
uv venv .venv
uv pip install --python .venv/bin/python -r requirements-local.txt -e .
.venv/bin/pytest -v
cement_router.py)For production plant queries, scripts/cement_router.py pairs cement-expert:v5 in Ollama with three deterministic grounding layers:
1. physics.py — automatically detects oxide/fineness/strength parameters or raw-mix requests and computes exact LSF, SM, AM, Bogue phases, liquid content, and Lab-QC verdicts (analyze_clinker, audit_lab_sample, solve_rawmix).
2. STANDARDS_TABLE — injects verified specification limits verbatim for ASTM C150, ASTM C595, ASTM C1157, and BS EN 197-1 so multi-column OCR tables are never misread.
3. BM25 RAG (ask_rag.py) — searches the 45-document corpus (cpt_corpus.jsonl + kb_sft_v5.jsonl) while filtering out synthetic tool-extract chunks.
# Single question (human-readable output):
.venv/bin/python scripts/cement_router.py --model cement-expert:v5 \
-q "According to BS EN 197-1, what are the clinker percentage limits for CEM I, CEM II/A, and CEM II/B cements?"
# Structured JSON output:
.venv/bin/python scripts/cement_router.py --model cement-expert:v5 --json \
-q "Audit this OPC lab record: CaO=63.6%, SiO2=20.4%, Al2O3=5.0%, Fe2O3=3.3%, MgO=2.2%, SO3=2.6%, LOI=1.5%, Blaine=3920 cm2/g, %R,80=1.4%, 2D=23.9 MPa, 28D=44.8 MPa."
# Interactive chat:
.venv/bin/python scripts/cement_router.py --model cement-expert:v5
All data/ files are gitignored (not included in the repo). To generate them from your own PDFs/manuals:
- Source PDFs: Place your cement textbooks/standards in cement_app/knowledge_base/ (or data/new_docs/).
- data/cpt_corpus.jsonl ← generated by scripts/extract_corpus.py (optionally after scripts/ocr_handbooks.py for scanned PDFs).
- data/kb_sft_v5.jsonl ← generated from data/cpt_corpus.jsonl by scripts/generate_kb_sft.py.
- data/sft_v5_train.jsonl, data/sft_v5_val.jsonl, data/eval_benchmark.jsonl ← generated by scripts/build_sft_dataset.py and scripts/build_v5_targeted_sft.py.
45 docs, 1,521 chunks)# Optional: resumable OCR for scanned Duda (656 pages) & Alsop PDFs (`pdftoppm` + `tesseract` required)
.venv/bin/python scripts/ocr_handbooks.py --workers 4 --dpi 200
# Extract clean corpus (picks up data/ocr_text/*.txt including ASTM C150/C595/C1157/C1565 & BS EN 197-1)
.venv/bin/python scripts/extract_corpus.py
.venv/bin/python scripts/build_sft_dataset.py
.venv/bin/python scripts/generate_kb_sft.py
.venv/bin/python scripts/build_v5_targeted_sft.py
6,430 training examples (data/sft_v5_train.jsonl) and 715 validation examples (data/sft_v5_val.jsonl) with zero train/val/eval overlap, including 6,155 KB Q&A pairs and 146 targeted ASTM/BS EN standards & diagnostic examples.data/eval_benchmark.jsonl (60 cases across clinker chemistry, raw-mix solving, and Lab-QC audits).GPU T4 x2 / Colab): notebooks/train_colab_v5_qwen25_7b.ipynb trains unsloth/Qwen2.5-7B-Instruct-bnb-4bit (LORA_R = 32, LORA_ALPHA = 32, MAX_SEQ_LENGTH = 1536, SFT_EPOCHS = 3, RUN_CPT = False, use_gradient_checkpointing = True) and exports Qwen2.5-7B-Instruct.Q4_K_M.gguf + Modelfile.pip install -r requirements-gpu.txt
python scripts/train_qlora.py --stage sft --model unsloth/Qwen2.5-7B-Instruct-bnb-4bit --export-gguf q4_k_m
Register the exported GGUF locally in Ollama:
ollama create cement-expert:v5 -f Modelfile
Evaluated via scripts/eval_comprehensive.py across held-out KB Q&A (Suite 1, 24 pairs), RAG faithfulness & abstention (Suite 2, 12 tests), physics.py tool-augmented math (Suite 3, 20 cases), Lab-QC anomaly detection (Suite 4, 25 cases), and format/adversarial/long-context stability (Suite 5, 8 tests):
| Suite / Metric | base_qwen3_4b |
v3_cement_4b |
v4_cement_7b |
v5_cement_7b |
v5_router (cement_router.py) |
|---|---|---|---|---|---|
| Suite 1 — KB Q&A Overall | 1.12 / 5 |
2.00 / 5 |
2.00 / 5 |
2.12 / 5 |
4.67 / 5 |
| Suite 1 — Accuracy / No-Hallucination | 1.50 / 2.25 |
2.17 / 3.08 |
2.29 / 2.79 |
2.33 / 2.79 |
4.92 / 4.83 |
| Suite 2 — RAG Faithfulness / Accuracy | 2.00 / 1.75 |
3.88 / 3.62 |
3.62 / 3.75 |
3.75 / 3.62 |
3.88 / 3.88 |
| Suite 2 — Abstention Traps | 4 / 4 |
4 / 4 |
3 / 4 |
4 / 4 |
4 / 4 |
Suite 3 — Tool-Math (physics.py) |
0.0% (0/20) |
85.0% (10/20) |
93.9% (13/20) |
96.1% (15/20) |
N/A (prose router) |
| Suite 4 — Lab-QC (closed-book) | 8.0% (F1 0.190) |
56.0% (F1 0.690) |
76.0% (F1 0.872) |
72.0% (F1 0.811) |
Deterministic via physics.py |
| Suite 5 — Stability & Adversarial | 3 / 8 (8 leaks) |
8 / 8 |
8 / 8 |
6 / 8 (0 leaks) |
N/A |
Tested on a non-calculation OPC false-set symptom prompt (rapid stiffening in 10 min, no heat, reversible on remixing):
| Model | Diagnosis | Notes |
|---|---|---|
cement-expert:v5 (standalone .gguf) |
❌ Misdiagnosed as flash set | Offline 7B without RAG |
cement_router.py + cement-expert:v5 |
✅ Correct (false set, 105 °C gypsum dehydration) |
Concise, textbook-cited (Duda), 100% local |
deepseek-v4.1-flash-free / mimo-v2.6-flash-free |
✅ Correct (false set, hemihydrate) | Detailed cooler/mill triggers & lab checks (cloud) |
Run benchmarks and deterministic code checks:
# Held-out benchmark (standalone or via cement_router.py):
.venv/bin/python scripts/eval_model.py --model cement-expert:v5 --timeout 300
.venv/bin/python scripts/eval_model.py --model cement-expert:v5 --router --timeout 300
# Comprehensive 5-suite runner:
.venv/bin/python scripts/eval_comprehensive.py --models v5_cement_7b,v5_router --suites 1,2
Deterministic binary checks in scripts/eval_code_checks.py (check_astm_c150_c3a, check_en_197_1_clinker, check_no_negative_bogue_on_valid, check_free_lime_direction) enforce exact standards and physical consistency in CI (tests/test_router.py).
Cluster traces with KMeans + 2D PCA, inspect full multi-step traces in the browser UI, and scan all 125 evaluation traces for recurring failure modes:
.venv/bin/python scripts/build_error_discovery_data.py
.venv/bin/python scripts/error_discovery_server.py --port 8765 # http://127.0.0.1:8765
.venv/bin/python scripts/scan_failure_modes.py
The 125-trace depth scan (outputs/depth_scan_report.json) surfaced 6 confirmed failure modes across closed-book runs (Invented Mechanisms & Missed Core Chemistry, Fabricated Standard / Threshold Numbers, Partial Tool-Extraction Drift, Inverted Physical / Process Direction, Hallucinated Bogue Math & False Lab-QC Flagging, and Multi-Column OCR Table Misread), directly motivating physics.py Lab-QC routing and STANDARDS_TABLE injection inside cement_router.py.
Qwen2.5-7B-Instruct model).