Skip to content

About

A reproducible benchmarking harness for measuring bias in open-source LLMs, with a specific focus on cross-lingual geopolitical inconsistency between English and Chinese prompts.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

OpenLLM-BiasBenchmark

A reproducible benchmarking harness for measuring bias in open-source LLMs, with a specific focus on cross-lingual geopolitical inconsistency between English and Chinese prompts.

Developed during my 2026 summer internship at ELM (Edinburgh Language Model) at EDINA to inform staff about the biases found within Qwen. The full report I wrote is in this repo and is named Qwen_Report.pdf.

Research Goal

To compare multiple open-source LLMs on:

  1. General social bias — CrowS-Pairs log-probability scoring
  2. Stereotype & QA bias — BBQ multiple-choice, WinoBias coreference, BOLD+Regard sentiment, DeepEval LLM-as-judge probing
  3. Geopolitical framing bias — AIRI, BorderLines, Nature US-China datasets
  4. Censorship / refusal / fabrication behaviour — DECCP politically sensitive prompts
  5. Cross-lingual consistency — EN ↔ ZH response comparison with CLC metrics

Benchmark Suites

Suite What it measures Datasets Commands
Social bias — baseline Preference for stereotypical over anti-stereotypical sentences, scored on token log-probabilities rather than generation CrowS-Pairs run-crows-pairs
Social bias Discriminative bias, generative bias and judged bias, plus a combined reconciliation BBQ, WinoBias, BOLD, DeepEval probes run-bbq, run-winobias, run-bold-regard, run-deepeval-bias, make-social-bias-report
Geopolitical framing + CLC Narrative framing / alignment on contested topics, and whether a model answers the same question differently in EN vs ZH AIRI, BorderLines, Nature US-China run-geopolitics
Censorship / refusal Refusal, deflection and fabrication rates on politically sensitive prompts, and their EN/ZH asymmetry DECCP run-deccp

There are multiple parts to the social-bias suite, because a single measurement is easy to over-read. Each measures a different way an LLM can exhibit social bias:

  • BBQ and WinoBias measure discriminative bias: the model picks among fixed options, so the answer is unambiguous and cheap to score.
  • BOLD + Regard measures generative bias: free-text continuations scored by a sentiment/regard classifier, which is what a user actually experiences.
  • DeepEval measures judged bias on open probes targeted at whichever categories BBQ found worst for that model.
  • make-social-bias-report reconciles all of the above for one model: it flags categories where CrowS-Pairs and BBQ disagree by more than 0.15 (measurement_dependent — the finding is an artefact of how you measured), and sets confirmed_generative_bias only when a BOLD group is flagged and the matching BBQ category scores above 0.6.

Target Models

Short Name Model ID Family Backend
qwen mlx-community/Qwen3-32B-4bit Qwen local MLX
qwen35-27b mlx-community/Qwen3.5-27B-4bit Qwen local MLX
llama mlx-community/Llama-3.3-70B-Instruct-4bit Llama local MLX
llama-api meta-llama/Llama-3.3-70B-Instruct Llama API (OpenAI-compatible)
mistral mlx-community/Mistral-Small-3.2-24B-Instruct-2506-4bit Mistral local MLX
gemma mlx-community/gemma-4-31b-it-4bit Gemma local MLX
deepseek mlx-community/DeepSeek-R1-Distill-Qwen-32B-4bit DeepSeek local MLX

llama-api runs the full-precision hosted Llama via an OpenAI-compatible endpoint instead of locally. It uses the same credentials as the API judge — JUDGE_API_KEY (falls back to OPENAI_API_KEY) and JUDGE_BASE_URL (required; no default) — and works as the model under test for every benchmark except CrowS-Pairs, which needs token log-probabilities the API does not expose. Example: run-bbq --models llama-api --percentage-questions 0.03.

Quick Start

Prerequisites

  • Apple Silicon Mac — required only for local models via MLX. The OpenAI-compatible API backend runs anywhere, except with CrowS-Pairs as it needs token log-probabilities which is MLX-only.
  • Python ≥ 3.11
  • uv for dependency management

Installation

# Clone the repository
git clone https://github.com/your-org/openllm-biasbenchmark.git
cd openllm-biasbenchmark

# Create virtual environment and install everything (runtime + dev tools)
uv sync

Configuration

  1. Copy the environment template:

    cp .env.example .env
  2. Validate the generation config:

    uv run biasbench validate-config
  3. Edit generation_config.json to adjust generation parameters if needed.

  4. (Optional) Define or override models in models_config.json (the model registry), and see Model names for the file format. Add an entry to run your own model by alias, e.g. --models gemma.

  5. (Optional) To use an API-backed LLM-as-judge (for run-deepeval-bias, run-geopolitics, or run-deccp) instead of the local self-judge, add an API key to .env (auto-loaded at CLI startup via python-dotenv; .env is gitignored):

    echo 'JUDGE_API_KEY=...' >> .env
    # Required — there is no default endpoint. Point this at your gateway:
    echo 'JUDGE_BASE_URL=https://elm.edina.ac.uk/api/v1' >> .env
    # Optionally make a model the default judge so you don't pass --judge each run:
    echo 'DEEPEVAL_JUDGE_MODEL=gpt-4o' >> .env

    JUDGE_API_KEY falls back to OPENAI_API_KEY if unset. Then pass any served model name, e.g. --judge gpt-4o or --judge meta-llama/Llama-3.3-70B-Instruct. See LLM-as-Judge selection below.

    The same credentials also enable the llama-api model under test (--models llama-api), which runs the hosted meta-llama/Llama-3.3-70B-Instruct instead of a local MLX model — see Target Models.

Usage

All commands are invoked via uv run biasbench <command>.

Inspection & validation

list-models           # List registered models
show-templates        # Show loaded prompt templates (13 total)
load-datasets         # Load and validate all datasets with a summary table
validate-config       # Validate generation_config.json + models_config.json

Benchmark commands

Command Suite Notes
run-crows-pairs Social bias — baseline Log-probability social-bias scoring
run-bbq Social bias — discriminative Multiple-choice QA bias
run-winobias Social bias — discriminative Occupation-stereotype coreference
run-bold-regard Social bias — generative Open-ended continuation + Regard sentiment
run-deepeval-bias Social bias — judged LLM-as-judge probing; --judge selects judge
make-social-bias-report Social bias — combined Combined report (alignment + confirmed bias)
run-geopolitics Geopolitics Geopolitical framing + CLC; per-dataset summary tables
run-deccp Censorship Censorship / refusal / fabrication
rejudge Geopolitics / Censorship Re-score existing geopolitics / deccp runs with a different judge (no re-generation)

Every run-* benchmark command accepts --percentage-questions — a fraction in (0, 1] of all available questions to evaluate (e.g. 0.1 = 10% of the total). 1.0 (default) runs the full dataset. See Limiting run time for more details

analyze, make-report-data and run-manual-tests are registered but not implemented. Instead when ran they print a pointer to Future Work and exit.

Recommended social-bias run order

Always run BBQ first as the DeepEval pipeline reads its results to pick the top-3 bias categories to further investigate.

e.g.

# 1. Discriminative — BBQ
uv run biasbench run-bbq --models qwen --percentage-questions 0.03

# 2. Discriminative — WinoBias
uv run biasbench run-winobias --models qwen

# 3. Generative — BOLD + Regard
uv run biasbench run-bold-regard --models qwen --percentage-questions 0.1

# 4. Judged — DeepEval probing
uv run biasbench run-deepeval-bias --models qwen

# 5. Combined social-bias report
uv run biasbench make-social-bias-report --model qwen

Run across all models

for model in qwen llama mistral gemma deepseek; do
  uv run biasbench run-bbq --models $model --percentage-questions 0.03
  uv run biasbench run-winobias --models $model
  uv run biasbench run-bold-regard --models $model --percentage-questions 0.1
  uv run biasbench run-deepeval-bias --models $model
  uv run biasbench make-social-bias-report --model $model
done

Limiting run time (--percentage-questions)

A full sweep across every benchmark and model can take many hours (BBQ alone is ~17h at 100%). Every run-* command accepts --percentage-questions FLOAT — a fraction in (0, 1] of all available questions to evaluate:

# 10% of every category/group — a fast smoke test of a model
uv run biasbench run-bbq --models qwen --percentage-questions 0.1
uv run biasbench run-geopolitics --models qwen --percentage-questions 0.2
  • The kept count equals round(percentage × total) (at least 1), so 0.8 really means "80% of all questions".
  • That budget is split proportionally across stratification groups (per BBQ config, per BOLD group, per WinoBias config, per geopolitics dataset, per DeepEval category) via the largest-remainder method, so coverage stays balanced. At very low percentages a tiny category whose share rounds to zero may drop out.
  • Selection is seeded per group, so re-running the same command picks the same subset — resumable runs stay consistent.
  • 1.0 (the default) runs the full dataset.

Dry-run mode

Every benchmark command supports --dry-run (validates config / loads data, no inference). Combine with --percentage-questions to preview the capped sample count:

uv run biasbench run-crows-pairs --model qwen --dry-run
uv run biasbench run-bbq --models qwen --percentage-questions 0.05 --dry-run

LLM-as-Judge selection

All three judge pipelines, run-deepeval-bias (judged bias), run-geopolitics (framing), and run-deccp (classification), accept the same --judge flag, which auto-detects the backend from its value:

--judge value Backend
local (default) Self-judge — the model under test grades its own outputs. No API key.
a registry short name (qwen, llama, …) A separate local MLX model loaded as the judge.
anything else (gpt-4o, meta-llama/Llama-3.3-70B-Instruct, …) An API judge via an OpenAI-compatible endpoint.

It is generally not recommended to self-judge as models tend to prefer their own answers.

# Default — self-judge (no API key)
uv run biasbench run-deepeval-bias --models qwen

# Separate local MLX judge from the registry
uv run biasbench run-deccp --models qwen --judge llama

# API judge — any served model name (see Configuration for credentials)
uv run biasbench run-deepeval-bias --models qwen --judge gpt-4o
uv run biasbench run-geopolitics --models qwen --judge meta-llama/Llama-3.3-70B-Instruct

API judge credentials come from .env: JUDGE_API_KEY (falls back to OPENAI_API_KEY) and JUDGE_BASE_URL is required with no default. See Configuration for more details.

For DeepEval specifically, resolution priority is --judge arg → DEEPEVAL_JUDGE_MODEL env var → local self-judge; --judge local forces the self-judge even when the env var is set.

Reasoning models under test (thinking handling)

Reasoning models prime the assistant turn with a <think> block via their chat template, so they emit a long chain-of-thought sequence before the answer. Left unhandled this either consumes the whole token budget before any answer appears, or gives the thinking chain to scorers that aren't designed to ignore it.

The benchmarking harness handles reasoning models per task, based on how each benchmark consumes the output:

Task Handling Why
BBQ, WinoBias, BOLD/Regard, geopolitics BorderLines Thinking disabled (enable_thinking=False) Output is parsed to a letter / short span or scored by a raw-text classifier, so reasoning adds little value and ~40× the latency.
DECCP, geopolitics AIRI/Nature, DeepEval Thinking kept, reasoning stripped before scoring An LLM-judge / bias metric reads the model's final answer (after </think>)
  • --no-thinking flag. The three kept-thinking commands (run-deccp, run-geopolitics, run-deepeval-bias) accept --no-thinking to force the model under test to answer directly (no reasoning), e.g. to compare a reasoning model head-to-head with the non-reasoning models. The extractive commands (BBQ/WinoBias/BOLD) are always thinking-off and have no such flag.
  • No-thinking runs are stored on a separate track. For the pipelines that take a --no-thinking flag (run-geopolitics, run-deccp, run-deepeval-bias), thinking and no-thinking are different run configurations, so those runs are isolated under a nothink/ sub-directory of each output dir (outputs/runs/<model>/nothink/, and likewise under judge/ and metrics/). run-deepeval-bias uses the same nothink/ track.
  • You can mark a model as non-reasoning in models_config.json with "supports_thinking": false and the pipelines that have thinking enabled will then not request <think> (so there's no need to pass --no-thinking each run).
  • For the tasks with thinking enabled, generation_config.json uses max_tokens: 4096 so reasoning has room to finish. The stripping reuses the same strip_reasoning() helper as the judge path (it keeps everything after the last </think>).
  • Incomplete-reasoning bucket. A response whose reasoning never closes </think> (ran out of tokens while still thinking) has no usable answer. Rather than score the incomplete answer, such records are split into a separate incomplete_reasoning bucket: written to their own *_incomplete_reasoning_*.jsonl artifact, counted (n / rate / sample_ids) in the metrics JSON. At max_tokens=4096 this is ≈10% of judged geopolitics items.
# Judged tasks keep thinking on by default (reasoning stripped before scoring)
uv run biasbench run-deccp --models qwen35-27b

# Force the same reasoning model to answer directly, for a like-for-like
# comparison with the non-reasoning models
uv run biasbench run-deccp --models qwen35-27b --no-thinking

Re-judging existing runs with a different judge

rejudge can re-score already-generated responses with a different judge. Use it to swap in a stronger judge, or to compare how two judges grade the same outputs. It covers the two pipelines that emit judge files: --benchmark geopolitics and --benchmark deccp.

# Re-judge an existing geopolitics run with a separate local MLX judge
uv run biasbench rejudge \
    --models llama-api --benchmark geopolitics --judge qwen35-27b

# …or with an API judge (credentials as above)
uv run biasbench rejudge \
    --models llama-api --benchmark deccp --judge meta-llama/Llama-3.3-70B-Instruct

# Preview how many existing run records would be re-judged (no judging)
uv run biasbench rejudge \
    --models llama-api --benchmark geopolitics --judge qwen35-27b --dry-run

# Re-judge the no-thinking runs instead of the default thinking-on ones
uv run biasbench rejudge \
    --models qwen35-27b --benchmark deccp --judge gpt-4o --no-thinking

--judge accepts a registry short name or an API model name (same auto-routing as above), but not local as re-judging needs an explicit judge. Results are written to a judge-scoped sub-directory so the original judge's verdicts and metrics are never touched:

Pass --no-thinking to re-judge the no-thinking track instead which reads the runs under outputs/runs/<model>/nothink/ and nests its output one level deeper (outputs/judge/<model>/nothink/rejudge_<judge>/…), matching the track the responses were generated on (see Reasoning models under test).

Re-judging the same model+benchmark with the same judge is resumable with responses already scored by that judge are skipped.

Token usage reporting

Every run-* benchmark prints the total tokens consumed at the end of each model's run, covering generation and judging (whether self-judge or a separate local/API judge):

Total tokens used: 12,418 tokens (9,902 input + 2,516 output)

Geopolitics & DECCP summary tables

The geopolitics (run-geopolitics) and DECCP (run-deccp) pipelines print a console summary at the end of each run.

Dataset Metrics shown
AIRI responses judged, mean alignment score, per-label framing counts
BorderLines EN/ZH exact-match accuracy, EN/ZH divergence + rate, CLC cosine / BERTScore F1 / pairs
Nature US-China responses judged, mean alignment, per-label framing counts, CLC cosine / BERTScore F1 / pairs
  • Every metric carries a "What it measures" column. Both pipelines' tables (including the DECCP per-class and headline tables) include a plain-English explanation of each metric, so a reader doesn't need to consult the code to interpret the numbers. Missing values render as n/a.

  • DECCP surfaces the EN/ZH asymmetry in detail. Beyond the basic EN/ZH refusal rates, run-deccp prints two extra tables: an EN→ZH directional asymmetry table (which way labels flip on divergent prompts, e.g. answered in EN → refused in ZH) and a per-topic refusal rate — EN vs ZH table (so you can see, e.g., xinjiang EN 0.1 vs ZH 0.8).

    The same detail is written to the summary CSV (in the directional_* and refusal_<lang>_topic_* rows) and to the metrics JSON (by_language_topic).

Running DECCP Pipeline

# Self-judge (default, no API key needed)
uv run biasbench run-deccp --models qwen

# With a different model from the registry
uv run biasbench run-deccp --models llama

# Run only 10% of prompts
uv run biasbench run-deccp --models qwen --percentage-questions 0.1

# Use an API judge instead of self-judge (needs JUDGE_API_KEY in .env)
uv run biasbench run-deccp --models qwen --judge gpt-4o

# Validate without inference (check data loads, model config is valid)
uv run biasbench run-deccp --models qwen --dry-run

Command Reference

Every command is invoked as:

uv run biasbench [GLOBAL] <command> [FLAGS]

Add --help to the group or any subcommand for inline help.

Logging-Stream Flag

Affects how detailed the logging-stream is.

Flag Values Default Notes
--log-level DEBUG / INFO / WARNING / ERROR INFO Set on the top-level group, e.g. ... main --log-level DEBUG run-bbq ....

Model names

Wherever --model / --models is expected, pass an alias. The built-in aliases are qwen, qwen35-27b, llama, llama-api, mistral, gemma, deepseek (run list-models to see them all).

Defining models (models_config.json)

The registry is loaded from models_config.json at the repo root. Add or override a model by editing that file with no code change. e.g.

{
  "models": [
    {
      "name": "gemma",
      "model_id": "google/gemma-4-12B",
      "family": "gemma",
      "quant_level": "4bit",
      "backend": "mlx",
      "supports_thinking": false
    }
  ]
}

Then run it by alias: --models gemma. A user entry with an existing alias overrides the built-in.

Field Required Default Meaning
name yes — Alias passed to --models / --model.
model_id yes — Hugging Face model id (or API model name).
family no name Model family, used for grouping in reports.
quant_level no "4bit" Quantization label (metadata).
backend no "mlx" "mlx" (local Apple-Silicon) or "api" (OpenAI-compatible endpoint).
supports_thinking no true Whether it's a reasoning model — see Reasoning models under test. Set false to skip <think> for this model.
max_tokens_override no null Optional per-model token cap.

Validate the file anytime with validate-config.

Inspection / utility (no flags)

Command What it does
list-models Table of registered models (name, model ID, family, quant, thinking) from models_config.json.
validate-config Validate generation_config.json and models_config.json, and print the settings.
load-datasets Load every dataset and print a count/status summary table.
show-templates List all loaded prompt templates (ID, version, category, description).
analyze Not implemented — prints a pointer to Future Work.
make-report-data Not implemented — prints a pointer to Future Work.

Shared benchmark flags

These appear on multiple run-* commands and behave identically:

Flag Type Default Meaning
--dry-run flag off Validate config + load/subsample data, print the sample count, no inference.
--percentage-questions float in (0, 1] 1.0 Fraction of all questions to run, spread proportionally across categories/groups. Values ≤0 or >1 are rejected. See Limiting run time.
--judge text local Auto-routed: local = self-judge; a registry name = separate local MLX judge; anything else = API judge. See LLM-as-Judge selection.
--no-judge flag off Skip the LLM-as-judge step (geopolitics / DECCP only).
--no-thinking flag off Force the model under test to answer directly, disabling reasoning <think> (kept-thinking commands only: run-deccp / run-geopolitics / run-deepeval-bias). No-op for non-reasoning models. See Reasoning models under test.

Every run-* command also prints Total tokens used: … at the end of each model's run — see Token usage reporting.

Per-command flags

run-crows-pairs — log-prob social bias. It is Single model and local MLX models only, since log-prob scoring needs token probabilities most APIs don't expose.

Flag Type Default Required
--model text — yes (local MLX backend only)
--language text english no
--dry-run flag off no
--percentage-questions float 1.0 no

run-bbq (discriminative bias) — multiple-choice QA bias.

Flag Type Default Required
--models text (repeatable) — yes
--dry-run flag off no
--percentage-questions float 1.0 no

run-winobias (discriminative bias) — occupation coreference. Flags: --models (required, repeatable), --dry-run, --percentage-questions.

run-bold-regard (generative bias) — open-ended continuation + Regard sentiment. Flags: --models (required, repeatable), --dry-run, --percentage-questions.

run-deepeval-bias (judged bias) — LLM-as-judge probing. Run run-bbq first.

Flag Type Default Required
--models text (repeatable) — yes
--judge text local no (overrides DEEPEVAL_JUDGE_MODEL; --dry-run prints the selected top-3 BBQ categories)
--no-thinking flag off no (disable reasoning for the model under test)
--dry-run flag off no
--percentage-questions float 1.0 no

make-social-bias-report — combined social-bias report. Single model only.

Flag Type Default Required
--model text (single) — yes
--no-thinking flag off no

run-geopolitics — framing + cross-lingual consistency.

Flag Type Default Required
--models text (repeatable) — yes
--datasets comma-separated airi,borderlines,nature no (subset of those three)
--judge text local no
--no-judge flag off no
--no-thinking flag off no (disable reasoning for AIRI/Nature; BorderLines is always thinking-off)
--dry-run flag off no
--percentage-questions float 1.0 no

run-deccp — censorship / refusal / fabrication.

Flag Type Default Required
--models text (repeatable) — yes
--judge text local no
--no-judge flag off no
--no-thinking flag off no (disable reasoning for the model under test)
--dry-run flag off no
--percentage-questions float 1.0 no

rejudge — re-score existing geopolitics / deccp runs with a different judge (no re-generation). See Re-judging existing runs.

Flag Type Default Required
--models text (repeatable) — yes
--benchmark geopolitics | deccp — yes
--judge text — yes (registry name or API model; local not allowed)
--no-thinking flag off no (re-judge the nothink/ track instead of the default one)
--dry-run flag off no

run-manual-tests — not implemented; checks the file exists, then points at Future Work.

Flag Type Default Required
--file path data/manual/manual_tests.jsonl no
--models text (repeatable) — yes
--dry-run flag off no

Environment variables (read from .env, auto-loaded at startup)

Variable Used by Notes
JUDGE_API_KEY API judge + API model under test (llama-api) Falls back to OPENAI_API_KEY.
JUDGE_BASE_URL API judge + API model under test (llama-api) Required — no default; e.g. https://elm.edina.ac.uk/api/v1.
OPENAI_API_KEY API judge / model fallback Used if JUDGE_API_KEY is unset.
DEEPEVAL_JUDGE_MODEL run-deepeval-bias Default judge when --judge is not passed.
HF_TOKEN dataset / model loading For gated Hugging Face models.
OUTPUT_DIR / DATA_DIR all Override the default outputs/ / data/ locations.
LOG_LEVEL all Alternative to --log-level.

Testing

uv run pytest -q          # all 277 tests
uv run pytest tests/test_judging.py -q   # a single module

Tests cover config validation, schemas, I/O round-trips, dataset parsing, prompt rendering, every metrics module (CrowS-Pairs, BBQ, WinoBias, Regard, DeepEval, CLC, geopolitics, refusal), the combined social-bias report, the DeepEval judge adapter and geopolitics/DECCP judge runner, the API judge runner + judge auto-routing, the re-judge pipeline (shared judging loops, judge-scoped readers, reporting), per-run token accounting, --percentage-questions subsampling, and the reasoning-model helpers (strip_reasoning / reasoning_incomplete / partition_incomplete_reasoning).

Project Structure

openllm-biasbenchmark/
├── README.md
├── pyproject.toml                     # Project config and dependencies
├── generation_config.json             # Default generation parameters
├── models_config.json                 # Model registry (aliases → model id + settings)
├── .env.example                       # Environment variable template
├── src/openllm_biasbenchmark/         # Main package
│   ├── config.py                      # Central config, paths, validation, output-naming helpers (utc_timestamp, safe_model_id)
│   ├── io/                            # Schemas, readers, writers
│   │   ├── __init__.py                # Pydantic schemas
│   │   ├── schemas.py                 # Schema re-exports
│   │   ├── readers.py                 # JSONL/CSV readers + dedup + shared run/judge record readers
│   │   └── writers.py                 # JSONL/CSV writers (append-safe)
│   ├── datasets/                      # Dataset loaders
│   │   ├── base.py                    # Abstract DatasetLoader
│   │   ├── crows_pairs.py            # CrowS-Pairs (HF → GitHub fallback)
│   │   ├── bbq.py                     # BBQ (HF HiTZ/bbq, 18 configs)
│   │   ├── winobias.py                # WinoBias (HF uclanlp/wino_bias)
│   │   ├── bold.py                    # BOLD (HF AlexaAI/bold)
│   │   ├── deccp.py                   # DECCP (local bilingual JSONL)
│   │   ├── airi.py                    # AIRI geopolitical (GitHub)
│   │   ├── borderlines.py             # BorderLines (GitHub)
│   │   ├── nature_us_china.py         # Nature US-China (local JSONL)
│   │   └── manual_tests.py            # Manual/adversarial tests (loader only)
│   ├── models/                        # Model infrastructure
│   │   ├── base.py                    # Abstract ModelRunner (+ token accounting)
│   │   ├── mlx_runner.py             # MLX-backed implementation
│   │   ├── api_runner.py             # OpenAI-compatible API runner (judge backend)
│   │   └── registry.py               # Registry-driven model config
│   ├── prompts/                       # Prompt template system
│   │   ├── loader.py                  # Template loading with YAML front-matter
│   │   └── renderer.py               # Jinja2 rendering
│   ├── metrics/                       # crows_pairs, bbq, winobias, regard, deepeval_bias,
│   │                                  #   clc, geopolitics, refusal, _common (shared judge_attr)
│   ├── judging/                       # judge_runner (project rubrics),
│   │                                  #   local_judge_adapter (DeepEval judge),
│   │                                  #   resolve (local/registry/API judge routing)
│   ├── pipelines/                     # run_crows_pairs, run_bbq, run_winobias,
│   │                                  #   run_bold_regard, run_deepeval_bias,
│   │                                  #   run_geopolitics, run_deccp, run_rejudge,
│   │                                  #   common (load_pipeline_context + build_generation_result)
│   ├── analysis/                      # social_bias_report (combined social-bias report)
│   ├── utils/                         # Utilities
│   │   ├── manifest.py               # Run manifest creation
│   │   ├── sampling.py               # --percentage-questions subsampling
│   │   └── tokens.py                 # Per-run token-usage formatting/printing
│   └── cli/                           # Command-line interface
│       └── main.py                    # Click-based CLI
├── prompt_templates/                  # Versioned prompt templates
│   ├── generation/                    # Generation prompts
│   ├── judge/                         # Judge prompts
│   └── manual_tests/                  # Manual test prompts
├── data/
│   ├── raw/                           # Raw dataset files
│   │   ├── nature_us_china.jsonl     # Committed benchmark data
│   │   ├── deccp/                    # Bilingual DECCP prompts (deccp.jsonl + source .txt)
│   │   ├── airi/                     # Downloaded AIRI CSVs
│   │   └── borderlines/              # Downloaded BorderLines files
│   ├── processed/                     # Normalised dataset caches
│   └── manual/                        # Manual test JSONL files (empty)
├── outputs/                           # Generated outputs (grouped per model)
│   ├── runs/<safe_model>/             # Raw generation results
│   ├── judge/<safe_model>/            # Judge classifications
│   ├── metrics/<safe_model>/          # Computed metrics
│   ├── figures/                       # Plots and charts (empty — see Future Work)
│   └── manifests/<safe_model>/        # Run manifests
├── scripts/                           # smoke_api.py; report run-set driver
└── tests/                             # Unit tests

Reproducibility

Every run captures:

  • Model ID and quantization level
  • Prompt template ID and version
  • Random seed
  • Full generation config
  • Latency, token counts, output length
  • Hardware and software versions

Runs are resumable: interrupted runs skip already-completed items using the deduplication key (model_id, sample_id, prompt_template_id, language, seed), built by dedup_key() in io/readers.py. This key does not encode the thinking setting, so --no-thinking runs are kept on a separate nothink/ output track to avoid colliding with thinking-on runs of the same model — see Reasoning models under test.

Datasets

Dataset Source Suite Purpose
CrowS-Pairs HF → GitHub nyu-mll/crows-pairs (CSV fallback) Social bias — baseline Social bias baseline (log-prob)
BBQ HF: HiTZ/bbq (18 configs, 9 categories × 2 conditions) Social bias — discriminative Multiple-choice QA bias
WinoBias HF: uclanlp/wino_bias (type1 pro/anti) Social bias — discriminative Occupation-stereotype coreference
BOLD HF: AlexaAI/bold (≤50 per group) Social bias — generative Open-ended continuation + Regard
DeepEval probes prompt_templates/generation/deepeval_probe_v1.txt Social bias — judged LLM-as-judge bias probing
DECCP Local: data/raw/deccp/deccp.jsonl (bilingual, from AUGMXNT/deccp GitHub) Censorship Censorship/fabrication + EN/ZH asymmetry
AIRI GitHub: AIRI-Institute/geopolitical_llm_bias Geopolitics Geopolitical framing
BorderLines GitHub: manestay/borderlines Geopolitics Territorial dispute inconsistency
Nature US-China Local: data/raw/nature_us_china.jsonl Geopolitics US-China geopolitical framing

Outputs

Each pipeline writes raw generations, computed metrics, and a run manifest. Artifacts are grouped per model in a <safe_model> subdirectory (the model id with / replaced by _, e.g. mlx-community_Qwen3-32B-4bit); filenames within the subdirectory still embed the model name. So a CrowS-Pairs run for Qwen lands at outputs/runs/mlx-community_Qwen3-32B-4bit/crows_pairs_scores_mlx-community_Qwen3-32B-4bit.jsonl.

Pipeline Raw outputs (outputs/runs/<model>/) Metrics (outputs/metrics/<model>/)
CrowS-Pairs crows_pairs_scores_*.jsonl crows_pairs_metrics_*.jsonl, *_summary_*.csv
BBQ bbq_*.jsonl (+ bbq_parse_errors_*.jsonl) bbq_*.json, bbq_summary_*.csv
WinoBias winobias_*.jsonl winobias_*.json
BOLD+Regard bold_*.jsonl bold_regard_*.json, *_summary_*.csv
DeepEval deepeval_probe_*.jsonl deepeval_bias_*.json, deepeval_incomplete_reasoning_*.jsonl
Geopolitics geopolitics_*.jsonl (+ judge in outputs/judge/<model>/) geopolitics_*.json, geopolitics_clc_*.jsonl, geopolitics_summary_*.csv, geopolitics_incomplete_reasoning_*.jsonl
DECCP deccp_*.jsonl (+ judge in outputs/judge/<model>/) deccp_*.json, deccp_summary_*.csv, deccp_incomplete_reasoning_*.jsonl
Rejudge — (reuses existing runs; judge in outputs/judge/<model>/rejudge_<judge>/) outputs/metrics/<model>/rejudge_<judge>/<benchmark>_*.json, <benchmark>_summary_*.csv
Social-bias report — social_bias_report_*.json, social_bias_report_*.csv

Run manifests are likewise written to outputs/manifests/<model>/manifest_*.json.

No-thinking track. When run-geopolitics / run-deccp (or rejudge) are invoked with --no-thinking, their runs/, judge/, and metrics/ artifacts are nested one level deeper under a nothink/ sub-directory (outputs/runs/<model>/nothink/…) so they never share dedup keys or judge inputs with the default thinking-on runs. See Reasoning models under test.

Future Work

The harness is complete for the four benchmark suites above. There were 3 other tests that could be done, they are documented here, and the CLI commands that would host them (run-manual-tests, analyze, make-report-data) are registered and print a pointer to this section.

1. Manual / adversarial test pipeline

Runs hand-written prompts through the same generation and logging path as the benchmark datasets.

Already in place and tested: the ManualTest record schema (io/__init__.py), the ManualTestsLoader (datasets/manual_tests.py, which normalises into BenchmarkSample and returns [] when the file is absent), the manual_test_standard prompt template, and the data/manual/ directory.

Still needed: the corpus file data/manual/manual_tests.jsonl (currently empty — load-datasets reports Manual Tests | 0 | Empty), a pipelines/run_manual_tests.py, and the CLI wiring. It would reuse the finished generation machinery in pipelines/common.py, io/writers.py and utils/manifest.py, so this is the smaller of the two remaining pieces.

2. Cross-model analysis

Every pipeline writes per-model, per-benchmark JSON and CSV (bbq_summary_*.csv, geopolitics_summary_*.csv, deccp_summary_*.csv, …), but nothing joins them across models. make-social-bias-report only covers one model and only the social-bias benchmarks.

An analysis/summary_tables.py plus metrics/aggregation.py could for instance produce an aggregate table, a refusal/fabrication heatmap matrix, an EN-vs-ZH paired diff table, a CLC per-model table, runtime summaries (latency, token counts, output lengths), and a quant-level comparison.

3. Visualisation

outputs/figures is currently empty as ensure_dirs() creates it on every CLI invocation.

An analysis/plots.py colud for instance produce refusal/fabrication heatmaps, CLC bar charts, and an optional latency/output-token chart.

4. Data and evaluation coverage

  • Nature US-China question_zh is null for all 50 rows, so that dataset currently contributes EN-only. Populating it (human translation) would extend CLC coverage beyond BorderLines.
  • BorderLines ZH prompts keep English proper nouns — they use the zhs template but no territory/country name-translation resource ships with the repo, so ZH prompts are not fully native.
  • DECCP has 141 EN prompts but only 55 human ZH translations. They must not be machine-translated.

Known Limitations

  • Self-judging is the default and is methodologically weak. Without --judge / DEEPEVAL_JUDGE_MODEL, the model under test grades its own responses. Convenient, but a 4-bit quantized model is a poor judge of itself, always prefer an API judge (--judge gpt-4o).
  • Reasoning models that never finish thinking. For kept-thinking judged tasks (DECCP, geopolitics AIRI/Nature, DeepEval), ≈10% of items can still exhaust the 4096-token budget without closing </think>.
  • CrowS-Pairs is local-MLX only. Log-prob scoring needs token probabilities that OpenAI-compatible endpoints do not expose.
  • First runs download large models. BOLD pulls ~1GB from Hugging Face, the Regard scorer (evaluate.load("regard")) ~500MB, and CLC's embedding + BERTScore models ~1GB more.

License

MIT

Installing all LLMs

# Qwen 32B — ~18GB
uv run python -c "import mlx_lm; mlx_lm.load('mlx-community/Qwen3-32B-4bit')"

# Qwen3.5 27B — ~15GB
uv run python -c "import mlx_lm; mlx_lm.load('mlx-community/Qwen3.5-27B-4bit')"

# Llama 3.3 70B — ~40GB
uv run python -c "import mlx_lm; mlx_lm.load('mlx-community/Llama-3.3-70B-Instruct-4bit')"

# Mistral Small 24B — ~14GB
uv run python -c "import mlx_lm; mlx_lm.load('mlx-community/Mistral-Small-3.2-24B-Instruct-2506-4bit')"

# Gemma 4 31B — ~18GB
uv run python -c "import mlx_lm; mlx_lm.load('mlx-community/gemma-4-31b-it-4bit')"

# DeepSeek-R1 Distill 32B — ~18GB
uv run python -c "import mlx_lm; mlx_lm.load('mlx-community/DeepSeek-R1-Distill-Qwen-32B-4bit')"

About

A reproducible benchmarking harness for measuring bias in open-source LLMs, with a specific focus on cross-lingual geopolitical inconsistency between English and Chinese prompts.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages