Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
834e32a
fix(release): resync CHANGELOG fragments after v0.8.0 cut
claude Aug 17, 2026
f4adf8a
Merge current main into PR #971 changelog fragment drift fix
claude Aug 17, 2026
40b8aa8
fix(release): re-render CHANGELOG fragments for v0.8.0 aggregate
claude Aug 17, 2026
3beb7c4
fix(dif): harden logistic and purification controls (#959)
seonghobae Aug 20, 2026
a862114
test(dif): preserve native zero-iteration and NumPy bool domains
seonghobae Aug 22, 2026
da8cd3e
fix(dif): preserve native control compatibility
seonghobae Aug 22, 2026
7bc9277
test(dif): align regressions with native control domains
seonghobae Aug 22, 2026
09f6269
test(dif): prove hardened package aliases on landing lane
seonghobae Aug 22, 2026
50d7c9d
Merge remote-tracking branch 'origin/main' into fix/release-resync-cu…
claude Aug 24, 2026
141a048
fix(dif): reject max_iter=0 before native discovery in logistic DIF w…
claude Aug 24, 2026
2d964af
Merge remote-tracking branch 'origin/main' into HEAD
seonghobae Aug 24, 2026
f25c9a7
fix(release): resync changelog after current main
seonghobae Aug 24, 2026
a706bc9
fix(dif): make control installer idempotent
seonghobae Aug 24, 2026
b4cdb87
Merge remote-tracking branch 'origin/main' into fix/release-resync-cu…
claude Aug 24, 2026
666bd4c
merge: sync with main
claude Aug 24, 2026
3177525
merge: sync with main
claude Aug 25, 2026
6cb730c
merge: current main into release-resync and logistic-DIF lane
seonghobae Aug 25, 2026
68d8e54
merge: sync with main
claude Aug 25, 2026
4b8e058
feat(interaction-map): own residual factorization in Rust
seonghobae Aug 25, 2026
4f32560
test(interaction-map): seal evidence and resource admission
seonghobae Aug 25, 2026
0080788
fix(interaction-map): seal evidence before Rust
seonghobae Aug 25, 2026
405203c
test(interaction-map): bound native resource requests
seonghobae Aug 25, 2026
ea33483
fix(interaction-map): bound native workspaces
seonghobae Aug 25, 2026
27dd0ae
fix(interaction-map): reject oversized axis controls before data
seonghobae Aug 25, 2026
1f3e816
test(interaction-map): reject maximal axis request before data
seonghobae Aug 25, 2026
12bd034
docs(interaction-map): record bounded evidence admission
seonghobae Aug 25, 2026
2cf7c3d
test(interaction-map): require shape-consistent empty map
seonghobae Aug 25, 2026
ef09fa7
test(interaction-map): require coherent empty rectangle
seonghobae Aug 25, 2026
ea84f67
fix(interaction-map): normalize empty complete-case rectangle
seonghobae Aug 25, 2026
1d27c71
docs(interaction-map): record empty complete-case contract
seonghobae Aug 25, 2026
8304f3f
feat(interaction-map): expose coverage and cell evidence
seonghobae Aug 25, 2026
ed85629
Merge remote-tracking branch 'origin/feat/residual-interaction-map-co…
seonghobae Aug 25, 2026
df72c9e
test(interaction-map): reject NaN model expectations
seonghobae Aug 25, 2026
070ce17
test(interaction-map): reject nonfinite expected evidence in Rust
seonghobae Aug 25, 2026
94c0243
fix(interaction-map): reject NaN model expectations
seonghobae Aug 25, 2026
897e1c7
Merge pull request #998 from ContextualWisdomLab/fix/release-resync-c…
seonghobae Aug 25, 2026
7805a79
fix(interaction-map): require finite expected evidence
seonghobae Aug 25, 2026
e741168
docs(changelog): record finite interaction-map expectations
seonghobae Aug 25, 2026
4cec5b6
test(interaction-map): preserve observed infinity rejection in Rust
seonghobae Aug 25, 2026
a317ccf
fix(interaction-map): reject infinite observed evidence in Rust
seonghobae Aug 25, 2026
f9e80c1
docs(changelog): align interaction-map missingness parity
seonghobae Aug 25, 2026
08d3991
Merge remote-tracking branch 'origin/feat/public-polytomous-predictio…
seonghobae Aug 25, 2026
51637b8
Merge branch 'main' into feat/residual-interaction-map-contract
opencode-agent[bot] Aug 25, 2026
c2261f0
Merge remote-tracking branch 'origin/feat/residual-interaction-map-co…
seonghobae Aug 25, 2026
842151e
chore: normalize composed public exports
seonghobae Aug 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@
<!-- BEGIN AUTHORITATIVE CHANGELOG FRAGMENTS -->
### Changed

#### Own residual interaction-map computation in the psychometric core

- Add a Rust-backed, complete-case Gabriel residual interaction-map contract
for consumers that already hold observed responses and fitted IRT
expectations. The API returns coordinates, singular values, axis inertia,
reconstruction, unexplained residual, and the exact cross term without
product identifiers, persistence, authorization, or presentation policy.

#### Validate Rasch CML controls before data materialization

- Validate `max_iter` and `tol` before caller-owned response or group arrays are materialized by the public Rasch CML and Andersen LR entry points.
Expand Down
37 changes: 37 additions & 0 deletions crates/fast-mlsirm-py/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ use mlsirm_core::inference::{
standard_errors_from_vcov as core_standard_errors_from_vcov,
vcov_from_hessian as core_vcov_from_hessian,
};
use mlsirm_core::interaction_map::residual_interaction_map as core_residual_interaction_map;
use mlsirm_core::jmle_opt::{adam as core_jmle_adam, lbfgs as core_jmle_lbfgs, run_optimizer as core_jmle_run_optimizer};
use mlsirm_core::marginal::{
fit_marginal_full as core_fit_marginal_full, Anchors, ItemCovariate, MarginalConfig,
Expand Down Expand Up @@ -9368,11 +9369,47 @@ fn standard_errors_from_vcov(vcov: PyReadonlyArray2<'_, f64>) -> PyResult<Vec<f6
/// Version of the Python-to-Rust marginal-MMLE call contract.
const MARGINAL_CAPABILITY_VERSION: u32 = 1;

#[pyfunction]
fn residual_interaction_map(
py: Python<'_>,
observed: PyReadonlyArray2<'_, f64>,
expected: PyReadonlyArray2<'_, f64>,
axis_count: usize,
) -> PyResult<Py<PyAny>> {
if observed.shape() != expected.shape() {
return Err(PyValueError::new_err(
"observed and expected must have the same two-dimensional shape",
));
}
let shape = observed.shape();
let result = core_residual_interaction_map(
observed.as_slice()?,
expected.as_slice()?,
shape[0],
shape[1],
axis_count,
)
.map_err(PyValueError::new_err)?;
let out = pyo3::types::PyDict::new(py);
out.set_item("person_indices", result.person_indices)?;
out.set_item("item_indices", result.item_indices)?;
out.set_item("person_coordinates", result.person_coordinates)?;
out.set_item("item_coordinates", result.item_coordinates)?;
out.set_item("singular_values", result.singular_values)?;
out.set_item("axis_shares", result.axis_shares)?;
out.set_item("reconstruction", result.reconstruction)?;
out.set_item("unexplained", result.unexplained)?;
out.set_item("cross_share", result.cross_share)?;
out.set_item("axis_count", result.axis_count)?;
Ok(out.into_any().unbind())
}

#[pymodule]
#[pyo3(name = "_core")]
fn fast_mlsirm_core(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add("MARGINAL_CAPABILITY_VERSION", MARGINAL_CAPABILITY_VERSION)?;
m.add_function(wrap_pyfunction!(neg_loglik_and_grad, m)?)?;
m.add_function(wrap_pyfunction!(residual_interaction_map, m)?)?;
m.add_function(wrap_pyfunction!(fit_mmle_2pl, m)?)?;
m.add_function(wrap_pyfunction!(fit_cdm, m)?)?;
m.add_function(wrap_pyfunction!(fit_gdina, m)?)?;
Expand Down
1 change: 1 addition & 0 deletions crates/mlsirm-core/src/entrypoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@

include!("lib.rs");

pub mod interaction_map;
pub mod rotation;
5 changes: 4 additions & 1 deletion crates/mlsirm-core/src/factor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,10 @@ pub struct OmegaResult {
/// with matching eigenvectors (columns of `v`, row-major `p x p`). Same
/// sweep scheme as `parallel::symmetric_eigenvalues_desc`, extended with
/// vector accumulation.
fn symmetric_eigen_desc(matrix: &[f64], p: usize) -> Result<(Vec<f64>, Vec<f64>), String> {
pub(crate) fn symmetric_eigen_desc(
matrix: &[f64],
p: usize,
) -> Result<(Vec<f64>, Vec<f64>), String> {
let mut a = matrix.to_vec();
let mut v = vec![0.0; p * p];
for i in 0..p {
Expand Down
276 changes: 276 additions & 0 deletions crates/mlsirm-core/src/interaction_map.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,276 @@
//! Gabriel residual interaction maps after an externally fitted IRT main effect.
//!
//! The caller supplies observed responses and their model expectations. This
//! module owns the numerical residual factorization; product repositories own
//! identifiers, authorization, persistence, and presentation.

use crate::factor::symmetric_eigen_desc;

const SINGULAR_FLOOR: f64 = 1e-12;
const MAX_INTERACTION_MAP_CELLS: usize = 20_000_000;
const MAX_INTERACTION_MAP_COORDINATE_CELLS: usize = 20_000_000;
const MAX_INTERACTION_MAP_EIGEN_WORKSPACE_BYTES: usize = 128 * 1024 * 1024;
const EIGEN_WORKSPACE_MATRIX_COUNT: usize = 3;

fn validate_factorization_workspace(
rows: usize,
columns: usize,
axis_count: usize,
) -> Result<(), String> {
let coordinate_cells = rows
.checked_add(columns)
.and_then(|dimension_sum| dimension_sum.checked_mul(axis_count))
.ok_or_else(|| "residual interaction map coordinate request overflows".to_string())?;
if coordinate_cells > MAX_INTERACTION_MAP_COORDINATE_CELLS {
return Err(format!(
"residual interaction map coordinate request exceeds {MAX_INTERACTION_MAP_COORDINATE_CELLS} cells"
));
}

// `symmetric_eigen_desc` holds the caller's Gram matrix plus an internal
// matrix copy and eigenvector matrix at peak, so budget all three dense
// `columns x columns` f64 matrices before allocating any of them.
let eigen_workspace_bytes = columns
.checked_mul(columns)
.and_then(|cells| cells.checked_mul(std::mem::size_of::<f64>()))
.and_then(|bytes| bytes.checked_mul(EIGEN_WORKSPACE_MATRIX_COUNT))
.ok_or_else(|| "residual interaction map eigen workspace overflows".to_string())?;
if eigen_workspace_bytes > MAX_INTERACTION_MAP_EIGEN_WORKSPACE_BYTES {
return Err(format!(
"residual interaction map eigen workspace exceeds {} MiB",
MAX_INTERACTION_MAP_EIGEN_WORKSPACE_BYTES / (1024 * 1024)
));
}
Ok(())
}

/// A complete-case Gabriel biplot of `observed - expected`.
#[derive(Debug, Clone, PartialEq)]
pub struct ResidualInteractionMap {
pub person_indices: Vec<usize>,
pub item_indices: Vec<usize>,
pub person_coordinates: Vec<f64>,
pub item_coordinates: Vec<f64>,
pub singular_values: Vec<f64>,
pub axis_shares: Vec<f64>,
pub reconstruction: Vec<f64>,
pub unexplained: Vec<f64>,
pub cross_share: Vec<Option<f64>>,
pub axis_count: usize,
}

/// Factor a complete-case residual rectangle using Gabriel's symmetric scaling.
pub fn residual_interaction_map(
observed: &[f64],
expected: &[f64],
n_persons: usize,
n_items: usize,
axis_count: usize,
) -> Result<ResidualInteractionMap, String> {
if axis_count == 0 {
return Err("axis_count must be positive".into());
}
// Even an empty complete-case rectangle returns `axis_shares`, so bound the
// requested axis vector independently of the surviving matrix dimensions.
if axis_count > MAX_INTERACTION_MAP_COORDINATE_CELLS {
return Err(format!(
"residual interaction map coordinate request exceeds {MAX_INTERACTION_MAP_COORDINATE_CELLS} cells"
));
}

let cell_count = n_persons
.checked_mul(n_items)
.ok_or_else(|| "residual interaction map shape overflows".to_string())?;
if cell_count > MAX_INTERACTION_MAP_CELLS {
return Err(format!(
"residual interaction map logical-cell count exceeds {MAX_INTERACTION_MAP_CELLS}"
));
}
if observed.len() != cell_count || expected.len() != cell_count {
return Err("observed and expected lengths must match the declared shape".into());
}

let observed_cell = |index: usize| observed[index].is_finite() && expected[index].is_finite();
let mut person_indices: Vec<usize> = (0..n_persons)
.filter(|&person| (0..n_items).any(|item| observed_cell(person * n_items + item)))
.collect();
let mut item_indices: Vec<usize> = (0..n_items)
.filter(|&item| (0..n_persons).any(|person| observed_cell(person * n_items + item)))
.collect();
person_indices.retain(|&person| {
item_indices
.iter()
.all(|&item| observed_cell(person * n_items + item))
});
item_indices.retain(|&item| {
person_indices
.iter()
.all(|&person| observed_cell(person * n_items + item))
});
if person_indices.is_empty() || item_indices.is_empty() {
return Ok(ResidualInteractionMap {
person_indices,
item_indices,
person_coordinates: Vec::new(),
item_coordinates: Vec::new(),
singular_values: Vec::new(),
axis_shares: vec![0.0; axis_count],
reconstruction: Vec::new(),
unexplained: Vec::new(),
cross_share: Vec::new(),
axis_count,
});
}

let rows = person_indices.len();
let columns = item_indices.len();
validate_factorization_workspace(rows, columns, axis_count)?;

let mut residual = Vec::with_capacity(rows * columns);
for &person in &person_indices {
for &item in &item_indices {
let index = person * n_items + item;
residual.push(observed[index] - expected[index]);
}
}
let center = residual.iter().sum::<f64>() / residual.len() as f64;
let centered: Vec<f64> = residual.iter().map(|value| value - center).collect();
let mut gram = vec![0.0; columns * columns];
for left in 0..columns {
for right in left..columns {
let value = (0..rows)
.map(|row| centered[row * columns + left] * centered[row * columns + right])
.sum();
gram[left * columns + right] = value;
gram[right * columns + left] = value;
}
}
let (eigenvalues, eigenvectors) = symmetric_eigen_desc(&gram, columns)?;
let singular_values: Vec<f64> = eigenvalues
.iter()
.take_while(|value| **value > SINGULAR_FLOOR * SINGULAR_FLOOR)
.map(|value| value.sqrt())
.collect();
let retained = singular_values.len();
let mut person_coordinates = vec![0.0; rows * axis_count];
let mut item_coordinates = vec![0.0; columns * axis_count];
for axis in 0..axis_count.min(retained) {
let root_singular = singular_values[axis].sqrt();
for item in 0..columns {
item_coordinates[item * axis_count + axis] =
eigenvectors[item * columns + axis] * root_singular;
}
for person in 0..rows {
let projection: f64 = (0..columns)
.map(|item| centered[person * columns + item] * eigenvectors[item * columns + axis])
.sum();
person_coordinates[person * axis_count + axis] = projection / root_singular;
}
}
let inertia = singular_values
.iter()
.map(|value| value * value)
.sum::<f64>();
let axis_shares = (0..axis_count)
.map(|axis| {
singular_values
.get(axis)
.map_or(0.0, |value| value * value / inertia)
})
.collect();
let mut reconstruction = Vec::with_capacity(rows * columns);
let mut unexplained = Vec::with_capacity(rows * columns);
let mut cross_share = Vec::with_capacity(rows * columns);
for person in 0..rows {
for item in 0..columns {
let fitted = (0..axis_count)
.map(|axis| {
person_coordinates[person * axis_count + axis]
* item_coordinates[item * axis_count + axis]
})
.sum::<f64>();
let raw = residual[person * columns + item];
let remainder = raw - fitted;
let share = if raw.abs() > SINGULAR_FLOOR {
Some(2.0 * fitted * remainder / (raw * raw))
} else if fitted.abs() <= SINGULAR_FLOOR && remainder.abs() <= SINGULAR_FLOOR {
Some(0.0)
} else {
None
};
reconstruction.push(fitted);
unexplained.push(remainder);
cross_share.push(share.filter(|value| value.is_finite()));
}
}

Ok(ResidualInteractionMap {
person_indices,
item_indices,
person_coordinates,
item_coordinates,
singular_values,
axis_shares,
reconstruction,
unexplained,
cross_share,
axis_count,
})
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn reconstructs_rank_one_residual_without_inventing_a_second_axis() {
let observed = [2.0, 0.0, 0.0, 2.0];
let expected = [1.0, 1.0, 1.0, 1.0];
let map = residual_interaction_map(&observed, &expected, 2, 2, 2).unwrap();
assert_eq!(map.person_indices, vec![0, 1]);
assert_eq!(map.item_indices, vec![0, 1]);
assert_eq!(map.singular_values.len(), 1);
assert!((map.axis_shares[0] - 1.0).abs() < 1e-12);
assert_eq!(map.axis_shares[1], 0.0);
for (raw, fitted) in observed
.iter()
.zip(expected)
.map(|(observed, expected)| observed - expected)
.zip(&map.reconstruction)
{
assert!((raw - fitted).abs() < 1e-12);
}
}

#[test]
fn excludes_incomplete_rows_without_zero_filling() {
let map =
residual_interaction_map(&[2.0, f64::NAN, 1.0, 2.0], &[1.0, 1.0, 1.0, 1.0], 2, 2, 2)
.unwrap();
assert_eq!(map.person_indices, vec![1]);
assert_eq!(map.item_indices, vec![0, 1]);
}

#[test]
fn rejects_declared_grid_above_resource_ceiling_before_length_validation() {
let error = residual_interaction_map(&[], &[], 1, 20_000_001, 1).unwrap_err();
assert!(error.contains("logical-cell"));
}

#[test]
fn rejects_coordinate_overflow_before_allocation() {
let call = std::panic::catch_unwind(|| {
residual_interaction_map(&[1.0, 1.0], &[0.0, 0.0], 2, 1, usize::MAX)
});
assert!(call.is_ok(), "resource admission must return Err instead of panicking");
let error = call.unwrap().unwrap_err();
assert!(error.contains("coordinate"));
}

#[test]
fn rejects_quadratic_eigen_workspace_before_allocation() {
let error = validate_factorization_workspace(1, 3_000, 1).unwrap_err();
assert!(error.contains("eigen workspace"));
validate_factorization_workspace(1, 2_000, 1).unwrap();
}
}
Loading
Loading