Skip to content

Commit a9e45f3

Browse files
committed
Decouple sum/prod promotion from reduce
1 parent fefcfe0 commit a9e45f3

File tree

8 files changed

+153
-87
lines changed

8 files changed

+153
-87
lines changed

NEWS.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,9 @@ Language changes
9595
* Prefix `&` for by-reference arguments to `ccall` has been deprecated in favor of
9696
`Ref` argument types ([#6080]).
9797

98+
* `reduce(+, [...])` and `reduce(*, [...])` no longer widen the iterated over arguments to
99+
system word size. `sum` and `prod` still preserve this behavior. ([#22825])
100+
98101
Breaking changes
99102
----------------
100103

base/process.jl

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -230,8 +230,6 @@ setenv(cmd::Cmd; dir="") = Cmd(cmd; dir=dir)
230230
(&)(left::AbstractCmd, right::AbstractCmd) = AndCmds(left, right)
231231
redir_out(src::AbstractCmd, dest::AbstractCmd) = OrCmds(src, dest)
232232
redir_err(src::AbstractCmd, dest::AbstractCmd) = ErrOrCmds(src, dest)
233-
Base.mr_empty(f, op::typeof(&), T::Type{<:Base.AbstractCmd}) =
234-
throw(ArgumentError("reducing over an empty collection of type $T with operator & is not allowed"))
235233

236234
# Stream Redirects
237235
redir_out(dest::Redirectable, src::AbstractCmd) = CmdRedirect(src, dest, STDIN_NO)

base/reduce.jl

Lines changed: 83 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -5,45 +5,29 @@
55
###### Generic (map)reduce functions ######
66

77
if Int === Int32
8-
const SmallSigned = Union{Int8,Int16}
9-
const SmallUnsigned = Union{UInt8,UInt16}
8+
const SmallSigned = Union{Int8,Int16}
9+
const SmallUnsigned = Union{UInt8,UInt16}
1010
else
11-
const SmallSigned = Union{Int8,Int16,Int32}
12-
const SmallUnsigned = Union{UInt8,UInt16,UInt32}
11+
const SmallSigned = Union{Int8,Int16,Int32}
12+
const SmallUnsigned = Union{UInt8,UInt16,UInt32}
1313
end
1414

15-
const CommonReduceResult = Union{UInt64,UInt128,Int64,Int128,Float16,Float32,Float64}
16-
const WidenReduceResult = Union{SmallSigned, SmallUnsigned}
17-
18-
promote_sys_size{T}(::Type{T}) = T
19-
promote_sys_size{T<:SmallSigned}(::Type{T}) = Int
20-
promote_sys_size{T<:SmallUnsigned}(::Type{T}) = UInt
21-
# r_promote_type: promote T to the type of reduce(op, ::Array{T})
22-
# (some "extra" methods are required here to avoid ambiguity warnings)
23-
r_promote_type(op, ::Type{T}) where {T} = T
24-
r_promote_type(op, ::Type{T}) where {T<:WidenReduceResult} = promote_sys_size(T)
25-
r_promote_type(::typeof(+), ::Type{T}) where {T<:WidenReduceResult} = promote_sys_size(T)
26-
r_promote_type(::typeof(*), ::Type{T}) where {T<:WidenReduceResult} = promote_sys_size(T)
27-
r_promote_type(::typeof(+), ::Type{T}) where {T<:Number} = typeof(zero(T)+zero(T))
28-
r_promote_type(::typeof(*), ::Type{T}) where {T<:Number} = typeof(one(T)*one(T))
29-
r_promote_type(::typeof(scalarmax), ::Type{T}) where {T<:WidenReduceResult} = T
30-
r_promote_type(::typeof(scalarmin), ::Type{T}) where {T<:WidenReduceResult} = T
31-
r_promote_type(::typeof(max), ::Type{T}) where {T<:WidenReduceResult} = T
32-
r_promote_type(::typeof(min), ::Type{T}) where {T<:WidenReduceResult} = T
33-
34-
# r_promote: promote x to the type of reduce(op, [x])
35-
r_promote(op, x::T) where {T} = convert(r_promote_type(op, T), x)
15+
# Certain reductions like sum and prod may wish to promote the items being
16+
# reduced over to an appropriate size.
17+
promote_sys_size(x) = x
18+
promote_sys_size(x::SmallSigned) = Int(x)
19+
promote_sys_size(x::SmallUnsigned) = UInt(x)
3620

3721
## foldl && mapfoldl
3822

3923
@noinline function mapfoldl_impl(f, op, v0, itr, i)
4024
# Unroll the while loop once; if v0 is known, the call to op may
4125
# be evaluated at compile time
4226
if done(itr, i)
43-
return r_promote(op, v0)
27+
return v0
4428
else
4529
(x, i) = next(itr, i)
46-
v = op(r_promote(op, v0), f(x))
30+
v = op(v0, f(x))
4731
while !done(itr, i)
4832
@inbounds (x, i) = next(itr, i)
4933
v = op(v, f(x))
@@ -69,7 +53,7 @@ this cannot be used with empty collections (see `reduce(op, itr)`).
6953
function mapfoldl(f, op, itr)
7054
i = start(itr)
7155
if done(itr, i)
72-
return Base.mr_empty_iter(f, op, itr, iteratoreltype(itr))
56+
return Base.mapreduce_empty_iter(f, op, itr, iteratoreltype(itr))
7357
end
7458
(x, i) = next(itr, i)
7559
v0 = f(x)
@@ -108,10 +92,10 @@ function mapfoldr_impl(f, op, v0, itr, i::Integer)
10892
# Unroll the while loop once; if v0 is known, the call to op may
10993
# be evaluated at compile time
11094
if isempty(itr) || i == 0
111-
return r_promote(op, v0)
95+
return v0
11296
else
11397
x = itr[i]
114-
v = op(f(x), r_promote(op, v0))
98+
v = op(f(x), v0)
11599
while i > 1
116100
x = itr[i -= 1]
117101
v = op(f(x), v)
@@ -137,7 +121,7 @@ this cannot be used with empty collections (see `reduce(op, itr)`).
137121
function mapfoldr(f, op, itr)
138122
i = endof(itr)
139123
if isempty(itr)
140-
return Base.mr_empty_iter(f, op, itr, iteratoreltype(itr))
124+
return Base.mapreduce_empty_iter(f, op, itr, iteratoreltype(itr))
141125
end
142126
return mapfoldr_impl(f, op, f(itr[i]), itr, i-1)
143127
end
@@ -180,12 +164,12 @@ foldr(op, itr) = mapfoldr(identity, op, itr)
180164
@noinline function mapreduce_impl(f, op, A::AbstractArray, ifirst::Integer, ilast::Integer, blksize::Int)
181165
if ifirst == ilast
182166
@inbounds a1 = A[ifirst]
183-
return r_promote(op, f(a1))
167+
return f(a1)
184168
elseif ifirst + blksize > ilast
185169
# sequential portion
186170
@inbounds a1 = A[ifirst]
187171
@inbounds a2 = A[ifirst+1]
188-
v = op(r_promote(op, f(a1)), r_promote(op, f(a2)))
172+
v = op(f(a1), f(a2))
189173
@simd for i = ifirst + 2 : ilast
190174
@inbounds ai = A[i]
191175
v = op(v, f(ai))
@@ -244,39 +228,49 @@ pairwise_blocksize(::typeof(abs2), ::typeof(+)) = 4096
244228

245229
# handling empty arrays
246230
_empty_reduce_error() = throw(ArgumentError("reducing over an empty collection is not allowed"))
247-
mr_empty(f, op, T) = _empty_reduce_error()
248-
# use zero(T)::T to improve type information when zero(T) is not defined
249-
mr_empty(::typeof(identity), op::typeof(+), T) = r_promote(op, zero(T)::T)
250-
mr_empty(::typeof(abs), op::typeof(+), T) = r_promote(op, abs(zero(T)::T))
251-
mr_empty(::typeof(abs2), op::typeof(+), T) = r_promote(op, abs2(zero(T)::T))
252-
mr_empty(::typeof(identity), op::typeof(*), T) = r_promote(op, one(T)::T)
253-
mr_empty(::typeof(abs), op::typeof(scalarmax), T) = abs(zero(T)::T)
254-
mr_empty(::typeof(abs2), op::typeof(scalarmax), T) = abs2(zero(T)::T)
255-
mr_empty(::typeof(abs), op::typeof(max), T) = mr_empty(abs, scalarmax, T)
256-
mr_empty(::typeof(abs2), op::typeof(max), T) = mr_empty(abs2, scalarmax, T)
257-
mr_empty(f, op::typeof(&), T) = true
258-
mr_empty(f, op::typeof(|), T) = false
259-
260-
mr_empty_iter(f, op, itr, ::HasEltype) = mr_empty(f, op, eltype(itr))
261-
mr_empty_iter(f, op::typeof(&), itr, ::EltypeUnknown) = true
262-
mr_empty_iter(f, op::typeof(|), itr, ::EltypeUnknown) = false
263-
mr_empty_iter(f, op, itr, ::EltypeUnknown) = _empty_reduce_error()
231+
reduce_empty(op, T) = _empty_reduce_error()
232+
reduce_empty(::typeof(+), T) = zero(T)
233+
reduce_empty(::typeof(*), T) = one(T)
234+
reduce_empty(::typeof(&), ::Type{Bool}) = true
235+
reduce_empty(::typeof(|), ::Type{Bool}) = false
236+
237+
mapreduce_empty(f, op, T) = _empty_reduce_error()
238+
mapreduce_empty(::typeof(identity), op, T) = reduce_empty(op, T)
239+
mapreduce_empty(::typeof(promote_sys_size), op, T) =
240+
promote_sys_size(mapreduce_empty(identity, op, T))
241+
mapreduce_empty(::typeof(abs), ::typeof(+), T) = abs(zero(T))
242+
mapreduce_empty(::typeof(abs2), ::typeof(+), T) = abs2(zero(T))
243+
mapreduce_empty(::typeof(abs), ::Union{typeof(scalarmax), typeof(max)}, T) =
244+
abs(zero(T))
245+
mapreduce_empty(::typeof(abs2), ::Union{typeof(scalarmax), typeof(max)}, T) =
246+
abs2(zero(T))
247+
248+
# Allow mapreduce_empty to “see through” promote_sys_size
249+
let ComposedFunction = typename(typeof(identity identity)).wrapper
250+
global mapreduce_empty(f::ComposedFunction{typeof(promote_sys_size)}, op, T) =
251+
promote_sys_size(mapreduce_empty(f.g, op, T))
252+
end
253+
254+
mapreduce_empty_iter(f, op, itr, ::HasEltype) = mapreduce_empty(f, op, eltype(itr))
255+
mapreduce_empty_iter(f, op::typeof(&), itr, ::EltypeUnknown) = true
256+
mapreduce_empty_iter(f, op::typeof(|), itr, ::EltypeUnknown) = false
257+
mapreduce_empty_iter(f, op, itr, ::EltypeUnknown) = _empty_reduce_error()
264258

265259
_mapreduce(f, op, A::AbstractArray) = _mapreduce(f, op, IndexStyle(A), A)
266260

267261
function _mapreduce(f, op, ::IndexLinear, A::AbstractArray{T}) where T
268262
inds = linearindices(A)
269263
n = length(inds)
270264
if n == 0
271-
return mr_empty(f, op, T)
265+
return mapreduce_empty(f, op, T)
272266
elseif n == 1
273267
@inbounds a1 = A[inds[1]]
274-
return r_promote(op, f(a1))
268+
return f(a1)
275269
elseif n < 16 # process short array here, avoid mapreduce_impl() compilation
276270
@inbounds i = inds[1]
277271
@inbounds a1 = A[i]
278272
@inbounds a2 = A[i+=1]
279-
s = op(r_promote(op, f(a1)), r_promote(op, f(a2)))
273+
s = op(f(a1), f(a2))
280274
while i < last(inds)
281275
@inbounds Ai = A[i+=1]
282276
s = op(s, f(Ai))
@@ -299,9 +293,6 @@ Reduce the given collection `itr` with the given binary operator `op`. `v0` must
299293
neutral element for `op` that will be returned for empty collections. It is unspecified
300294
whether `v0` is used for non-empty collections.
301295
302-
The return type is `Int` (`UInt`) for (un)signed integers of less than system word size.
303-
For all other arguments, a common return type is found to which all arguments are promoted.
304-
305296
Reductions for certain commonly-used operators may have special implementations, and
306297
should be used instead: `maximum(itr)`, `minimum(itr)`, `sum(itr)`, `prod(itr)`,
307298
`any(itr)`, `all(itr)`.
@@ -347,24 +338,47 @@ reduce(op, a::Number) = a
347338
348339
Sum the results of calling function `f` on each element of `itr`.
349340
341+
The return type is `Int` for signed integers of less than system word size, and
342+
`UInt` for unsigned integers of less than system word size. For all other
343+
arguments, a common return type is found to which all arguments are promoted.
344+
350345
```jldoctest
351346
julia> sum(abs2, [2; 3; 4])
352347
29
353348
```
349+
350+
Note the important difference between `sum(A)` and `reduce(+, A)` for arrays
351+
with small integer eltype:
352+
353+
```jldoctest
354+
julia> sum(Int8[100, 28])
355+
128
356+
357+
julia> reduce(+, Int8[100, 28])
358+
-128
359+
```
360+
361+
In the former case, the integers are widened to system word size and therefore
362+
the result is 128. In the latter case, no such widening happens and integer
363+
overflow results in -128.
354364
"""
355-
sum(f::Callable, a) = mapreduce(f, +, a)
365+
sum(f::Callable, a) = mapreduce(promote_sys_size f, +, a)
356366

357367
"""
358368
sum(itr)
359369
360370
Returns the sum of all elements in a collection.
361371
372+
The return type is `Int` for signed integers of less than system word size, and
373+
`UInt` for unsigned integers of less than system word size. For all other
374+
arguments, a common return type is found to which all arguments are promoted.
375+
362376
```jldoctest
363377
julia> sum(1:20)
364378
210
365379
```
366380
"""
367-
sum(a) = mapreduce(identity, +, a)
381+
sum(a) = mapreduce(promote_sys_size, +, a)
368382
sum(a::AbstractArray{Bool}) = count(a)
369383

370384

@@ -379,7 +393,7 @@ summation algorithm for additional accuracy.
379393
"""
380394
function sum_kbn(A)
381395
T = _default_eltype(typeof(A))
382-
c = r_promote(+, zero(T)::T)
396+
c = promote_sys_size(zero(T)::T)
383397
i = start(A)
384398
if done(A, i)
385399
return c
@@ -405,24 +419,32 @@ end
405419
406420
Returns the product of `f` applied to each element of `itr`.
407421
422+
The return type is `Int` for signed integers of less than system word size, and
423+
`UInt` for unsigned integers of less than system word size. For all other
424+
arguments, a common return type is found to which all arguments are promoted.
425+
408426
```jldoctest
409427
julia> prod(abs2, [2; 3; 4])
410428
576
411429
```
412430
"""
413-
prod(f::Callable, a) = mapreduce(f, *, a)
431+
prod(f::Callable, a) = mapreduce(promote_sys_size f, *, a)
414432

415433
"""
416434
prod(itr)
417435
418436
Returns the product of all elements of a collection.
419437
438+
The return type is `Int` for signed integers of less than system word size, and
439+
`UInt` for unsigned integers of less than system word size. For all other
440+
arguments, a common return type is found to which all arguments are promoted.
441+
420442
```jldoctest
421443
julia> prod(1:20)
422444
2432902008176640000
423445
```
424446
"""
425-
prod(a) = mapreduce(identity, *, a)
447+
prod(a) = mapreduce(promote_sys_size, *, a)
426448

427449
## maximum & minimum
428450

base/reducedim.jl

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -137,19 +137,22 @@ reducedim_init(f, op::typeof(|), A::AbstractArray, region) = reducedim_initarray
137137

138138
# specialize to make initialization more efficient for common cases
139139

140-
for (IT, RT) in ((CommonReduceResult, :(eltype(A))), (SmallSigned, :Int), (SmallUnsigned, :UInt))
141-
T = Union{[AbstractArray{t} for t in uniontypes(IT)]..., [AbstractArray{Complex{t}} for t in uniontypes(IT)]...}
142-
@eval begin
143-
reducedim_init(f::typeof(identity), op::typeof(+), A::$T, region) =
144-
reducedim_initarray(A, region, zero($RT))
145-
reducedim_init(f::typeof(identity), op::typeof(*), A::$T, region) =
146-
reducedim_initarray(A, region, one($RT))
147-
reducedim_init(f::Union{typeof(abs),typeof(abs2)}, op::typeof(+), A::$T, region) =
148-
reducedim_initarray(A, region, real(zero($RT)))
149-
reducedim_init(f::Union{typeof(abs),typeof(abs2)}, op::typeof(*), A::$T, region) =
150-
reducedim_initarray(A, region, real(one($RT)))
151-
end
140+
let
141+
BitIntFloat = Union{BitInteger, Math.IEEEFloat}
142+
T = Union{
143+
[AbstractArray{t} for t in uniontypes(BitIntFloat)]...,
144+
[AbstractArray{Complex{t}} for t in uniontypes(BitIntFloat)]...}
145+
146+
global reducedim_init(f::typeof(identity), op::typeof(+), A::T, region) =
147+
reducedim_initarray(A, region, zero(eltype(A)))
148+
global reducedim_init(f::typeof(identity), op::typeof(*), A::T, region) =
149+
reducedim_initarray(A, region, one(eltype(A)))
150+
global reducedim_init(f::Union{typeof(abs),typeof(abs2)}, op::typeof(+), A::T, region) =
151+
reducedim_initarray(A, region, real(zero(eltype(A))))
152+
global reducedim_init(f::Union{typeof(abs),typeof(abs2)}, op::typeof(*), A::T, region) =
153+
reducedim_initarray(A, region, real(one(eltype(A))))
152154
end
155+
153156
reducedim_init(f::Union{typeof(identity),typeof(abs),typeof(abs2)}, op::typeof(+), A::AbstractArray{Bool}, region) =
154157
reducedim_initarray(A, region, 0)
155158

@@ -610,14 +613,21 @@ any!(r, A)
610613
for (fname, op) in [(:sum, :+), (:prod, :*),
611614
(:maximum, :scalarmax), (:minimum, :scalarmin),
612615
(:all, :&), (:any, :|)]
616+
function compose_promote_sys_size(x)
617+
if fname in [:sum, :prod]
618+
:(promote_sys_size $x)
619+
else
620+
x
621+
end
622+
end
613623
fname! = Symbol(fname, '!')
614624
@eval begin
615625
$(fname!)(f::Function, r::AbstractArray, A::AbstractArray; init::Bool=true) =
616626
mapreducedim!(f, $(op), initarray!(r, $(op), init, A), A)
617627
$(fname!)(r::AbstractArray, A::AbstractArray; init::Bool=true) = $(fname!)(identity, r, A; init=init)
618628

619629
$(fname)(f::Function, A::AbstractArray, region) =
620-
mapreducedim(f, $(op), A, region)
630+
mapreducedim($(compose_promote_sys_size(:f)), $(op), A, region)
621631
$(fname)(A::AbstractArray, region) = $(fname)(identity, A, region)
622632
end
623633
end

base/sparse/sparsematrix.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1660,7 +1660,7 @@ function Base._mapreduce(f, op, ::Base.IndexCartesian, A::SparseMatrixCSC{T}) wh
16601660
n = length(A)
16611661
if z == 0
16621662
if n == 0
1663-
Base.mr_empty(f, op, T)
1663+
Base.mapreduce_empty(f, op, T)
16641664
else
16651665
_mapreducezeros(f, op, T, n-z-1, f(zero(T)))
16661666
end

base/tuple.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,9 +308,13 @@ reverse(t::Tuple) = revargs(t...)
308308

309309
# TODO: these definitions cannot yet be combined, since +(x...)
310310
# where x might be any tuple matches too many methods.
311+
# TODO: this is inconsistent with the regular sum in cases where the arguments
312+
# require size promotion to system size.
311313
sum(x::Tuple{Any, Vararg{Any}}) = +(x...)
312314

313315
# NOTE: should remove, but often used on array sizes
316+
# TODO: this is inconsistent with the regular prod in cases where the arguments
317+
# require size promotion to system size.
314318
prod(x::Tuple{}) = 1
315319
prod(x::Tuple{Any, Vararg{Any}}) = *(x...)
316320

0 commit comments

Comments
 (0)