Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use a faster and safer implementation of alias_sample! #927

Merged
merged 3 commits into from
Apr 12, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
2 changes: 2 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ authors = ["JuliaStats"]
version = "0.34.3"

[deps]
AliasTables = "66dad0bd-aa9a-41b7-9441-69ab47430ed8"
DataAPI = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
DataStructures = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Expand All @@ -17,6 +18,7 @@ Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
StatsAPI = "82ae8749-77ed-4fe6-ae5f-f523153014b0"

[compat]
AliasTables = "1"
DataAPI = "1"
DataStructures = "0.10, 0.11, 0.12, 0.13, 0.14, 0.17, 0.18"
LinearAlgebra = "<0.0.1, 1"
Expand Down
23 changes: 9 additions & 14 deletions src/sampling.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#
###########################################################

using AliasTables
using Random: Sampler

if VERSION < v"1.3.0-DEV.565"
Expand Down Expand Up @@ -704,29 +705,23 @@ Build an alias table, and sample therefrom.
Reference: Walker, A. J. "An Efficient Method for Generating Discrete Random Variables
with General Distributions." *ACM Transactions on Mathematical Software* 3 (3): 253, 1977.

Noting `k=length(x)` and `n=length(a)`, this algorithm takes ``O(n \\log n)`` time
for building the alias table, and then ``O(1)`` to draw each sample. It consumes ``2 k`` random numbers.
Noting `k=length(x)` and `n=length(a)`, this algorithm takes ``O(n)`` time
for building the alias table, and then ``O(1)`` to draw each sample. It consumes ``k`` random numbers.
"""
function alias_sample!(rng::AbstractRNG, a::AbstractArray, wv::AbstractWeights, x::AbstractArray)
Base.mightalias(a, x) &&
throw(ArgumentError("output array x must not share memory with input array a"))
Base.mightalias(x, wv) &&
throw(ArgumentError("output array x must not share memory with weights array wv"))
1 == firstindex(a) == firstindex(wv) == firstindex(x) ||
1 == firstindex(a) == firstindex(wv) ||
throw(ArgumentError("non 1-based arrays are not supported"))
n = length(a)
length(wv) == n || throw(DimensionMismatch("Inconsistent lengths."))
length(wv) == length(a) || throw(DimensionMismatch("Inconsistent lengths."))

# create alias table
ap = Vector{Float64}(undef, n)
alias = Vector{Int}(undef, n)
make_alias_table!(wv, sum(wv), ap, alias)
at = AliasTable(wv)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess there is no reason to keep make_alias_table! (defined above) around.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to the public API of StatsBase, no, there's no reason. However there are some usages downstream of that internal function. Most notably, Distributions.jl, which would break if we remove make_alias_table! before we merge JuliaStats/Distributions.jl#1848. Once Distributions.jl no longer depends on this, I think it's worth removing.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems Distributions might be the only more widely used package that relies on these internals? I was aware of potential problems with using an internal function when writing ConsistencyResampling, and would be fine with breaking it (and probably switching to AliasTables) 😛 But given the impact on Distributions, maybe it would be safer to deprecate make_alias_table! and remove it in a future breaking release.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO it would even be acceptable to deprecate it and remove it in a future non-breaking release once Distributions has a few releases out that don't use it.


# sampling
s = Sampler(rng, 1:n)
for i = 1:length(x)
j = rand(rng, s)
x[i] = rand(rng) < ap[j] ? a[j] : a[alias[j]]
for i in eachindex(x)
j = rand(rng, at)
x[i] = a[j]
end
return x
end
Expand Down
3 changes: 3 additions & 0 deletions test/wsampling.jl
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ for wv in (
check_wsample_wrep(a, (4, 7), wv, 5.0e-3; ordered=false)
end

@test_throws ArgumentError alias_sample!(rand(10), weights(fill(0, 10)), rand(10))
@test_throws ArgumentError alias_sample!(rand(100), weights(randn(100)), rand(10))

for rev in (true, false), T in (Int, Int16, Float64, Float16, BigInt, ComplexF64, Rational{Int})
r = rev ? reverse(4:7) : (4:7)
r = T===Int ? r : T.(r)
Expand Down
Loading