Scientific LLM Evaluation and Pre-Deployment Validation: Benchmarks, Sandboxes, RAG, and Checks
Scientific LLM assistants are moving into drug discovery, materials design, physics simulation, and mathematical derivation, where they can help researchers search literature, write calculation scripts, and organize experiment records. Safe adoption depends on two things: the criteria used to evaluate the model and the engineering controls used to constrain its errors. This article explains how to choose scientific benchmarks such as GPQA, SciBench, SciCode, and ScienceQA; where current models fail, including multi-step derivation, numerical and unit errors, and citation hallucination; how code sandboxing and retrieval-augmented generation (RAG) reduce risk; and how to run a six-step pre-deployment validation workflow with a runnable Python validation script and launch checklist. It avoids specific scores because the same model can vary widely under different settings.
LLMs are moving from general conversation toward professional scientific work. In drug discovery, materials design, physics simulation, and mathematical derivation, models can help researchers search literature, write calculation scripts, and organize experiment records. Whether they can be used with confidence depends on two things: what criteria are used to evaluate the model, and how its errors are constrained in engineering.
The following sections explain how to select evaluation benchmarks, analyze the model’s capability boundaries, introduce code sandboxing and retrieval-augmented generation as two constraint mechanisms, and provide a pre-launch validation workflow with a runnable validation script. The final section adds a pre-launch checklist. The article does not cite specific scores because the same model can produce very different results under different settings.
1. How to Choose Benchmarks for Scientific Scenarios
General QA and basic code benchmarks are usually not enough on their own to reflect scientific capability. Scientific tasks require domain knowledge, multi-step derivation, and numerical computation, so the industry commonly uses several types of benchmarks.
- GPQA: Graduate-level multiple-choice questions written by domain experts, covering biology, physics, chemistry, and related fields. Questions go through multiple rounds of expert review, and non-specialists tend to score poorly even with web search. The primary metric is multiple-choice accuracy. The original paper is “GPQA: A Graduate-Level Google-Proof Q&A Benchmark” by Rein et al., 2023.
- SciBench: College-level mathematics, physics, and chemistry calculation problems, mostly drawn from textbooks and course exams. It tests whether a model can complete multi-step derivations and produce the correct numerical result. The original paper is the SciBench paper by Wang et al., 2023.
- SciCode: A code generation benchmark set in scientific computing contexts. It requires the model to implement functions that pass test cases and tests whether the model can turn scientific formulas into runnable programs.
- ScienceQA: Multimodal QA covering the natural sciences, with questions that include both text and diagrams. The original paper is “Learn to Explain” by Lu et al., published at NeurIPS in 2022. It is suitable for testing a model’s understanding of charts and schematic diagrams.
When citing these benchmarks, use the original papers and official repositories as the source of truth. A benchmark may update its questions or scoring scripts across versions, and a name alone is not enough to define what a score means. Some datasets require access requests or specific licenses, so read their official documentation before use.
| Capability dimension | Common benchmark | Primary metric | Suitable tasks |
|---|---|---|---|
| Domain knowledge and reasoning | GPQA | Multiple-choice accuracy | Literature QA, domain knowledge verification |
| Multi-step numerical derivation | SciBench | Final-answer accuracy | Formula derivation, calculation assistance |
| Scientific computing programming | SciCode | Test-case pass rate | Numerical simulation script generation |
| Multimodal scientific understanding | ScienceQA | QA accuracy | Chart interpretation, experiment diagram understanding |
These benchmarks use different scoring protocols, so their scores cannot be compared directly across benchmarks. Use the following four steps when selecting benchmarks.
- First determine the task type, such as literature QA, formula derivation, script generation, or chart interpretation.
- Select two or three relevant benchmarks from the table instead of relying on a single leaderboard.
- Fix the target model version, prompts, decoding parameters, and answer extraction rules, and reproduce scores under the same conditions.
- Write the complete test conditions and results into the experiment log so new versions can be compared later.
At minimum, record the following during reproduction: model name and version, prompt text, decoding parameters such as temperature and top_p, answer extraction script version, sample size and random seed, test date, and runtime environment. Missing any one of these makes two test runs difficult to compare.
2. Current Model Capability Boundaries
The following three classes of problems often appear in real projects. Frequency depends on model version and task type; this article does not give specific proportions.
The first is broken multi-step derivation. Models usually perform well on language understanding and common coding tasks, but they are more likely to make mistakes on long derivations. Errors rarely appear at the beginning; they are more common in a middle step: a symbol is replaced, a boundary condition is ignored, and the later derivation still reads fluently. A long answer that looks complete does not mean every step is correct.
The second is numerical and unit errors. A model may give a result with the correct order of magnitude but the wrong significant figures, treat electron volts as joules, or omit a unit conversion. These errors are hard to spot in text and need numeric tolerances and unit checks to catch.
The third is citation hallucination. A model may fabricate paper titles, authors, or DOIs, or attach a real paper to an unrelated conclusion. The more polished the citation format, the easier it is for readers to lower their guard.
Detection can combine three main methods. Human spot checks have domain experts randomly inspect a subset of outputs and are good for finding errors in physical meaning and logic. Unit tests use examples with known answers to verify scripts and formulas and are good for finding calculation errors. Citation verification checks whether each citation can be found in a trusted literature library and tracks the citation hit rate. Numerical checks use a relative tolerance, for example requiring relative error no greater than 0.1%. Unit checks confirm that a number is followed by the expected unit.
3. Code Sandboxing and Retrieval-Augmented Generation
Scientific assistants often need to generate and run scripts. The code written by a model may contain errors or dangerous operations, so it must run in an isolated environment. A sandbox should at least restrict the following.
- Runtime: terminate the process on timeout.
- Memory and CPU limits.
- File write size, with writes allowed only to a temporary directory.
- Network access: blocked by default.
- Run user: use a non-root account.
- Environment variables: do not pass any secrets or tokens to the process.
Resource limits from the standard library are only one layer of protection. On Linux, the resource module can set CPU and memory limits, but it cannot isolate the filesystem and network. For untrusted code, use a container or virtual machine, for example docker run --network none --read-only with a non-root user. On macOS, memory limits are also unreliable.
Retrieval-augmented generation (RAG) lets a model first retrieve snippets from a trusted corpus and then answer based on those snippets. It reduces the chance of the model fabricating content from memory, but it does not eliminate hallucination. Retrieved results may be irrelevant or outdated, and the model may ignore the snippets and continue using old knowledge from training. Therefore, every claim in the answer should cite a snippet ID, and the system should then verify that the ID exists and that the snippet actually supports the conclusion. The corpus should record document version numbers and ingestion dates so that results can be traced later.
4. Pre-Launch Validation Workflow and Validation Code
Validate with the following six steps.
- Prepare a test set. Each case should include the question, reference answer, reference numeric value, expected unit, and retrievable document IDs. Test cases should come from real tasks and be updated regularly.
- Fix the configuration. Record the model version, prompts, decoding parameters, and retrieval library version.
- Run in batches. Execute model-generated code in the sandbox and save the full output.
- Run automated checks. Use the script below to check sandbox execution, numeric values, units, and citations.
- Perform human spot checks. Randomly sample a portion of each batch and have domain experts review it. High-risk tasks should use a higher sampling ratio.
- Use a canary rollout. Start with a small group of users, monitor failure rates and human feedback, and expand after stability is confirmed.
The script runs on Python 3.10 or later, uses only the standard library, and supports Linux and macOS. Generated code must print its result on the last line; the script reads that line and compares it with the reference value.
"""Scientific output validation script: run model-generated code in an isolated subprocess and check numbers, units, and citations.Environment: Python 3.10+, standard library only, running on Linux or macOS."""import jsonimport mathimport osimport reimport subprocessimport sysimport tempfilefrom dataclasses import asdict, dataclasstry:import resourceexcept ImportError:resource = NoneSANDBOX_TIMEOUT_S = 10SANDBOX_MEM_MB = 512ALLOWED_UNITS = {"m", "s", "kg", "mol", "K", "J", "W", "Pa", "N", "eV", "nm", "cm"}@dataclassclass CheckResult:name: strpassed: booldetail: strdef _set_limits():cpu = SANDBOX_TIMEOUT_Smem = SANDBOX_MEM_MB * 1024 * 1024resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu))resource.setrlimit(resource.RLIMIT_AS, (mem, mem))resource.setrlimit(resource.RLIMIT_FSIZE, (1024 * 1024, 1024 * 1024))def run_generated_code(code: str) -> tuple[bool, str]:"""Run code in a temporary directory in isolated mode. Note: this is not full isolation; use a container in production."""with tempfile.TemporaryDirectory() as workdir:script = os.path.join(workdir, "task.py")with open(script, "w", encoding="utf-8") as f:f.write(code)try:proc = subprocess.run([sys.executable, "-I", script],cwd=workdir,capture_output=True,text=True,timeout=SANDBOX_TIMEOUT_S,env={"PATH": "/usr/bin:/bin"},preexec_fn=_set_limits if resource else None,)except subprocess.TimeoutExpired:return False, "timeout"if proc.returncode != 0:return False, proc.stderr[-500:]return True, proc.stdout.strip()def check_number(output: str, reference: float, rel_tol: float = 1e-3) -> CheckResult:try:value = float(output.splitlines()[-1])except (IndexError, ValueError):return CheckResult("number", False, f"Could not parse last output line: {output[-80:]}")ok = math.isclose(value, reference, rel_tol=rel_tol, abs_tol=1e-12)return CheckResult("number", ok, f"Output {value}, reference {reference}, relative tolerance {rel_tol}")def check_unit(answer: str, unit: str) -> CheckResult:if unit not in ALLOWED_UNITS:return CheckResult("unit", False, f"Unit {unit} is not in the allowlist")pattern = rf"\d\s*{re.escape(unit)}(?![A-Za-z])"ok = re.search(pattern, answer) is not Nonereturn CheckResult("unit", ok, "Number is followed by the expected unit" if ok else f"Unit {unit} not found after a number")def check_citations(answer: str, retrieved_ids: set[str]) -> CheckResult:cited = set(re.findall(r"\[(doc-\d+)\]", answer))if not cited:return CheckResult("citation", False, "Answer does not cite any retrieved snippet IDs")missing = cited - retrieved_idshit_rate = (len(cited) - len(missing)) / len(cited)return CheckResult("citation", not missing, f"Citation hit rate {hit_rate:.0%}; missing: {sorted(missing)}")def validate(case: dict) -> dict:results = []ok, output = run_generated_code(case["code"])results.append(CheckResult("sandbox execution", ok, "success" if ok else output))if ok:results.append(check_number(output, case["reference"], case.get("rel_tol", 1e-3)))results.append(check_unit(case["answer"], case["unit"]))results.append(check_citations(case["answer"], set(case["retrieved_ids"])))return {"case_id": case["id"],"passed": all(r.passed for r in results),"checks": [asdict(r) for r in results],}if __name__ == "__main__":demo = {"id": "demo-001","code": "import math\nprint(math.sqrt(2) * 3)","reference": 4.242640687,"rel_tol": 1e-6,"unit": "m","answer": "Result is 4.2426 m [doc-1]","retrieved_ids": ["doc-1", "doc-2"],}print(json.dumps(validate(demo), ensure_ascii=False, indent=2))
When you run the example, the script outputs JSON. If all four checks pass, passed is true, and details for each check are listed in checks, ready to be written into the experiment log. If any check fails, the case is marked as failed and the reason is given in the detail field.
5. Pre-Launch Checklist
Before launch, confirm each item below.
- The test set covers actual task types and includes reference answers and reference numeric values.
- Model version, prompts, decoding parameters, answer extraction rules, and retrieval library version have been recorded.
- Generated code runs in a container or virtual machine, with limits on time, memory, file writes, and network access.
- The relative tolerance used for numerical checks is set according to task requirements and documented.
- The unit allowlist matches the task, and numeric values in answers carry units.
- The citation hit rate meets the threshold set by the team, and missed citations are blocked.
- The human spot-check ratio and owners have been defined.
- Failure-rate monitoring and feedback channels for the canary stage are ready, and rollback is possible if anomalies appear.
After these checks are complete, expand usage gradually. The validation script can catch some errors, but it cannot replace the judgment of domain experts.
