llmmetric treats large language models (LLMs) explicitly as fallible psychometric measurement instruments. It integrates four tightly connected layers:
-
Multi-Facet Structured Coding Engine — reproducible
unit x prompt x model x temperature x replicateorchestration with strict JSON schema validation, content-addressed caching, retry handling, and pluggable backends (backend_openai(),backend_ollama(),backend_mock()). -
LLM Psychometrics & Generalizability Suite — Generalizability Theory (
g_study(),d_study()), calibration against human gold standards (calibration_metrics()), and temporal/version drift diagnostics (check_drift()). -
Differential Prompt Functioning (DPF) & Fairness Diagnostics — uniform and non-uniform measurement invariance testing across demographic or experimental subgroups (
dpf_test()), including prompt-level FDR screening and prompt-by-group interaction tests. -
Measurement-Error-Corrected Downstream Inference — Prediction-Powered Inference (
ppi_mean(),ppi_lm(),ppi_glm()), optimal power-tuning (PPI++), and clustered/multilevel extensions (ppi_clustered(),ppi_lmer()) providing asymptotically valid parameter estimates, confidence intervals, and hypothesis tests when combining large LLM-annotated datasets with smaller human-validated subsets.
1. Formal Statistical Formulation
1.1 Generalizability Theory (G-Study and D-Study)
Let denote the numeric score assigned to measurement object (unit/text/person) under crossed measurement facets (, such as prompt , model , temperature ) and replicate .
Under a fully crossed random-effects G-theory model (Brennan, 2001; Shavelson & Webb, 1991), the observed score decomposes into orthogonal random effects indexed by non-empty subsets , where :
For the canonical two-facet crossed design (, without replicates ), the highest-order interaction is confounded with residual error:
Variance Component Estimation
-
REML (primary): Estimated via
lme4::lmer(..., REML = TRUE)with crossed random intercepts foru, each facet , and interaction terms up to the estimable order. REML naturally handles unbalanced designs and guarantees non-negative variance component estimates (). -
Expected Mean Squares / ANOVA (fallback & option): For balanced designs or when REML fails to converge,
g_study()solves the exact linear system of Type-I/balanced ANOVA expected mean squares and truncates negative variance estimates to zero per Brennan (2001).
Error Variances and Reliability Coefficients
For a Decision Study (D-study) aggregating scores over facet sizes and replicates per cell:
- Universe-score variance: .
- Relative error variance (relevant for rank-ordering units): sums all components involving both and at least one facet, plus residual error:
- Absolute error variance (relevant for absolute cutoffs, criterion-referenced scoring, and mean comparisons): adds all facet main effects and pure facet interactions:
- Generalizability coefficient () and Dependability index ():
For the two-facet design (), this simplifies to:
d_study() evaluates over a user-specified grid of facet counts, computes single-facet asymptotes (e.g., ), and identifies minimum-cost designs attaining a target reliability threshold (e.g., ).
1.2 Calibration Metrics and Drift Testing
Calibration vs. Human Gold Standards (calibration_metrics())
For human gold-standard scores and LLM scores ():
- Continuous outcomes: Pearson , Spearman , Lin’s Concordance Correlation Coefficient (CCC), two-way random absolute-agreement and consistency , MAE, RMSE, mean bias (), SD ratio, and calibration regression with joint -test of ideal calibration .
- Categorical/ordinal outcomes: Accuracy, Macro-, unweighted and linearly/quadratically weighted Cohen’s , and exact coincidence-matrix Krippendorff’s (nominal or ordinal metric).
Temporal & Model-Version Drift (check_drift())
Given anchor texts scored across timepoints or model versions with baseline :
- Tests overall mean invariance via within-unit repeated-measures modeling (
score ~ version + (1 | unit_id)/ paired comparisons), reporting paired mean shift, paired Cohen’s , variance ratio, anchor-set Pearson , Spearman , , MAE, and two-sample Kolmogorov-Smirnov statistic against .
1.3 Differential Prompt Functioning (DPF) & Measurement Invariance
Adapting psychometric Differential Item Functioning (Swaminathan & Rogers, 1990; Zumbo, 1999) to LLM scoring, dpf_test() tests whether LLM score exhibits subgroup-dependent bias across observed group conditional on human gold-standard score :
- Model 0 (Invariant): (or polynomial basis )
- Model 1 (Uniform DPF):
- Model 2 (Non-Uniform DPF):
where is the identity link for continuous scores (OLS) or logit link for binary scores (binomial GLM).
-
Hypothesis tests:
- Uniform DPF: (Model 1 vs. Model 0)
- Non-uniform DPF: (Model 2 vs. Model 1)
- Omnibus (Total) DPF: (Model 2 vs. Model 0)
- When repeated rows per unit exist (e.g., multiple prompts per unit),
dpf_test()computes unit-clustered sandwich Wald tests to prevent pseudoreplication Type-I error inflation.
- Effect sizes: (OLS) or Nagelkerke (logistic), Cohen’s , and conditional subgroup bias estimates at with standard errors and 95% confidence intervals.
-
Prompt-level screening: When
prompt_colis supplied,dpf_test()runs per-prompt DPF tests with Benjamini-Hochberg FDR adjustment and tests the global Prompt Group interaction controlling for .
1.4 Prediction-Powered Inference (PPI, PPI++, and Clustered/Multilevel Extensions)
Let the observed data consist of: - Labeled validation sample with human gold standard and LLM score , - Unlabeled sample with covariates and LLM scores only, drawn independently from the same population.
Let denote the target population parameter solving , where .
Power-Tuned M-Estimation (ppi_mean(), ppi_lm(), ppi_glm())
Following Angelopoulos, Bates, Fannjiang, Jordan, & Zrnic (2023) and Angelopoulos, Duchi, & Zrnic (2024), the PPI++ objective with tuning weight is:
- recovers the classical human-only estimator; recovers standard PPI.
- Because for any (possibly biased, noisy, or nonlinearly distorted) LLM predictor , is consistent and asymptotically normal around : with plug-in sandwich covariance: where and sample covariances are explicitly centered to account for non-zero under biased LLMs.
-
Canonical-link GLMs (
gaussian,binomial,poisson): For cumulant with and , the Hessian is strictly positive definite for all , solved via damped Newton-Raphson / IRLS. -
Optimal power tuning (): Minimizing yields: where and . For
ppi_mean(), is unconstrained (exact optimal control variate); forppi_lm()andppi_glm(), is clipped to to preserve finite-sample convexity of . -
Coordinate-wise Control-Variate Calibration (
method = "calibrated"): Fits separate models on (human), (LLM), and (LLM) to compute using coordinate-optimal influence-function weights . This estimator handles severe slope attenuation and LLM-coded predictors seamlessly while preserving valid sandwich inference.
Clustered & Multilevel PPI++ (ppi_clustered(), ppi_lmer())
Suppose observations belong to clusters (e.g., EMA entries within participants, students within schools). Define centered observation scores and .
- Disjoint cluster validation ():
- Overlapping/within-cluster validation (): Define unified cluster score . Since distinct clusters are independent, This automatically captures within-cluster correlation between labeled and unlabeled entries from the same cluster.
-
Random-intercept multilevel extension (
ppi_lmer()): Estimates random-intercept variance components vialme4::lmer(), forms exact Woodbury GLS weights , solves the GLS-weighted PPI++ estimating equations, and computes cluster-robust PPI++ sandwich standard errors alongside human-only and naive-LLM multilevel benchmarks.
2. Modular Package Architecture
llmmetric/
├── DESCRIPTION # Package metadata, lean Imports/Suggests
├── NAMESPACE # Generated via roxygen2
├── ARCHITECTURE.md # Formal math & design blueprint (this file)
├── README.md # Overview, installation, quickstart examples
├── R/
│ ├── llmmetric-package.R # Package-level docs & shared imports
│ ├── utils.R # Validation helpers, tidy formatting, math utilities
│ ├── schema.R # coding_schema(), JSON Schema export, strict validation
│ ├── cache.R # coding_cache() content-addressed memory/disk cache
│ ├── backends.R # backend_mock(), backend_openai(), backend_ollama()
│ ├── coding.R # coding_design(), code_texts(), aggregate_scores()
│ ├── g_study.R # g_study() REML + ANOVA multi-facet variance engine
│ ├── d_study.R # d_study() reliability projections & target solver
│ ├── calibration.R # calibration_metrics() continuous & categorical metrics
│ ├── drift.R # check_drift() temporal/version stability tests
│ ├── dpf.R # dpf_test() uniform/non-uniform & prompt-level DPF
│ ├── ppi_core.R # Shared PPI/PPI++ data splitting, optimal lambda, sandwich core
│ ├── ppi_models.R # ppi_mean(), ppi_lm(), ppi_glm() + S3 methods
│ ├── ppi_clustered.R # ppi_clustered(), ppi_lmer() cluster/multilevel PPI++
│ ├── autoplot.R # ggplot2::autoplot() S3 methods for all diagnostic objects
│ ├── simulate.R # simulate_coding_study() synthetic study generator
│ └── data.R # Documentation for built-in dataset `ema_coded`
├── data/
│ └── ema_coded.rda # Compact multi-facet EMA coding study dataset
├── tests/
│ ├── testthat.R
│ └── testthat/
│ ├── test-schema-cache.R
│ ├── test-backends-coding.R
│ ├── test-g-d-study.R
│ ├── test-calibration-drift.R
│ ├── test-dpf.R
│ ├── test-ppi-models.R
│ ├── test-ppi-clustered.R
│ ├── test-ppi-coverage.R # Monte Carlo 95% CI coverage proofs (biased/noisy LLMs)
│ └── test-autoplot.R
└── vignettes/
├── getting-started.Rmd # End-to-end psychometric workflow
└── ppi-coverage-proof.Rmd # Monte Carlo proof: Naive LLM vs Human-Only vs PPI/PPI++
3. Core Design Invariants
-
Dual-input ergonomics: Psychometric and inference functions accept both
llm_coded_dataobjects produced bycode_texts()and standarddata.frame/tibbleobjects from external coding pipelines. -
Offline reproducibility: Every test, example, and vignette runs deterministically offline using
backend_mock()and mockable HTTP transports forbackend_openai()/backend_ollama(). -
Zero global RNG pollution:
backend_mock()derives deterministic per-cell hashes from(seed, unit_id, prompt_id, model, temperature, replicate)while preserving.Random.seed. -
CRAN hygiene: Zero writes to user home directories (caches default to in-memory or user-supplied paths), zero non-standard evaluation
R CMD checknotes, clean S3print/summary/autoplotcontracts.
