jirt 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jirt/__init__.py +94 -0
- jirt/_iteration.py +119 -0
- jirt/_optimize.py +215 -0
- jirt/amortized.py +272 -0
- jirt/binary.py +236 -0
- jirt/bootstrap.py +106 -0
- jirt/diagnostic.py +298 -0
- jirt/dynamic.py +251 -0
- jirt/groups.py +598 -0
- jirt/hierarchical.py +222 -0
- jirt/logistic.py +273 -0
- jirt/multidimensional.py +308 -0
- jirt/network.py +162 -0
- jirt/nominal.py +367 -0
- jirt/noncompensatory.py +278 -0
- jirt/ordinal.py +189 -0
- jirt/poisson.py +156 -0
- jirt/polytomous.py +305 -0
- jirt/py.typed +0 -0
- jirt/sequential.py +50 -0
- jirt/types.py +115 -0
- jirt/unfolding.py +251 -0
- jirt/utilities.py +98 -0
- jirt-0.1.0.dist-info/METADATA +164 -0
- jirt-0.1.0.dist-info/RECORD +27 -0
- jirt-0.1.0.dist-info/WHEEL +4 -0
- jirt-0.1.0.dist-info/licenses/LICENSE +674 -0
jirt/__init__.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Item response theory in Python and JAX."""
|
|
2
|
+
|
|
3
|
+
from .amortized import AmortizedResult, amortized_irt
|
|
4
|
+
from .binary import Control, FitResult, bin_irt
|
|
5
|
+
from .bootstrap import BootstrapResult, bootstrap
|
|
6
|
+
from .diagnostic import (
|
|
7
|
+
DiagnosticResult,
|
|
8
|
+
diagnostic_irt,
|
|
9
|
+
diagnostic_probabilities,
|
|
10
|
+
mastery_profiles,
|
|
11
|
+
)
|
|
12
|
+
from .dynamic import dyn_irt
|
|
13
|
+
from .hierarchical import hier_irt
|
|
14
|
+
from .groups import (
|
|
15
|
+
GroupIRTResult,
|
|
16
|
+
group_irt,
|
|
17
|
+
group_probabilities,
|
|
18
|
+
mixture_irt,
|
|
19
|
+
mixture_probabilities,
|
|
20
|
+
)
|
|
21
|
+
from .logistic import LogisticResult, logistic_irt, logistic_probabilities
|
|
22
|
+
from .multidimensional import (
|
|
23
|
+
MultidimensionalResult,
|
|
24
|
+
multidimensional_irt,
|
|
25
|
+
multidimensional_probabilities,
|
|
26
|
+
)
|
|
27
|
+
from .network import network_irt
|
|
28
|
+
from .noncompensatory import (
|
|
29
|
+
NoncompensatoryResult,
|
|
30
|
+
noncompensatory_irt,
|
|
31
|
+
noncompensatory_probabilities,
|
|
32
|
+
)
|
|
33
|
+
from .nominal import (
|
|
34
|
+
NominalResult,
|
|
35
|
+
nominal_irt,
|
|
36
|
+
nominal_probabilities,
|
|
37
|
+
nested_probabilities,
|
|
38
|
+
)
|
|
39
|
+
from .ordinal import ord_irt
|
|
40
|
+
from .poisson import pois_irt
|
|
41
|
+
from .polytomous import PolytomousResult, polytomous_irt, polytomous_probabilities
|
|
42
|
+
from .sequential import sequential_irt, sequential_probabilities
|
|
43
|
+
from .unfolding import GGUMResult, ggum_irt, ggum_probabilities
|
|
44
|
+
from .utilities import convert_votes, get_starts, make_priors, network_starts
|
|
45
|
+
|
|
46
|
+
__version__ = "0.1.0"
|
|
47
|
+
__all__ = [
|
|
48
|
+
"AmortizedResult",
|
|
49
|
+
"amortized_irt",
|
|
50
|
+
"Control",
|
|
51
|
+
"FitResult",
|
|
52
|
+
"BootstrapResult",
|
|
53
|
+
"bin_irt",
|
|
54
|
+
"bootstrap",
|
|
55
|
+
"dyn_irt",
|
|
56
|
+
"DiagnosticResult",
|
|
57
|
+
"diagnostic_irt",
|
|
58
|
+
"diagnostic_probabilities",
|
|
59
|
+
"mastery_profiles",
|
|
60
|
+
"hier_irt",
|
|
61
|
+
"GroupIRTResult",
|
|
62
|
+
"group_irt",
|
|
63
|
+
"group_probabilities",
|
|
64
|
+
"mixture_irt",
|
|
65
|
+
"mixture_probabilities",
|
|
66
|
+
"LogisticResult",
|
|
67
|
+
"logistic_irt",
|
|
68
|
+
"logistic_probabilities",
|
|
69
|
+
"MultidimensionalResult",
|
|
70
|
+
"multidimensional_irt",
|
|
71
|
+
"multidimensional_probabilities",
|
|
72
|
+
"network_irt",
|
|
73
|
+
"NoncompensatoryResult",
|
|
74
|
+
"noncompensatory_irt",
|
|
75
|
+
"noncompensatory_probabilities",
|
|
76
|
+
"NominalResult",
|
|
77
|
+
"nominal_irt",
|
|
78
|
+
"nominal_probabilities",
|
|
79
|
+
"nested_probabilities",
|
|
80
|
+
"ord_irt",
|
|
81
|
+
"pois_irt",
|
|
82
|
+
"PolytomousResult",
|
|
83
|
+
"polytomous_irt",
|
|
84
|
+
"polytomous_probabilities",
|
|
85
|
+
"sequential_irt",
|
|
86
|
+
"sequential_probabilities",
|
|
87
|
+
"GGUMResult",
|
|
88
|
+
"ggum_irt",
|
|
89
|
+
"ggum_probabilities",
|
|
90
|
+
"convert_votes",
|
|
91
|
+
"get_starts",
|
|
92
|
+
"make_priors",
|
|
93
|
+
"network_starts",
|
|
94
|
+
]
|
jirt/_iteration.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Device-side convergence and control flow shared by iterative estimators."""
|
|
2
|
+
|
|
3
|
+
import jax
|
|
4
|
+
import jax.numpy as jnp
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def change(before, after, correlation):
|
|
9
|
+
u, v = jnp.ravel(before), jnp.ravel(after)
|
|
10
|
+
absolute = jnp.max(jnp.abs(v - u))
|
|
11
|
+
if not correlation:
|
|
12
|
+
return absolute
|
|
13
|
+
uc, vc = u - jnp.mean(u), v - jnp.mean(v)
|
|
14
|
+
uu, vv = jnp.sum(uc * uc), jnp.sum(vc * vc)
|
|
15
|
+
denominator = jnp.sqrt(uu * vv)
|
|
16
|
+
corr = jnp.clip(
|
|
17
|
+
jnp.sum(uc * vc) / jnp.where(denominator > 0, denominator, 1.0), -1.0, 1.0
|
|
18
|
+
)
|
|
19
|
+
return jnp.where((uu > 0) & (vv > 0), jnp.maximum(0.0, 1 - corr), absolute)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def finite_state(state):
|
|
23
|
+
return jnp.all(
|
|
24
|
+
jnp.stack([jnp.all(jnp.isfinite(x)) for x in jax.tree.leaves(state)])
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def compiled_iterations(
|
|
29
|
+
step,
|
|
30
|
+
state,
|
|
31
|
+
data,
|
|
32
|
+
tolerance,
|
|
33
|
+
*,
|
|
34
|
+
max_iter,
|
|
35
|
+
correlation,
|
|
36
|
+
count,
|
|
37
|
+
min_iter=3,
|
|
38
|
+
select=None,
|
|
39
|
+
valid=None,
|
|
40
|
+
finalize=None,
|
|
41
|
+
):
|
|
42
|
+
"""Reusable module-level executor for explicit-data update functions."""
|
|
43
|
+
history = jnp.full((max_iter, count), jnp.nan)
|
|
44
|
+
initial = (jnp.array(0), state, jnp.array(False), jnp.array(True), history)
|
|
45
|
+
|
|
46
|
+
def condition(carry):
|
|
47
|
+
i, _, converged, ok, _ = carry
|
|
48
|
+
return (i < max_iter) & ~converged & ok
|
|
49
|
+
|
|
50
|
+
def body(carry):
|
|
51
|
+
i, old, _, _, history = carry
|
|
52
|
+
new = step(old, data)
|
|
53
|
+
errors = jnp.stack(
|
|
54
|
+
[
|
|
55
|
+
change(u, v, correlation)
|
|
56
|
+
for u, v in zip(
|
|
57
|
+
old[:count] if select is None else select(old, data),
|
|
58
|
+
new[:count] if select is None else select(new, data),
|
|
59
|
+
)
|
|
60
|
+
]
|
|
61
|
+
)
|
|
62
|
+
ok = finite_state(new) if valid is None else valid(new, data)
|
|
63
|
+
converged = ok & (i + 1 >= min_iter) & (jnp.max(errors) < tolerance)
|
|
64
|
+
if finalize is not None:
|
|
65
|
+
new = jax.lax.cond(
|
|
66
|
+
converged, lambda _: finalize(new, old, data), lambda _: new, None
|
|
67
|
+
)
|
|
68
|
+
ok = ok & (finite_state(new) if valid is None else valid(new, data))
|
|
69
|
+
return i + 1, new, converged, ok, history.at[i].set(errors)
|
|
70
|
+
|
|
71
|
+
return jax.lax.while_loop(condition, body, initial)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
_cached_iterations = jax.jit(
|
|
75
|
+
compiled_iterations,
|
|
76
|
+
static_argnames=(
|
|
77
|
+
"step",
|
|
78
|
+
"max_iter",
|
|
79
|
+
"correlation",
|
|
80
|
+
"count",
|
|
81
|
+
"min_iter",
|
|
82
|
+
"select",
|
|
83
|
+
"valid",
|
|
84
|
+
"finalize",
|
|
85
|
+
),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def run_explicit(
|
|
90
|
+
step,
|
|
91
|
+
state,
|
|
92
|
+
data,
|
|
93
|
+
*,
|
|
94
|
+
max_iter,
|
|
95
|
+
tolerance,
|
|
96
|
+
correlation,
|
|
97
|
+
count,
|
|
98
|
+
min_iter=3,
|
|
99
|
+
select=None,
|
|
100
|
+
valid=None,
|
|
101
|
+
finalize=None,
|
|
102
|
+
):
|
|
103
|
+
i, state, converged, ok, history = _cached_iterations(
|
|
104
|
+
step,
|
|
105
|
+
state,
|
|
106
|
+
data,
|
|
107
|
+
jnp.asarray(tolerance),
|
|
108
|
+
max_iter=max_iter,
|
|
109
|
+
correlation=correlation,
|
|
110
|
+
count=count,
|
|
111
|
+
min_iter=min_iter,
|
|
112
|
+
select=select,
|
|
113
|
+
valid=valid,
|
|
114
|
+
finalize=finalize,
|
|
115
|
+
)
|
|
116
|
+
i = int(i)
|
|
117
|
+
if not bool(ok):
|
|
118
|
+
raise FloatingPointError(f"Nonfinite update at iteration {i}")
|
|
119
|
+
return state, bool(converged), i, np.asarray(history)[:i]
|
jirt/_optimize.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Device-native spectral projected gradient for box/linear constrained fits.
|
|
2
|
+
|
|
3
|
+
The optional solver keeps the original closed feasible set. SciPy remains the
|
|
4
|
+
reference/default; this path uses a projected-gradient stopping criterion.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from functools import partial
|
|
8
|
+
from types import SimpleNamespace
|
|
9
|
+
|
|
10
|
+
import jax
|
|
11
|
+
import jax.numpy as jnp
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _project(x, lower, upper, matrix, rhs, pairs=()):
|
|
16
|
+
"""Dykstra projection onto a box and linear half-spaces A x >= b."""
|
|
17
|
+
rows = matrix.shape[0]
|
|
18
|
+
if rows == 0:
|
|
19
|
+
return jnp.clip(x, lower, upper), jnp.array(True)
|
|
20
|
+
if pairs:
|
|
21
|
+
point = jnp.clip(x, lower, upper)
|
|
22
|
+
for row, (left, right) in enumerate(pairs):
|
|
23
|
+
gap = rhs[row]
|
|
24
|
+
boundary = jnp.clip(
|
|
25
|
+
(x[left] + x[right] - gap) / 2,
|
|
26
|
+
jnp.maximum(lower[left], lower[right] - gap),
|
|
27
|
+
jnp.minimum(upper[left], upper[right] - gap),
|
|
28
|
+
)
|
|
29
|
+
violates = point[right] - point[left] < gap
|
|
30
|
+
point = point.at[left].set(jnp.where(violates, boundary, point[left]))
|
|
31
|
+
point = point.at[right].set(
|
|
32
|
+
jnp.where(violates, boundary + gap, point[right])
|
|
33
|
+
)
|
|
34
|
+
return point, jnp.array(True)
|
|
35
|
+
norms = jnp.sum(matrix * matrix, axis=1)
|
|
36
|
+
|
|
37
|
+
def cycle(carry):
|
|
38
|
+
i, previous, box_correction, corrections, _ = carry
|
|
39
|
+
previous_box, previous_corrections = box_correction, corrections
|
|
40
|
+
z = previous + box_correction
|
|
41
|
+
point = jnp.clip(z, lower, upper)
|
|
42
|
+
box_correction = z - point
|
|
43
|
+
|
|
44
|
+
def row(k, state):
|
|
45
|
+
point, corrections = state
|
|
46
|
+
z = point + corrections[k] * matrix[k]
|
|
47
|
+
shift = jnp.maximum(rhs[k] - matrix[k] @ z, 0.0) / norms[k]
|
|
48
|
+
return z + shift * matrix[k], corrections.at[k].set(-shift)
|
|
49
|
+
|
|
50
|
+
point, corrections = jax.lax.fori_loop(0, rows, row, (point, corrections))
|
|
51
|
+
violation = jnp.maximum(
|
|
52
|
+
jnp.max(jnp.maximum(lower - point, point - upper)),
|
|
53
|
+
jnp.max(rhs - matrix @ point),
|
|
54
|
+
)
|
|
55
|
+
done = (
|
|
56
|
+
(jnp.max(jnp.abs(point - previous)) <= 1e-10)
|
|
57
|
+
& (jnp.max(jnp.abs(box_correction - previous_box)) <= 1e-10)
|
|
58
|
+
& (jnp.max(jnp.abs(corrections - previous_corrections)) <= 1e-10)
|
|
59
|
+
& (violation <= 1e-10)
|
|
60
|
+
)
|
|
61
|
+
return i + 1, point, box_correction, corrections, done
|
|
62
|
+
|
|
63
|
+
result = jax.lax.while_loop(
|
|
64
|
+
lambda c: (c[0] < 1000) & ~c[-1],
|
|
65
|
+
cycle,
|
|
66
|
+
(jnp.array(0), x, jnp.zeros_like(x), jnp.zeros(rows), jnp.array(False)),
|
|
67
|
+
)
|
|
68
|
+
return result[1], result[-1]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@partial(jax.jit, static_argnames=("loss", "config", "max_iter", "pairs"))
|
|
72
|
+
def _solve(
|
|
73
|
+
loss, x, args, lower, upper, matrix, rhs, tolerance, *, config, max_iter, pairs=()
|
|
74
|
+
):
|
|
75
|
+
evaluate = jax.value_and_grad(loss)
|
|
76
|
+
|
|
77
|
+
def objective(x):
|
|
78
|
+
return evaluate(x, *args, **dict(config))
|
|
79
|
+
|
|
80
|
+
value, gradient = objective(x)
|
|
81
|
+
trace = jnp.full(max_iter + 1, jnp.nan).at[0].set(value)
|
|
82
|
+
recent = jnp.full(10, value)
|
|
83
|
+
finite = jnp.isfinite(value) & jnp.all(jnp.isfinite(gradient))
|
|
84
|
+
# Status: 0 running, 1 converged, 2 line search, 3 projection, 4 nonfinite.
|
|
85
|
+
initial = (
|
|
86
|
+
jnp.array(0),
|
|
87
|
+
x,
|
|
88
|
+
value,
|
|
89
|
+
gradient,
|
|
90
|
+
jnp.array(1.0),
|
|
91
|
+
jnp.where(finite, 0, 4),
|
|
92
|
+
trace,
|
|
93
|
+
recent,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
def body(state):
|
|
97
|
+
i, x, value, gradient, scale, _, trace, recent = state
|
|
98
|
+
projected, ok = _project(x - gradient, lower, upper, matrix, rhs, pairs)
|
|
99
|
+
converged = jnp.max(jnp.abs(projected - x)) <= tolerance
|
|
100
|
+
target, target_ok = _project(
|
|
101
|
+
x - scale * gradient, lower, upper, matrix, rhs, pairs
|
|
102
|
+
)
|
|
103
|
+
direction = target - x
|
|
104
|
+
slope = gradient @ direction
|
|
105
|
+
ceiling = jnp.max(recent)
|
|
106
|
+
|
|
107
|
+
def trial(alpha):
|
|
108
|
+
point = x + alpha * direction
|
|
109
|
+
v, g = objective(point)
|
|
110
|
+
finite = jnp.isfinite(v) & jnp.all(jnp.isfinite(g))
|
|
111
|
+
accepted = finite & (v <= ceiling + 1e-4 * alpha * slope)
|
|
112
|
+
return point, v, g, accepted
|
|
113
|
+
|
|
114
|
+
point, v, g, accepted = trial(jnp.array(1.0))
|
|
115
|
+
search = jax.lax.while_loop(
|
|
116
|
+
lambda s: (s[0] < 40) & ~s[-1],
|
|
117
|
+
lambda s: (s[0] + 1, s[1] * 0.5, *trial(s[1] * 0.5)),
|
|
118
|
+
(jnp.array(0), jnp.array(1.0), point, v, g, accepted),
|
|
119
|
+
)
|
|
120
|
+
_, _, point, v, g, accepted = search
|
|
121
|
+
delta, dg = point - x, g - gradient
|
|
122
|
+
curvature = delta @ dg
|
|
123
|
+
next_scale = jnp.where(curvature > 0, (delta @ delta) / curvature, 1.0)
|
|
124
|
+
next_scale = jnp.clip(next_scale, 1e-6, 1e3)
|
|
125
|
+
status = jnp.where(
|
|
126
|
+
~(ok & target_ok), 3, jnp.where(converged, 1, jnp.where(accepted, 0, 2))
|
|
127
|
+
)
|
|
128
|
+
advance = status == 0
|
|
129
|
+
point = jnp.where(advance, point, x)
|
|
130
|
+
v = jnp.where(advance, v, value)
|
|
131
|
+
g = jnp.where(advance, g, gradient)
|
|
132
|
+
return (
|
|
133
|
+
i + advance.astype(int),
|
|
134
|
+
point,
|
|
135
|
+
v,
|
|
136
|
+
g,
|
|
137
|
+
next_scale,
|
|
138
|
+
status,
|
|
139
|
+
jax.lax.cond(advance, lambda t: t.at[i + 1].set(v), lambda t: t, trace),
|
|
140
|
+
jax.lax.cond(advance, lambda t: t.at[i % 10].set(v), lambda t: t, recent),
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
result = jax.lax.while_loop(
|
|
144
|
+
lambda s: (s[0] < max_iter) & (s[5] == 0), body, initial
|
|
145
|
+
)
|
|
146
|
+
i, x, value, gradient, _, status, trace, _ = result
|
|
147
|
+
projected, ok = _project(x - gradient, lower, upper, matrix, rhs, pairs)
|
|
148
|
+
status = jnp.where(
|
|
149
|
+
(status == 0) & ok & (jnp.max(jnp.abs(projected - x)) <= tolerance), 1, status
|
|
150
|
+
)
|
|
151
|
+
return x, value, i, status, trace
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def device_minimize(
|
|
155
|
+
loss, initial, args, *, lower, upper, constraints=(), config=(), max_iter, tolerance
|
|
156
|
+
):
|
|
157
|
+
"""Host boundary around one compiled solve; no iteration callbacks."""
|
|
158
|
+
x = np.asarray(initial, dtype=float)
|
|
159
|
+
matrices, limits = [], []
|
|
160
|
+
for constraint in constraints:
|
|
161
|
+
a = np.asarray(constraint.A, dtype=float)
|
|
162
|
+
lo = np.broadcast_to(constraint.lb, a.shape[0])
|
|
163
|
+
hi = np.broadcast_to(constraint.ub, a.shape[0])
|
|
164
|
+
matrices.extend((a[np.isfinite(lo)], -a[np.isfinite(hi)]))
|
|
165
|
+
limits.extend((lo[np.isfinite(lo)], -hi[np.isfinite(hi)]))
|
|
166
|
+
matrix = np.concatenate(matrices) if matrices else np.zeros((0, len(x)))
|
|
167
|
+
rhs = np.concatenate(limits) if limits else np.zeros(0)
|
|
168
|
+
if np.any(np.sum(matrix * matrix, axis=1) == 0):
|
|
169
|
+
raise ValueError("Constraint rows must be nonzero")
|
|
170
|
+
pairs = []
|
|
171
|
+
used = set()
|
|
172
|
+
for row in matrix:
|
|
173
|
+
left, right = np.flatnonzero(row == -1), np.flatnonzero(row == 1)
|
|
174
|
+
if (
|
|
175
|
+
len(left) != 1
|
|
176
|
+
or len(right) != 1
|
|
177
|
+
or np.count_nonzero(row) != 2
|
|
178
|
+
or int(left[0]) in used
|
|
179
|
+
or int(right[0]) in used
|
|
180
|
+
):
|
|
181
|
+
pairs = []
|
|
182
|
+
break
|
|
183
|
+
pair = (int(left[0]), int(right[0]))
|
|
184
|
+
pairs.append(pair)
|
|
185
|
+
used.update(pair)
|
|
186
|
+
x, value, iterations, status, trace = _solve(
|
|
187
|
+
loss,
|
|
188
|
+
jnp.asarray(x),
|
|
189
|
+
args,
|
|
190
|
+
jnp.asarray(lower),
|
|
191
|
+
jnp.asarray(upper),
|
|
192
|
+
jnp.asarray(matrix),
|
|
193
|
+
jnp.asarray(rhs),
|
|
194
|
+
jnp.asarray(tolerance),
|
|
195
|
+
config=config,
|
|
196
|
+
max_iter=max_iter,
|
|
197
|
+
pairs=tuple(pairs),
|
|
198
|
+
)
|
|
199
|
+
iterations, status = int(iterations), int(status)
|
|
200
|
+
if status == 4:
|
|
201
|
+
raise FloatingPointError("Nonfinite device objective or gradient")
|
|
202
|
+
messages = {
|
|
203
|
+
0: "Iteration limit reached",
|
|
204
|
+
1: "Converged (projected gradient)",
|
|
205
|
+
2: "Line search failed",
|
|
206
|
+
3: "Constraint projection failed",
|
|
207
|
+
}
|
|
208
|
+
return SimpleNamespace(
|
|
209
|
+
x=x,
|
|
210
|
+
fun=value,
|
|
211
|
+
nit=iterations,
|
|
212
|
+
success=status == 1,
|
|
213
|
+
message=messages[status],
|
|
214
|
+
trace=np.asarray(trace)[: iterations + 1],
|
|
215
|
+
)
|
jirt/amortized.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""Content-only item calibration with a shared logistic 1PL encoder."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
import jax
|
|
5
|
+
import jax.numpy as jnp
|
|
6
|
+
import numpy as np
|
|
7
|
+
from numpy.polynomial.hermite import hermgauss
|
|
8
|
+
from scipy.optimize import minimize
|
|
9
|
+
from jax.flatten_util import ravel_pytree
|
|
10
|
+
from jax.scipy.optimize import minimize as jax_minimize
|
|
11
|
+
from functools import partial
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _encode(params, features):
|
|
15
|
+
if "hidden" in params:
|
|
16
|
+
features = jnp.tanh(features @ params["hidden"] + params["hidden_bias"])
|
|
17
|
+
return features @ params["output"] + params["bias"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _posterior(difficulty, patterns, nodes, lw):
|
|
21
|
+
z = nodes[:, None] - difficulty[None, :]
|
|
22
|
+
joint = (
|
|
23
|
+
(patterns == 1) @ jax.nn.log_sigmoid(z).T
|
|
24
|
+
+ (patterns == 0) @ jax.nn.log_sigmoid(-z).T
|
|
25
|
+
+ lw
|
|
26
|
+
)
|
|
27
|
+
return jax.scipy.special.logsumexp(joint, axis=1), jax.nn.softmax(joint, axis=1)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _unpack(raw, layout):
|
|
31
|
+
params = {}
|
|
32
|
+
offset = 0
|
|
33
|
+
for name, shape in layout:
|
|
34
|
+
size = int(np.prod(shape))
|
|
35
|
+
params[name] = raw[offset : offset + size].reshape(shape)
|
|
36
|
+
offset += size
|
|
37
|
+
return params
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _loss(raw, data, layout):
|
|
41
|
+
features, patterns, freq, nodes, lw, l2 = data
|
|
42
|
+
params = _unpack(raw, layout)
|
|
43
|
+
ll, _ = _posterior(_encode(params, features), patterns, nodes, lw)
|
|
44
|
+
penalty = sum(jnp.sum(v * v) for k, v in params.items() if "bias" not in k)
|
|
45
|
+
return -(ll @ freq) / freq.sum() + 0.5 * l2 * penalty
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
_value_grad = jax.jit(jax.value_and_grad(_loss), static_argnames=("layout",))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@partial(jax.jit, static_argnames=("layout", "max_iter"))
|
|
52
|
+
def _fit_bfgs(raw, data, layout, max_iter, tolerance):
|
|
53
|
+
return jax_minimize(
|
|
54
|
+
lambda x: _loss(x, data, layout),
|
|
55
|
+
raw,
|
|
56
|
+
method="BFGS",
|
|
57
|
+
options=dict(maxiter=max_iter, gtol=tolerance),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass
|
|
62
|
+
class AmortizedResult:
|
|
63
|
+
params: dict
|
|
64
|
+
feature_mean: np.ndarray
|
|
65
|
+
feature_scale: np.ndarray
|
|
66
|
+
item_ids: tuple
|
|
67
|
+
difficulty: jax.Array
|
|
68
|
+
ability: jax.Array
|
|
69
|
+
ability_variance: jax.Array
|
|
70
|
+
converged: bool
|
|
71
|
+
iterations: int
|
|
72
|
+
log_likelihood: float
|
|
73
|
+
objective: float
|
|
74
|
+
trace: np.ndarray
|
|
75
|
+
message: str
|
|
76
|
+
|
|
77
|
+
def infer_difficulty(self, features):
|
|
78
|
+
"""Infer content-only difficulty using the frozen training transform."""
|
|
79
|
+
x = np.asarray(features, dtype=float)
|
|
80
|
+
if (
|
|
81
|
+
x.ndim != 2
|
|
82
|
+
or x.shape[1] != len(self.feature_mean)
|
|
83
|
+
or not np.isfinite(x).all()
|
|
84
|
+
):
|
|
85
|
+
raise ValueError("features must be finite (items, training_feature_count)")
|
|
86
|
+
return _encode(
|
|
87
|
+
self.params, jnp.asarray((x - self.feature_mean) / self.feature_scale)
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
def predict(self, features, *, theta=None):
|
|
91
|
+
"""Predict (subjects,new_items) at supplied abilities or training EAPs."""
|
|
92
|
+
b = self.infer_difficulty(features)
|
|
93
|
+
theta = self.ability if theta is None else jnp.atleast_1d(jnp.asarray(theta))
|
|
94
|
+
return jax.nn.sigmoid(theta[:, None] - b[None, :])
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def amortized_irt(
|
|
98
|
+
responses,
|
|
99
|
+
*,
|
|
100
|
+
item_features,
|
|
101
|
+
item_ids,
|
|
102
|
+
feature_item_ids,
|
|
103
|
+
key,
|
|
104
|
+
hidden_size=16,
|
|
105
|
+
l2=1e-4,
|
|
106
|
+
quadrature_points=41,
|
|
107
|
+
max_iter=1000,
|
|
108
|
+
tolerance=1e-10,
|
|
109
|
+
jit=True,
|
|
110
|
+
optimizer="scipy",
|
|
111
|
+
):
|
|
112
|
+
"""Fit a shared content encoder by regularized normal-marginal 1PL MLE.
|
|
113
|
+
|
|
114
|
+
Responses are (N,J) binary with NaN missing. Feature rows are explicitly
|
|
115
|
+
reordered from feature_item_ids to response-column item_ids; both must
|
|
116
|
+
contain the same unique string identifiers. Only training items may enter
|
|
117
|
+
this call. The stored mean/scale never refits on prediction features.
|
|
118
|
+
|
|
119
|
+
hidden_size>0 uses one tanh hidden layer; zero uses an affine encoder.
|
|
120
|
+
Unit discrimination and fixed N(0,1) person distribution identify the scale.
|
|
121
|
+
No item-specific offsets or variational posteriors are used. key controls
|
|
122
|
+
initialization. optimizer="scipy" uses full-batch L-BFGS-B; "jax" uses
|
|
123
|
+
device-side BFGS with a gradient-infinity-norm stopping tolerance. The JAX
|
|
124
|
+
path requires jit=True and records only initial/final objectives in trace.
|
|
125
|
+
It reports line-search failure and iteration exhaustion as nonconvergence.
|
|
126
|
+
The loss
|
|
127
|
+
is mean negative person marginal log likelihood plus l2/2 times the sum of
|
|
128
|
+
squared encoder weights (biases excluded). Explicit key is always required.
|
|
129
|
+
"""
|
|
130
|
+
if not jax.config.x64_enabled:
|
|
131
|
+
raise ValueError("Enable JAX x64 before fitting")
|
|
132
|
+
for value, name, minimum in (
|
|
133
|
+
(hidden_size, "hidden_size", 0),
|
|
134
|
+
(quadrature_points, "quadrature_points", 3),
|
|
135
|
+
(max_iter, "max_iter", 1),
|
|
136
|
+
):
|
|
137
|
+
if (
|
|
138
|
+
isinstance(value, bool)
|
|
139
|
+
or not isinstance(value, (int, np.integer))
|
|
140
|
+
or value < minimum
|
|
141
|
+
):
|
|
142
|
+
raise ValueError(f"{name} must be an integer >= {minimum}")
|
|
143
|
+
for value, name, minimum in ((l2, "l2", 0), (tolerance, "tolerance", 0)):
|
|
144
|
+
if (
|
|
145
|
+
not np.isscalar(value)
|
|
146
|
+
or not np.isfinite(value)
|
|
147
|
+
or value < minimum
|
|
148
|
+
or (name == "tolerance" and value == 0)
|
|
149
|
+
):
|
|
150
|
+
raise ValueError(f"Invalid {name}")
|
|
151
|
+
if not isinstance(jit, bool):
|
|
152
|
+
raise ValueError("jit must be boolean")
|
|
153
|
+
if optimizer not in ("scipy", "jax") or (optimizer == "jax" and not jit):
|
|
154
|
+
raise ValueError("optimizer must be scipy or jax; jax requires jit=True")
|
|
155
|
+
# Validate typed and legacy JAX keys before doing any optimization work.
|
|
156
|
+
try:
|
|
157
|
+
k1, k2 = jax.random.split(key)
|
|
158
|
+
except (TypeError, ValueError) as exc:
|
|
159
|
+
raise ValueError("key must be a JAX random key") from exc
|
|
160
|
+
y = np.asarray(responses, dtype=float)
|
|
161
|
+
x = np.asarray(item_features, dtype=float)
|
|
162
|
+
if y.ndim != 2 or min(y.shape) < 2:
|
|
163
|
+
raise ValueError("responses must have at least two subjects/items")
|
|
164
|
+
if not (np.isnan(y) | (y == 0) | (y == 1)).all():
|
|
165
|
+
raise ValueError("responses must be binary or NaN")
|
|
166
|
+
if np.any(np.all(np.isnan(y), axis=0)):
|
|
167
|
+
raise ValueError("Every training item needs observed responses")
|
|
168
|
+
ids = tuple(item_ids)
|
|
169
|
+
fids = tuple(feature_item_ids)
|
|
170
|
+
if (
|
|
171
|
+
not all(isinstance(v, str) for v in ids + fids)
|
|
172
|
+
or len(ids) != y.shape[1]
|
|
173
|
+
or len(set(ids)) != len(ids)
|
|
174
|
+
or len(set(fids)) != len(fids)
|
|
175
|
+
or set(ids) != set(fids)
|
|
176
|
+
):
|
|
177
|
+
raise ValueError("Item IDs must be unique strings with matching sets")
|
|
178
|
+
if (
|
|
179
|
+
x.ndim != 2
|
|
180
|
+
or x.shape[0] != len(fids)
|
|
181
|
+
or x.shape[1] < 1
|
|
182
|
+
or not np.isfinite(x).all()
|
|
183
|
+
):
|
|
184
|
+
raise ValueError("item_features must be a finite aligned matrix")
|
|
185
|
+
lookup = {v: i for i, v in enumerate(fids)}
|
|
186
|
+
x = x[[lookup[v] for v in ids]]
|
|
187
|
+
mean = x.mean(axis=0)
|
|
188
|
+
scale = x.std(axis=0)
|
|
189
|
+
scale = np.where(scale > 1e-12, scale, 1.0)
|
|
190
|
+
features = jnp.asarray((x - mean) / scale)
|
|
191
|
+
F = x.shape[1]
|
|
192
|
+
if hidden_size:
|
|
193
|
+
params = dict(
|
|
194
|
+
hidden=jax.random.normal(k1, (F, hidden_size), dtype=jnp.float64)
|
|
195
|
+
/ np.sqrt(F),
|
|
196
|
+
hidden_bias=jnp.zeros(hidden_size),
|
|
197
|
+
output=0.1
|
|
198
|
+
* jax.random.normal(k2, (hidden_size,), dtype=jnp.float64)
|
|
199
|
+
/ np.sqrt(hidden_size),
|
|
200
|
+
bias=jnp.array(0.0),
|
|
201
|
+
)
|
|
202
|
+
else:
|
|
203
|
+
params = dict(
|
|
204
|
+
output=0.01 * jax.random.normal(k1, (F,), dtype=jnp.float64),
|
|
205
|
+
bias=jnp.array(0.0),
|
|
206
|
+
)
|
|
207
|
+
raw, _ = ravel_pytree(params)
|
|
208
|
+
layout = tuple((name, tuple(params[name].shape)) for name in sorted(params))
|
|
209
|
+
patterns, inverse, freq = np.unique(
|
|
210
|
+
np.where(np.isnan(y), -1, y).astype(int),
|
|
211
|
+
axis=0,
|
|
212
|
+
return_inverse=True,
|
|
213
|
+
return_counts=True,
|
|
214
|
+
)
|
|
215
|
+
patterns = jnp.asarray(patterns)
|
|
216
|
+
freq = jnp.asarray(freq)
|
|
217
|
+
nodes, w = hermgauss(quadrature_points)
|
|
218
|
+
nodes = jnp.asarray(nodes * np.sqrt(2))
|
|
219
|
+
lw = jnp.asarray(np.log(w) - 0.5 * np.log(np.pi))
|
|
220
|
+
|
|
221
|
+
data = (features, patterns, freq, nodes, lw, jnp.asarray(l2))
|
|
222
|
+
evaluate = _value_grad if jit else jax.value_and_grad(_loss)
|
|
223
|
+
|
|
224
|
+
def objective(raw):
|
|
225
|
+
value, grad = evaluate(jnp.asarray(raw), data, layout)
|
|
226
|
+
if not np.isfinite(value) or not np.isfinite(grad).all():
|
|
227
|
+
raise FloatingPointError("Nonfinite amortized objective")
|
|
228
|
+
return float(value), np.asarray(grad)
|
|
229
|
+
|
|
230
|
+
trace = [objective(raw)[0]]
|
|
231
|
+
if optimizer == "jax":
|
|
232
|
+
opt = _fit_bfgs(raw, data, layout, max_iter, jnp.asarray(tolerance))
|
|
233
|
+
if not np.isfinite(opt.fun) or not np.isfinite(opt.x).all():
|
|
234
|
+
raise FloatingPointError("Nonfinite amortized optimization result")
|
|
235
|
+
trace.append(float(opt.fun))
|
|
236
|
+
message = {
|
|
237
|
+
0: "Converged (gradient norm)",
|
|
238
|
+
1: "Iteration limit reached",
|
|
239
|
+
3: "Line search zoom failed",
|
|
240
|
+
4: "Line search failed (saddle point)",
|
|
241
|
+
5: "Line search iteration limit reached",
|
|
242
|
+
}.get(int(opt.status), f"BFGS status {int(opt.status)}")
|
|
243
|
+
else:
|
|
244
|
+
opt = minimize(
|
|
245
|
+
objective,
|
|
246
|
+
np.asarray(raw),
|
|
247
|
+
jac=True,
|
|
248
|
+
method="L-BFGS-B",
|
|
249
|
+
callback=lambda r: trace.append(objective(r)[0]),
|
|
250
|
+
options=dict(maxiter=max_iter, ftol=tolerance, gtol=tolerance),
|
|
251
|
+
)
|
|
252
|
+
message = str(opt.message)
|
|
253
|
+
params = _unpack(jnp.asarray(opt.x), layout)
|
|
254
|
+
b = _encode(params, features)
|
|
255
|
+
ll, post = _posterior(b, patterns, nodes, lw)
|
|
256
|
+
ability = post @ nodes
|
|
257
|
+
variance = jnp.sum(post * (nodes[None, :] - ability[:, None]) ** 2, axis=1)
|
|
258
|
+
return AmortizedResult(
|
|
259
|
+
params,
|
|
260
|
+
mean,
|
|
261
|
+
scale,
|
|
262
|
+
ids,
|
|
263
|
+
b,
|
|
264
|
+
ability[inverse],
|
|
265
|
+
variance[inverse],
|
|
266
|
+
bool(opt.success),
|
|
267
|
+
int(opt.nit),
|
|
268
|
+
float(ll @ freq),
|
|
269
|
+
float(opt.fun),
|
|
270
|
+
np.asarray(trace),
|
|
271
|
+
message,
|
|
272
|
+
)
|