From 7a5af021df3969b12d45f39f48aa9a67a8a72f17 Mon Sep 17 00:00:00 2001 From: Frankie Robertson Date: Mon, 9 Nov 2026 19:35:22 +0200 Subject: [PATCH 1/2] Support Float32 fixed-grid density tracking and MEPV --- src/Aggregators/ability_estimator.jl | 6 +- src/Aggregators/ability_tracker.jl | 15 ++- src/Aggregators/ability_trackers/grid.jl | 43 +++++-- src/Aggregators/log_grid.jl | 20 ++-- src/NextItemRules/combinators/grid_mepv.jl | 58 +++++++--- src/NextItemRules/prelude/criteria.jl | 5 +- src/NextItemRules/strategies/exhaustive.jl | 7 +- src/Responses.jl | 16 ++- test/prepared_grid_mepv.jl | 124 ++++++++++++++++++++- 9 files changed, 245 insertions(+), 49 deletions(-) diff --git a/src/Aggregators/ability_estimator.jl b/src/Aggregators/ability_estimator.jl index a236507..c6bf9ea 100644 --- a/src/Aggregators/ability_estimator.jl +++ b/src/Aggregators/ability_estimator.jl @@ -319,12 +319,16 @@ function mean( denom) end +# Scalar coordinates and their estimated mean can have different precisions. +squared_deviation(mean::Real) = x -> abs2(x - mean) +squared_deviation(mean) = IntegralCoeffs.SqDev(mean) + function variance_given_mean(integrator::AbilityIntegrator, est::DistributionAbilityEstimator, tracked_responses::TrackedResponses, mean, denom = normdenom(integrator, est, tracked_responses)) - expectation(IntegralCoeffs.SqDev(mean), + expectation(squared_deviation(mean), 0, integrator, est, diff --git a/src/Aggregators/ability_tracker.jl b/src/Aggregators/ability_tracker.jl index 4af8191..7228cec 100644 --- a/src/Aggregators/ability_tracker.jl +++ b/src/Aggregators/ability_tracker.jl @@ -69,8 +69,11 @@ mutable struct StackedGridAbilityTracker{T <: AbilityTracker, D} <: AbilityTrack delta_start::Int end -StackedGridAbilityTracker(parent, density::D, delta_start) where {D} = - StackedGridAbilityTracker{typeof(parent), D}(parent, density, deepcopy(density), delta_start) +StackedGridAbilityTracker(parent, density::Vector, delta_start) = + StackedGridAbilityTracker{typeof(parent), Vector}(parent, density, copy(density), delta_start) +StackedGridAbilityTracker(parent, density::LogGridWeights, delta_start) = + StackedGridAbilityTracker{typeof(parent), LogGridWeights}( + parent, density, deepcopy(density), delta_start) base_grid_tracker(tracker::StackedGridAbilityTracker) = base_grid_tracker(tracker.parent) base_grid_tracker(tracker) = tracker @@ -79,11 +82,17 @@ function track_delta!(responses::TrackedResponses, tracker::StackedGridAbilityTr tracker.density = nothing parent_density = tracker.parent.density parent_density === nothing && throw(ArgumentError("Track the parent before speculating")) - tracker.density = grid_delta_density!(tracker.scratch, base_grid_tracker(tracker), + density = grid_delta_density!(tracker.scratch, base_grid_tracker(tracker), parent_density, responses, tracker.delta_start) + tracker.scratch = updated_grid_scratch(tracker.scratch, density) + tracker.density = density tracker end +updated_grid_scratch(scratch, density) = density +updated_grid_scratch(scratch::LogGridWeights, density::LogGridWeights) = + scratch.log_values === density.log_values ? scratch : density + track!(responses::TrackedResponses, tracker::StackedGridAbilityTracker) = track_delta!(responses, tracker) track_append!(responses::TrackedResponses, tracker::StackedGridAbilityTracker) = diff --git a/src/Aggregators/ability_trackers/grid.jl b/src/Aggregators/ability_trackers/grid.jl index 27a45b7..4c5e1b8 100644 --- a/src/Aggregators/ability_trackers/grid.jl +++ b/src/Aggregators/ability_trackers/grid.jl @@ -1,8 +1,9 @@ const EqualWeightGridIntegrator = Union{FixedGridIntegrator, PreallocatedFixedGridIntegrator, Integrators.IterativeFixedGridIntegrator} -const ScalarGridIntegrator = Union{FixedGridIntegrator{<:AbstractVector{Float64}}, - PreallocatedFixedGridIntegrator{<:AbstractVector{Float64}}, - Integrators.IterativeFixedGridIntegrator{<:AbstractVector{Float64}}} +const ScalarGrid = Union{AbstractVector{Float32}, AbstractVector{Float64}} +const ScalarGridIntegrator = Union{FixedGridIntegrator{<:ScalarGrid}, + PreallocatedFixedGridIntegrator{<:ScalarGrid}, + Integrators.IterativeFixedGridIntegrator{<:ScalarGrid}} const TabulatedDichotomousBank = Union{FittedItemBanks.DichotomousPointsItemBank, FittedItemBanks.DichotomousPointsWithLogsItemBank} @@ -27,6 +28,10 @@ $(TYPEDEF) Cache an unnormalized density on an equal-weight fixed grid. The estimator must declare `MultiplicativeResponseDelta()` through [`response_delta_style`](@ref). +The density uses the precision of the evaluated prior and responses. +Use Float32 coordinates, prior parameters and a Float32 2PL transfer bank +for Float32 EAP and prepared MEPV. FittedItemBanks 0.7.7 widens Float32 +guess/slip responses to Float64. Appending responses multiplies only their probabilities into `density`; `track!`, rollback and clearing rebuild the density, including its prior. @@ -41,10 +46,10 @@ mutable struct GriddedAbilityTracker{ } <: AbilityTracker ability_estimator::AbilityEstimatorT integrator::IntegratorT - density::Union{Nothing, Vector{Float64}} + density::Union{Nothing, Vector} function GriddedAbilityTracker(est::E, integrator::I, - density::Union{Nothing, Vector{Float64}}) where { + density::Union{Nothing, Vector}) where { E <: DistributionAbilityEstimator, I <: EqualWeightGridIntegrator} require_response_deltas(est) density === nothing || length(density) == length(Integrators.get_grid(integrator)) || @@ -67,8 +72,8 @@ end function track!(responses::TrackedResponses, tracker::GriddedAbilityTracker) responses.speculation_start == 0 || return tracker tracker.density = nothing - tracker.density = grid_linear_values(pdf(tracker.ability_estimator, responses), - Integrators.get_grid(tracker.integrator)) + tracker.density = collect(grid_linear_values(pdf(tracker.ability_estimator, responses), + Integrators.get_grid(tracker.integrator))) tracker end @@ -79,8 +84,8 @@ function track_append!(responses::TrackedResponses, tracker::GriddedAbilityTrack tracker.density = nothing delta = response_view(responses.responses, length(responses):length(responses)) likelihood = AbilityLikelihood(responses.item_bank, delta) - density .*= grid_delta_values(likelihood, Integrators.get_grid(tracker.integrator)) - tracker.density = density + factors = grid_delta_values(likelihood, Integrators.get_grid(tracker.integrator)) + tracker.density = update_grid_buffer!(density, *, density, factors) tracker end @@ -88,10 +93,24 @@ function refresh_after_history_edit!(responses, tracker::GriddedAbilityTracker) track!(responses, tracker) end -function grid_delta_density!(scratch::Vector{Float64}, tracker::GriddedAbilityTracker, +# Widen when a response has more precision than the existing buffer. In +# particular, an empty history's density has not seen the bank's response type. +function update_grid_buffer!(buffer, op, density, factors) + values = Base.Broadcast.broadcasted(op, density, factors) + if Base.Broadcast.combine_eltypes(values.f, values.args) === eltype(buffer) + return Base.materialize!(buffer, values) + end + Base.materialize(values) +end + +copy_grid_buffer!(scratch::Vector{T}, density::Vector{T}) where {T} = copyto!(scratch, density) +copy_grid_buffer!(scratch, density) = copy(density) + +function grid_delta_density!(scratch::Vector, tracker::GriddedAbilityTracker, density, responses, start) - start > length(responses) && return copyto!(scratch, density) + start > length(responses) && return copy_grid_buffer!(scratch, density) delta = response_view(responses.responses, start:length(responses)) likelihood = AbilityLikelihood(responses.item_bank, delta) - scratch .= density .* grid_delta_values(likelihood, Integrators.get_grid(tracker.integrator)) + factors = grid_delta_values(likelihood, Integrators.get_grid(tracker.integrator)) + update_grid_buffer!(scratch, *, density, factors) end diff --git a/src/Aggregators/log_grid.jl b/src/Aggregators/log_grid.jl index 612e522..5b91499 100644 --- a/src/Aggregators/log_grid.jl +++ b/src/Aggregators/log_grid.jl @@ -10,6 +10,8 @@ equal-weight fixed grid. Construct with `LogGridAbilityTracker(estimator, grid)` `tracker.density` contains `log_values`, normalized `weights`, `log_scale` and `scaled_sum`; the unnormalized grid mass is `exp(log_scale) * scaled_sum`. An all-zero density raises `DomainError` rather than manufacturing a posterior. +Float32 coordinates, prior parameters and native Float32 log responses keep +the cached log densities and weights in Float32. Wider inputs promote them. The estimator must declare `MultiplicativeResponseDelta()` through [`response_delta_style`](@ref). Appends add only new response log probabilities @@ -89,15 +91,16 @@ initialize_grid_tracker!(responses, tracker::LogGridAbilityTracker) = track!(res function grid_delta_density!(scratch::LogGridWeights, tracker::LogGridAbilityTracker, density, responses, start) if start > length(responses) - copyto!(scratch.log_values, density.log_values) - copyto!(scratch.weights, density.weights) - return LogGridWeights(scratch.log_values, - scratch.weights, density.log_scale, density.scaled_sum) + logs = copy_grid_buffer!(scratch.log_values, density.log_values) + weights = copy_grid_buffer!(scratch.weights, density.weights) + return LogGridWeights(logs, weights, density.log_scale, density.scaled_sum) end delta = response_view(responses.responses, start:length(responses)) - scratch.log_values .= density.log_values .+ grid_delta_values( - AbilityLogLikelihood(responses.item_bank, delta), Integrators.get_grid(tracker.integrator)) - normalize_grid_weights!(scratch.log_values, scratch.weights) + factors = grid_delta_values(AbilityLogLikelihood(responses.item_bank, delta), + Integrators.get_grid(tracker.integrator)) + logs = update_grid_buffer!(scratch.log_values, +, density.log_values, factors) + weights = eltype(logs) === eltype(scratch.weights) ? scratch.weights : similar(logs) + normalize_grid_weights!(logs, weights) end """ @@ -184,7 +187,8 @@ function expectation(rett::IntReturnType, f::F, ncomp, integrator::LogGridIntegr value = weighted_grid_mean(f, Integrators.get_grid(integrator.integrator), density) # Cancel the mass before multiplying by the moment. This also avoids loss of # precision from adding a moment's logarithm to a huge log normalization scale. - correction = denom === nothing ? 1.0 : unlog(grid_mass(density) / denom) + denom === nothing && return rett(BareIntegrationResult(value)) + correction = unlog(grid_mass(density) / denom) rett(BareIntegrationResult(value * correction)) end diff --git a/src/NextItemRules/combinators/grid_mepv.jl b/src/NextItemRules/combinators/grid_mepv.jl index f136607..9dc12f9 100644 --- a/src/NextItemRules/combinators/grid_mepv.jl +++ b/src/NextItemRules/combinators/grid_mepv.jl @@ -27,30 +27,56 @@ function prepare_grid_mepv(criterion, history, ::OneDimContinuousDomain, integrator::Union{ Aggregators.TrackedLikelihoodIntegrator{<:Aggregators.ScalarGridIntegrator}, LogGridIntegrator{<:Aggregators.ScalarGridIntegrator}}) - grid = prepare_mepv_grid(Integrators.get_grid(get_integrator(integrator))) + coordinates = Integrators.get_grid(get_integrator(integrator)) + bank = history.item_bank + paired = paired_mepv_bank(bank) + # Custom banks retain their existing Float64 path. On Float32 grids + # speculation can accommodate wider responses without rounding them. + eltype(coordinates) === Float32 && !paired && return Speculator(history, 1) + grid = prepare_mepv_grid(coordinates) density = deepcopy(Aggregators.grid_density(criterion.criterion.dist_est, history, integrator)) + scratch = if paired + T = candidate_factor_type(density, bank, eltype(grid)) + isconcretetype(T) || return Speculator(history, 1) + candidate_pair_scratch(density, T) + else + candidate_grid_scratch(density, ResponseType(bank)) + end theta = criterion.response_expectation.ability_estimator(history) - PreparedGridMEPV(grid, density, theta, - candidate_grid_scratch(density, ResponseType(history.item_bank), history.item_bank)) + PreparedGridMEPV(grid, density, theta, scratch) +end + +const PairedMEPVBank = Union{TransferItemBank, SlopeInterceptTransferItemBank, + CdfMirtItemBank, SlopeInterceptMirtItemBank} +paired_mepv_bank(::AbstractItemBank) = false +paired_mepv_bank(::PairedMEPVBank) = true +paired_mepv_bank(bank::GuessAndSlipItemBank) = paired_mepv_bank(bank.inner_bank) + +function candidate_factor_type(density, bank, coordinate_type) + response_pair = density isa Integrators.LogGridWeights ? log_resp_vec : resp_vec + # A bank with abstractly typed parameters may vary precision by item. + # Specialize the buffers only if one factor type covers the entire scan. + eltype(Base.promote_op(response_pair, ItemResponse{typeof(bank)}, coordinate_type)) +end + +function candidate_pair_scratch(density::AbstractVector, factor_type) + T = promote_type(eltype(density), factor_type) + (similar(density, T), similar(density, T)) +end + +function candidate_pair_scratch(density::Integrators.LogGridWeights, factor_type) + T = promote_type(eltype(density.log_values), factor_type) + template = T === eltype(density.log_values) ? density : + Integrators.LogGridWeights(T.(density.log_values)) + (deepcopy(template), deepcopy(template)) end candidate_grid_scratch(density, response_type) = deepcopy(density) -candidate_grid_scratch(density, response_type, bank) = candidate_grid_scratch(density, response_type) # Native vector log responses preserve both tails for all supported banks. candidate_grid_scratch(density::Integrators.LogGridWeights, ::BooleanResponse) = (deepcopy(density), deepcopy(density)) -# Only opt into paired ordinary responses where FIB preserves both tails. -# Custom banks retain scalar evaluation: their resp_vec may still form 1-p. -candidate_grid_scratch(density::AbstractVector, ::BooleanResponse, bank) = - candidate_linear_scratch(density, bank) -candidate_linear_scratch(density, bank::AbstractItemBank) = deepcopy(density) -candidate_linear_scratch(density, bank::Union{TransferItemBank, SlopeInterceptTransferItemBank, - CdfMirtItemBank, SlopeInterceptMirtItemBank}) = (deepcopy(density), deepcopy(density)) -candidate_linear_scratch(density, bank::GuessAndSlipItemBank) = - candidate_linear_scratch(density, bank.inner_bank) - function candidate_grid_density!(scratch::AbstractVector, density::AbstractVector, ir, category, grid) @inbounds for j in eachindex(scratch, density, grid) @@ -75,7 +101,7 @@ end function candidate_expected_variance(criterion, state, ir, scratch) probabilities = resp_vec(ir, state.theta) - value = 0.0 + value = zero(state.theta) for (probability, category) in zip(probabilities, responses(ir)) density = candidate_grid_density!(scratch, state.density, ir, category, state.grid) value += probability * candidate_grid_variance(criterion, state.grid, density) @@ -115,7 +141,7 @@ function candidate_expected_variance(criterion, state, ir, end function candidate_grid_variance(criterion, grid, density::AbstractVector) - criterion.skip_zero && all(iszero, density) && return Inf + criterion.skip_zero && all(iszero, density) && return oftype(float(zero(eltype(density))), Inf) Integrators.weighted_grid_moments(grid, density).variance end diff --git a/src/NextItemRules/prelude/criteria.jl b/src/NextItemRules/prelude/criteria.jl index 190b24c..5988bff 100644 --- a/src/NextItemRules/prelude/criteria.jl +++ b/src/NextItemRules/prelude/criteria.jl @@ -70,7 +70,10 @@ function compute_criteria( responses::TrackedResponseT, items::AbstractItemBank ) where {ItemCriterionT <: ItemCriterion, TrackedResponseT <: TrackedResponses} - objective_state = init_thread(criterion, responses) + compute_criteria(criterion, init_thread(criterion, responses), responses, items) +end + +function compute_criteria(criterion, objective_state, responses, items) return [compute_criterion(criterion, objective_state, responses, item_idx) for item_idx in eachindex(items)] end diff --git a/src/NextItemRules/strategies/exhaustive.jl b/src/NextItemRules/strategies/exhaustive.jl index 3f51bc0..b54757d 100644 --- a/src/NextItemRules/strategies/exhaustive.jl +++ b/src/NextItemRules/strategies/exhaustive.jl @@ -28,7 +28,10 @@ function exhaustive_search(objective::ItemCriterionT, Int, Float64 } where {ItemCriterionT <: ItemCriterion, TrackedResponseT <: TrackedResponses} - objective_state = init_thread(objective, responses) + exhaustive_search(objective, init_thread(objective, responses), responses, items) +end + +function exhaustive_search(objective, objective_state, responses, items) return exhaustive_search(responses.responses.indices, items) do item_idx return compute_criterion(objective, objective_state, responses, item_idx) end @@ -51,4 +54,4 @@ function best_item( items ) where {ItemCriterionT <: ItemCriterion} exhaustive_search(rule.criterion, responses, items)[1] -end \ No newline at end of file +end diff --git a/src/Responses.jl b/src/Responses.jl index 6d5de5c..ea9ed6a 100644 --- a/src/Responses.jl +++ b/src/Responses.jl @@ -164,17 +164,26 @@ function AbilityLogLikelihood(item_bank::AbstractItemBank, responses::BareRespon AbilityLogLikelihood(AbilityLikelihood(item_bank, responses)) end +# With no responses there is no probability type to use. Take the identity +# from the ability coordinate, without evaluating any item in the bank. +likelihood_unit(θ) = 1.0 +likelihood_unit(θ::Number) = one(float(θ)) +likelihood_unit(θ::AbstractArray{T}) where {T <: Number} = + isconcretetype(T) ? one(float(T)) : 1.0 + function (log_likelihood::AbilityLogLikelihood)(θ) likelihood = log_likelihood.likelihood + isempty(likelihood.responses.indices) && return zero(likelihood_unit(θ)) # As in AbilityLikelihood, traverse the response arrays directly. Iterating # BareResponses carries a nested generator in its state, which can escape # and allocate at every grid point when coverage instrumentation is enabled. - sum((log_resp(ItemResponse(likelihood.item_bank, likelihood.responses.indices[i]), + sum(log_resp(ItemResponse(likelihood.item_bank, likelihood.responses.indices[i]), likelihood.responses.values[i], θ) - for i in axes(likelihood.responses.indices, 1)); init = 0.0) + for i in axes(likelihood.responses.indices, 1)) end function (ability_lh::AbilityLikelihood)(θ) + isempty(ability_lh.responses.indices) && return likelihood_unit(θ) return prod( resp( ItemResponse( @@ -184,8 +193,7 @@ function (ability_lh::AbilityLikelihood)(θ) ability_lh.responses.values[resp_idx], θ ) - for resp_idx in axes(ability_lh.responses.indices, 1); - init = 1.0 + for resp_idx in axes(ability_lh.responses.indices, 1) ) end diff --git a/test/prepared_grid_mepv.jl b/test/prepared_grid_mepv.jl index ec4996e..e590a61 100644 --- a/test/prepared_grid_mepv.jl +++ b/test/prepared_grid_mepv.jl @@ -1,9 +1,10 @@ module PreparedGridMEPVTests using Test -using Distributions: Normal, pdf, logpdf +using Distributions: Logistic, Normal, pdf, logpdf import Distributions -using ComputerAdaptiveTesting: Aggregators, NextItemRules +using ComputerAdaptiveTesting: Aggregators, NextItemRules, Stateful, TerminationConditions +using ComputerAdaptiveTesting.Rules: CatRules using ComputerAdaptiveTesting.Aggregators using ComputerAdaptiveTesting.NextItemRules using ComputerAdaptiveTesting.Responses @@ -39,6 +40,120 @@ function generic_values(criterion, history) [compute_criterion(criterion, spec, history, i) for i in eachindex(history.item_bank)] end +function reference_2pl(grid, prior, difficulties, slopes, history) + xs = Float64.(grid) + p(i, x, y) = inv(1 + exp((y ? -1 : 1) * slopes[i] * (x - difficulties[i]))) + density = [pdf(prior, x) * prod(p(r.index, x, r.value) for r in history; init=1.0) + for x in xs] + theta = sum(xs .* density) / sum(density) + scores = map(eachindex(difficulties)) do i + sum((false, true)) do y + weights = density .* p.(i, xs, y) + mean = sum(xs .* weights) / sum(weights) + p(i, theta, y) * sum(weights .* (xs .- mean).^2) / sum(weights) + end + end + (; density, theta, scores) +end + +density_values(density::AbstractVector) = density +density_values(density::Integrators.LogGridWeights) = exp.(density.log_values) +density_eltype(density::AbstractVector) = eltype(density) +density_eltype(density::Integrators.LogGridWeights) = eltype(density.weights) + +@testset "Float32 fixed-grid MEPV" for space in (LinSpace(), LogSpace()) + xs = range(-4f0, 4f0; length=33) + grid = Integrators.FixedGridIntegrator(xs) + prior = Normal(0.35f0, 1.1f0) + difficulties = Float32[-1.7, -0.9, -0.3, 0.6, 1.4, 2.1] + slopes = Float32[0.9, 1.6, 1.1, 1.4, 1.3, 0.8] + bank = TransferItemBank(Logistic(0f0, 1f0), difficulties, slopes) + dist = PosteriorAbilityEstimator(prior, space) + tracker = AbilityTracker(GriddedAbilityTracker, dist, grid) + integral = AbilityIntegrator(grid, tracker) + point = MeanAbilityEstimator(dist, integral) + rules = preallocate(CatRules(; ability_estimator=point, + next_item=ItemCriterionRule(point, AbilityVariance(dist, integral)), + termination_condition=TerminationConditions.RunForever())) + cat = Stateful.StatefulCat(rules, bank) + history = cat.tracked_responses[] + criterion = cat.rules.next_item.criterion + + function check(history, committed) + ref = reference_2pl(xs, prior, difficulties, slopes, history.responses) + state = init_thread(criterion, history) + @test state isa NextItemRules.PreparedGridMEPV + @test state.grid isa Vector{Float32} + @test state.theta isa Float32 + @test state.theta ≈ ref.theta atol=2e-6 + @test density_eltype(state.density) === Float32 + @test density_values(state.density) ≈ ref.density rtol=2e-6 + @test all(s -> density_eltype(s) === Float32, state.scratch) + actual = committed ? Stateful.item_criteria(cat) : compute_criteria(criterion, history) + @test eltype(actual) === Float32 + @test actual ≈ ref.scores rtol=3e-6 + if committed + available = setdiff(eachindex(bank), history.responses.indices) + @test Stateful.next_item(cat) == available[argmin(ref.scores[available])] + end + end + + likelihood = AbilityLikelihood(bank, history.responses) + loglikelihood = AbilityLogLikelihood(likelihood) + @test likelihood(0f0) === 1f0 + @test loglikelihood(0f0) === 0f0 + track!(history) + @test density_eltype(tracker.density) === Float32 + check(history, true) + + for (i, outcome) in ((1, true), (2, false)) + Stateful.add_response!(cat, i, outcome) + @test likelihood(0f0) isa Float32 + @test loglikelihood(0f0) isa Float32 + @test density_eltype(tracker.density) === Float32 + check(history, true) + end + committed_density = copy(density_values(tracker.density)) + spec = Speculator(history, 1) + for outcome in (true, false) + replace_speculation!(spec, [3], [outcome]) + @test density_eltype(spec.responses.ability_tracker.head.scratch) === Float32 + check(spec.responses, false) + @test density_values(tracker.density) == committed_density + end + Stateful.rollback!(cat) + check(history, true) + Stateful.reset!(cat) + check(history, true) + add_response!(history.responses, Response(ResponseType(bank), 4, true)) + track!(history) + check(history, true) + + # A wider prior and a wider bank both promote the computation. In the + # latter case, the empty cache itself still uses the Float32 prior. + for wide_prior in (true, false) + mixed_dist = PosteriorAbilityEstimator(wide_prior ? Normal() : prior, space) + mixed_bank = wide_prior ? bank : + TransferItemBank(Logistic(), Float64.(difficulties), Float64.(slopes)) + mixed_tracker = AbilityTracker(GriddedAbilityTracker, mixed_dist, grid) + mixed_integral = AbilityIntegrator(grid, mixed_tracker) + mixed_point = MeanAbilityEstimator(mixed_dist, mixed_integral) + mixed_criterion = ExpectationBasedItemCriterion(PointResponseExpectation(mixed_point), + AbilityVariance(mixed_dist, mixed_integral)) + mixed = TrackedResponses(BareResponses(ResponseType(mixed_bank)), mixed_bank, mixed_tracker) + track!(mixed) + @test density_eltype(mixed_tracker.density) === (wide_prior ? Float64 : Float32) + @test all(s -> density_eltype(s) === Float64, init_thread(mixed_criterion, mixed).scratch) + mixed_spec = Speculator(mixed, 1) + replace_speculation!(mixed_spec, [1], [true]) + @test mixed_point(mixed_spec.responses) isa Float64 + @test density_eltype(mixed_spec.responses.ability_tracker.scratch) === Float64 + add_response!(mixed, Response(ResponseType(mixed_bank), 1, true)) + @test density_eltype(mixed_tracker.density) === Float64 + @test eltype(compute_criteria(mixed_criterion, mixed)) === Float64 + end +end + struct CountedPosterior <: DistributionAbilityEstimator calls::Base.RefValue{Int} end @@ -255,6 +370,11 @@ end @test counted.vector_calls[] == 1 @test compute_criteria(custom.criterion, custom.history) ≈ generic_values(custom.reference, custom.history) rtol=1e-12 + custom32 = setup(; bank=counted, n=4, history_length=2, + points=range(-4f0, 4f0; length=33)) + @test init_thread(custom32.criterion, custom32.history) isa Speculator + @test compute_criteria(custom32.criterion, custom32.history) ≈ + generic_values(custom32.reference, custom32.history) rtol=3e-6 certain = GuessAndSlipItemBank(ones(1), zeros(1), ItemBank2PL([0.], [1.])) zero_case = setup(; bank=certain, n=1, history_length=0) From dbb60f788dd60163d463840cfd056d805de758a1 Mon Sep 17 00:00:00 2001 From: Frankie Robertson Date: Tue, 10 Nov 2026 21:10:57 +0200 Subject: [PATCH 2/2] Generalize fixed-grid MEPV to real coordinates --- src/Aggregators/ability_trackers/grid.jl | 5 +- src/Aggregators/log_grid.jl | 4 +- src/NextItemRules/combinators/expectation.jl | 7 +- src/NextItemRules/combinators/grid_mepv.jl | 69 +++++++++++-------- .../criteria/state/ability_variance.jl | 4 +- src/NextItemRules/strategies/exhaustive.jl | 12 ++-- src/Responses.jl | 4 +- test/prepared_grid_mepv.jl | 50 +++++++++++++- 8 files changed, 103 insertions(+), 52 deletions(-) diff --git a/src/Aggregators/ability_trackers/grid.jl b/src/Aggregators/ability_trackers/grid.jl index 4c5e1b8..63a1a8d 100644 --- a/src/Aggregators/ability_trackers/grid.jl +++ b/src/Aggregators/ability_trackers/grid.jl @@ -1,6 +1,6 @@ const EqualWeightGridIntegrator = Union{FixedGridIntegrator, PreallocatedFixedGridIntegrator, Integrators.IterativeFixedGridIntegrator} -const ScalarGrid = Union{AbstractVector{Float32}, AbstractVector{Float64}} +const ScalarGrid = AbstractVector{<:Real} const ScalarGridIntegrator = Union{FixedGridIntegrator{<:ScalarGrid}, PreallocatedFixedGridIntegrator{<:ScalarGrid}, Integrators.IterativeFixedGridIntegrator{<:ScalarGrid}} @@ -28,7 +28,8 @@ $(TYPEDEF) Cache an unnormalized density on an equal-weight fixed grid. The estimator must declare `MultiplicativeResponseDelta()` through [`response_delta_style`](@ref). -The density uses the precision of the evaluated prior and responses. +Scalar grids accept real coordinates. The density uses the numeric types +produced by the prior and responses. Use Float32 coordinates, prior parameters and a Float32 2PL transfer bank for Float32 EAP and prepared MEPV. FittedItemBanks 0.7.7 widens Float32 guess/slip responses to Float64. diff --git a/src/Aggregators/log_grid.jl b/src/Aggregators/log_grid.jl index 5b91499..db1944d 100644 --- a/src/Aggregators/log_grid.jl +++ b/src/Aggregators/log_grid.jl @@ -10,8 +10,8 @@ equal-weight fixed grid. Construct with `LogGridAbilityTracker(estimator, grid)` `tracker.density` contains `log_values`, normalized `weights`, `log_scale` and `scaled_sum`; the unnormalized grid mass is `exp(log_scale) * scaled_sum`. An all-zero density raises `DomainError` rather than manufacturing a posterior. -Float32 coordinates, prior parameters and native Float32 log responses keep -the cached log densities and weights in Float32. Wider inputs promote them. +The cached log densities and weights use the floating-point type supported +by PsychometricsBazaarBase's `LogGridWeights` for the evaluated log densities. The estimator must declare `MultiplicativeResponseDelta()` through [`response_delta_style`](@ref). Appends add only new response log probabilities diff --git a/src/NextItemRules/combinators/expectation.jl b/src/NextItemRules/combinators/expectation.jl index 0c93aad..b8aa522 100644 --- a/src/NextItemRules/combinators/expectation.jl +++ b/src/NextItemRules/combinators/expectation.jl @@ -136,13 +136,14 @@ function compute_criterion( tracked_responses, item_idx) possible_responses = responses(ItemResponse(tracked_responses.item_bank, item_idx)) - res = 0.0 + res = nothing for (prob, possible_response) in zip(exp_resp, possible_responses) replace_speculation!(speculator, SVector(item_idx), SVector(possible_response)) - res += prob * + value = prob * _generic_criterion(item_criterion.criterion, speculator.responses, item_idx, possible_response) + res = res === nothing ? value : res + value end - res + something(res, 0.0) end function power_summary(io::IO, item_criterion::ExpectationBasedItemCriterion) diff --git a/src/NextItemRules/combinators/grid_mepv.jl b/src/NextItemRules/combinators/grid_mepv.jl index 9dc12f9..1975753 100644 --- a/src/NextItemRules/combinators/grid_mepv.jl +++ b/src/NextItemRules/combinators/grid_mepv.jl @@ -27,23 +27,22 @@ function prepare_grid_mepv(criterion, history, ::OneDimContinuousDomain, integrator::Union{ Aggregators.TrackedLikelihoodIntegrator{<:Aggregators.ScalarGridIntegrator}, LogGridIntegrator{<:Aggregators.ScalarGridIntegrator}}) - coordinates = Integrators.get_grid(get_integrator(integrator)) + grid = prepare_mepv_grid(Integrators.get_grid(get_integrator(integrator))) bank = history.item_bank - paired = paired_mepv_bank(bank) - # Custom banks retain their existing Float64 path. On Float32 grids - # speculation can accommodate wider responses without rounding them. - eltype(coordinates) === Float32 && !paired && return Speculator(history, 1) - grid = prepare_mepv_grid(coordinates) - density = deepcopy(Aggregators.grid_density(criterion.criterion.dist_est, history, integrator)) - scratch = if paired - T = candidate_factor_type(density, bank, eltype(grid)) - isconcretetype(T) || return Speculator(history, 1) - candidate_pair_scratch(density, T) + density = Aggregators.grid_density(criterion.criterion.dist_est, history, integrator) + paired = paired_mepv_bank(density, bank) + T = candidate_weight_type(density, ItemResponse{typeof(bank)}, eltype(grid), + eltype(history.responses.values), paired) + scratch = if isconcretetype(T) && T <: Real + candidate_grid_scratch(density, T, paired) + elseif paired + return Speculator(history, 1) else - candidate_grid_scratch(density, ResponseType(bank)) + # Let each outcome determine its own buffer type. + nothing end theta = criterion.response_expectation.ability_estimator(history) - PreparedGridMEPV(grid, density, theta, scratch) + PreparedGridMEPV(grid, deepcopy(density), theta, scratch) end const PairedMEPVBank = Union{TransferItemBank, SlopeInterceptTransferItemBank, @@ -52,31 +51,33 @@ paired_mepv_bank(::AbstractItemBank) = false paired_mepv_bank(::PairedMEPVBank) = true paired_mepv_bank(bank::GuessAndSlipItemBank) = paired_mepv_bank(bank.inner_bank) -function candidate_factor_type(density, bank, coordinate_type) - response_pair = density isa Integrators.LogGridWeights ? log_resp_vec : resp_vec - # A bank with abstractly typed parameters may vary precision by item. - # Specialize the buffers only if one factor type covers the entire scan. - eltype(Base.promote_op(response_pair, ItemResponse{typeof(bank)}, coordinate_type)) +paired_mepv_bank(::AbstractVector, bank) = paired_mepv_bank(bank) +paired_mepv_bank(::Integrators.LogGridWeights, bank) = ResponseType(bank) isa BooleanResponse + +function candidate_weight_type(::AbstractVector{W}, ::Type{IR}, + ::Type{X}, ::Type{C}, paired) where {W, IR, X, C} + paired ? Base.promote_op((w, ir, x, i) -> w * resp_vec(ir, x)[i], W, IR, X, Int) : + Base.promote_op((w, ir, c, x) -> w * resp(ir, c, x), W, IR, C, X) +end + +function candidate_weight_type(::Integrators.LogGridWeights{W}, ::Type{IR}, + ::Type{X}, ::Type{C}, paired) where {W, IR, X, C} + paired ? Base.promote_op((w, ir, x, i) -> w + log_resp_vec(ir, x)[i], W, IR, X, Int) : + Base.promote_op((w, ir, c, x) -> w + log_resp(ir, c, x), W, IR, C, X) end -function candidate_pair_scratch(density::AbstractVector, factor_type) - T = promote_type(eltype(density), factor_type) - (similar(density, T), similar(density, T)) +function candidate_grid_scratch(density::AbstractVector, T, paired) + scratch = similar(density, T) + paired ? (scratch, similar(scratch)) : scratch end -function candidate_pair_scratch(density::Integrators.LogGridWeights, factor_type) - T = promote_type(eltype(density.log_values), factor_type) +function candidate_grid_scratch(density::Integrators.LogGridWeights, T, paired) template = T === eltype(density.log_values) ? density : Integrators.LogGridWeights(T.(density.log_values)) - (deepcopy(template), deepcopy(template)) + scratch = deepcopy(template) + paired ? (scratch, deepcopy(template)) : scratch end -candidate_grid_scratch(density, response_type) = deepcopy(density) - -# Native vector log responses preserve both tails for all supported banks. -candidate_grid_scratch(density::Integrators.LogGridWeights, ::BooleanResponse) = - (deepcopy(density), deepcopy(density)) - function candidate_grid_density!(scratch::AbstractVector, density::AbstractVector, ir, category, grid) @inbounds for j in eachindex(scratch, density, grid) @@ -93,6 +94,14 @@ function candidate_grid_density!(scratch::Integrators.LogGridWeights, Integrators.normalize_grid_weights!(scratch.log_values, scratch.weights) end +function candidate_grid_density!(::Nothing, density::AbstractVector, ir, category, grid) + density .* resp.(Ref(ir), Ref(category), grid) +end + +function candidate_grid_density!(::Nothing, density::Integrators.LogGridWeights, ir, category, grid) + Integrators.LogGridWeights(density.log_values .+ log_resp.(Ref(ir), Ref(category), grid)) +end + function compute_criterion(criterion::GridMEPVCriterion, state::PreparedGridMEPV, history::TrackedResponses, item_idx) ir = ItemResponse(history.item_bank, item_idx) diff --git a/src/NextItemRules/criteria/state/ability_variance.jl b/src/NextItemRules/criteria/state/ability_variance.jl index 547e76c..21bb37f 100644 --- a/src/NextItemRules/criteria/state/ability_variance.jl +++ b/src/NextItemRules/criteria/state/ability_variance.jl @@ -23,7 +23,7 @@ function AbilityVariance(bits...) end function compute_criterion(criterion::AbilityVariance, - tracked_responses::TrackedResponses)::Float64 + tracked_responses::TrackedResponses) # XXX: Not sure if the estimator should come from somewhere else here denom = normdenom(criterion.integrator, criterion.dist_est, @@ -38,7 +38,7 @@ end function compute_criterion(criterion::AbilityVariance, ::Union{OneDimContinuousDomain, DiscreteDomain}, tracked_responses::TrackedResponses, - denom)::Float64 + denom) return variance( criterion.integrator, criterion.dist_est, diff --git a/src/NextItemRules/strategies/exhaustive.jl b/src/NextItemRules/strategies/exhaustive.jl index b54757d..4c116ea 100644 --- a/src/NextItemRules/strategies/exhaustive.jl +++ b/src/NextItemRules/strategies/exhaustive.jl @@ -2,9 +2,9 @@ function exhaustive_search( callback, answered_items::AbstractVector{Int}, items::AbstractItemBank -)::Tuple{Int, Float64} +) min_obj_idx::Int = -1 - min_obj_val::Float64 = Inf + min_obj_val = Inf for item_idx in eachindex(items) # TODO: Add these back in #@init irf_states_storage = zeros(Int, length(responses) + 1) @@ -22,12 +22,8 @@ function exhaustive_search( return (min_obj_idx, min_obj_val) end -function exhaustive_search(objective::ItemCriterionT, - responses::TrackedResponseT, - items::AbstractItemBank)::Tuple{ - Int, - Float64 -} where {ItemCriterionT <: ItemCriterion, TrackedResponseT <: TrackedResponses} +function exhaustive_search(objective::ItemCriterion, responses::TrackedResponses, + items::AbstractItemBank) exhaustive_search(objective, init_thread(objective, responses), responses, items) end diff --git a/src/Responses.jl b/src/Responses.jl index ea9ed6a..540f188 100644 --- a/src/Responses.jl +++ b/src/Responses.jl @@ -167,9 +167,9 @@ end # With no responses there is no probability type to use. Take the identity # from the ability coordinate, without evaluating any item in the bank. likelihood_unit(θ) = 1.0 -likelihood_unit(θ::Number) = one(float(θ)) +likelihood_unit(θ::Number) = one(θ) likelihood_unit(θ::AbstractArray{T}) where {T <: Number} = - isconcretetype(T) ? one(float(T)) : 1.0 + isconcretetype(T) ? one(T) : 1.0 function (log_likelihood::AbilityLogLikelihood)(θ) likelihood = log_likelihood.likelihood diff --git a/test/prepared_grid_mepv.jl b/test/prepared_grid_mepv.jl index e590a61..5083b64 100644 --- a/test/prepared_grid_mepv.jl +++ b/test/prepared_grid_mepv.jl @@ -41,7 +41,7 @@ function generic_values(criterion, history) end function reference_2pl(grid, prior, difficulties, slopes, history) - xs = Float64.(grid) + xs = promote_type(Float64, eltype(grid)).(grid) p(i, x, y) = inv(1 + exp((y ? -1 : 1) * slopes[i] * (x - difficulties[i]))) density = [pdf(prior, x) * prod(p(r.index, x, r.value) for r in history; init=1.0) for x in xs] @@ -372,7 +372,7 @@ end generic_values(custom.reference, custom.history) rtol=1e-12 custom32 = setup(; bank=counted, n=4, history_length=2, points=range(-4f0, 4f0; length=33)) - @test init_thread(custom32.criterion, custom32.history) isa Speculator + @test init_thread(custom32.criterion, custom32.history).scratch isa Vector{Float64} @test compute_criteria(custom32.criterion, custom32.history) ≈ generic_values(custom32.reference, custom32.history) rtol=3e-6 @@ -390,12 +390,56 @@ end ItemResponse(certain, 1), first(skip_state.scratch))) end + @testset "Other real coordinate types" for space in (LinSpace(), LogSpace()) + for T in (Float16, BigFloat) + xs = T.(range(-4, 4; length=33)) + prior = Normal(zero(T), one(T)) + difficulties = T[-2, -1, 0, 1, 2] + slopes = ones(T, 5) + bank = TransferItemBank(Logistic(zero(T), one(T)), difficulties, slopes) + grid = Integrators.FixedGridIntegrator(xs) + dist = PosteriorAbilityEstimator(prior, space) + tracker = AbilityTracker(GriddedAbilityTracker, dist, grid) + integral = AbilityIntegrator(grid, tracker) + point = MeanAbilityEstimator(dist, integral) + criterion = ExpectationBasedItemCriterion(PointResponseExpectation(point), + AbilityVariance(dist, integral)) + history = TrackedResponses(BareResponses(ResponseType(bank)), bank, tracker) + track!(history) + add_response!(history, Response(ResponseType(bank), 1, true)) + state = init_thread(criterion, history) + @test state isa NextItemRules.PreparedGridMEPV + @test state.theta isa T + @test density_eltype(state.density) === T + @test all(s -> density_eltype(s) === T, state.scratch) + @test compute_criterion(criterion.criterion, history) isa T + ref = reference_2pl(xs, prior, difficulties, slopes, history.responses) + actual = compute_criteria(criterion, history) + @test eltype(actual) === T + @test actual ≈ ref.scores rtol=16eps(T) + end + + config = setup(; space, points=range(-4//1, 4//1; length=33)) + @test init_thread(config.criterion, config.history) isa NextItemRules.PreparedGridMEPV + @test compute_criteria(config.criterion, config.history) ≈ + generic_values(config.reference, config.history) rtol=1e-12 + likelihood = AbilityLikelihood(config.bank, BareResponses(ResponseType(config.bank))) + @test likelihood(0//1) === 1//1 + end + + @testset "Exhaustive selection keeps criterion precision" begin + bank = ItemBank2PL([-1.0, 0.0, 1.0], ones(3)) + scores = [1 + 2eps(BigFloat), 1 + eps(BigFloat), 1 + 3eps(BigFloat)] + @test NextItemRules.exhaustive_search(i -> scores[i], Int[], bank) === + (2, scores[2]) + end + @testset "Polytomous per-outcome fallback" begin bank = FittedItemBanks.OneDimensionItemBankAdapter( NominalItemBank([[-1.0, 0.0, 1.0]], [1.0], [[-0.5, 0.0, 0.5]])) (; history, criterion, reference) = setup(; space = LogSpace(), bank, n = 1, history_length = 0) - @test init_thread(criterion, history).scratch isa Integrators.LogGridWeights + @test init_thread(criterion, history) isa NextItemRules.PreparedGridMEPV @test compute_criteria(criterion, history) ≈ generic_values(reference, history) rtol=1e-12 end end