ANN: Transducers.jl, efficient and composable algorithms for map- and reduce-like operations

Here is a quote from the README:

Transducers.jl provides composable algorithms on sequence of inputs.
They are called transducers, first introduced in Clojure language
by Rich Hickey.

Using transducers is quite straightforward, especially if you already
know similar concepts in iterator libraries:

using Transducers
xf = Partition(7) |> Filter(x -> prod(x) % 11 == 0) |> Cat() |> Scan(+)
mapfoldl(xf, +, 1:40)

However, the formalization of the transducers is quite different from
iterators and resulting in a better performance for complex
compositions.

See more in the documentation.

Installation

]add https://github.com/tkf/Transducers.jl

There are more examples in the documentation (see also reference manual). I also discussed difference to iterators in the documentation.

Some (technical) highlights:

Implementing transducers in a Julia-friendly way was an interesting holiday project. It even makes me wonder why itā€™s not as main stream as iterators (outside Clojure world?). I know there is a C++ library which is actually where I get the idea of type-stability consideration. Anyway, if you have any thoughts on this, Iā€™d like to hear.

Wish you a happy new year!

51 Likes

This is very cool and really impressive for a ā€œholiday projectā€! Iā€™ve been meaning to spend some time looking at clojureā€™s transducers ever since Rich Hickey first introduced them and not gotten around to it. Now I guess thereā€™s no excuse since thereā€™s a Julia implementation :grin:

2 Likes

Thanks! Itā€™s good to know that transducer was on your radar :slight_smile:

Wow, this is really cool! It feels very Julian.

2 Likes

Sorry to ask for numbers, but Iā€™m curious as to the advantages of Transducers, any bench-marks showing how much better this is than iterators?

To me the selling point of Transducers are composability and generality. I would not say that they are ā€œfasterā€ then iterators. They are not faster than a hand tuned for loop. But they avoid materializing intermediate results and thus they are faster then high level iterator code. Here is the example from @tkfā€™s SIMD test:

Edit: This snipped is misleading. I benchmark apples against oranges. See @tkfā€™s comment below.

julia> using Transducers, BenchmarkTools

julia> xs = randn(1000); ys = similar(xs);

julia> xf = Filter(x -> -0.5 < x < 0.5) |> Map(x -> 2x)
Filter(Main.Ī»ā“) |>
    Map(Main.Ī»ā“)

julia> @benchmark map!(xf,ys,xs)
BenchmarkTools.Trial: 
  memory estimate:  0 bytes
  allocs estimate:  0
  --------------
  minimum time:     953.750 ns (0.00% GC)
  median time:      965.950 ns (0.00% GC)
  mean time:        977.053 ns (0.00% GC)
  maximum time:     1.890 Ī¼s (0.00% GC)
  --------------
  samples:          10000
  evals/sample:     20

julia> @benchmark map!(x -> 2x, ys, filter(x -> -0.5 < x < 0.5, xs))
BenchmarkTools.Trial: 
  memory estimate:  8.39 KiB
  allocs estimate:  9
  --------------
  minimum time:     4.883 Ī¼s (0.00% GC)
  median time:      5.311 Ī¼s (0.00% GC)
  mean time:        7.015 Ī¼s (16.79% GC)
  maximum time:     6.901 ms (99.78% GC)
  --------------
  samples:          10000
  evals/sample:     6
1 Like

Good point. Here is an example that is very ā€œhostileā€ to iterator:

julia> xs = 1:2^15
1:32768

julia> @btime foldl(+, Iterators.flatten(1:x for x in xs))
  200.448 ms (10 allocations: 352 bytes)
5864598896640

julia> @btime mapfoldl(Map(x -> 1:x) |> Cat(), +, xs)
  45.532 Ī¼s (18 allocations: 880 bytes)
5864598896640

Piggybacking on Skipnothing is missing, here is a more reasonable case for comparison:

julia> xs = [abs(x) > 1 ? nothing : x for x in randn(2^20)];

julia> @btime foldl(+, Iterators.filter(!isnothing, xs); init=0.0)
  4.084 ms (4 allocations: 80 bytes)
779.0559461186579

julia> @btime mapfoldl(Filter(!isnothing), +, xs, init=0.0)
  2.913 ms (5 allocations: 80 bytes)
779.0559461186579
4 Likes

Thanks for bringing up that example. Let me note that the semantics of map! for transducers and iterators are bit different. Transducer Filter skips the destination elements as well while the iterator version ā€œcompressā€ all the output in a contiguous chunk. A function that does a similar thing in Transducers.jl is copy! (we may need copyto! which could be more efficient).

1 Like

@tkf cool! Do you have an explanation, why the skip nothing example if faster using Transducers?

I need to look at IR to be sure but some guesses:

  • foldl in Base actually does a lot more than what Iā€™ve implemented in Transducers.jl, like detecting correct zero even when eltype(xs) is Union{Nothing, Float64}. This may give it some overhead to the iterator version (although I tried to be slightly fair by passing an init).

  • Maybe I put too many @inlines :slight_smile:

  • But it could also be a real effect; as I wrote in difference to iterators, the code ā€œgeneratedā€ by the iterator is a nested while loop with conditional break. Maybe Julia compiler can optimize structured for loop more easily? Although this means in the future there would probably be no difference in performance.

1 Like

I find something very bizarre: Transducer is actually faster than ā€œequivalentā€ manual loop. I took sum_nonmissing from First-Class Statistical Missing Values Support in Julia 0.7 which noted:

replacing x !== missing by ismissing(x) in sum_nonmissing currently leads to a large performance drop

Indeed, sum_isnotmissing below is much slower than sum_nonmissing (as of 1.2.0-DEV.63).

Keno explained in the issue comment linked from the blog this is because:

=== is special in inference and inference happens before inlining, so even if theyā€™re the same after inlining, Inference doesnā€™t know that.

However, using Filter(!ismissing) is just as fast as using x !== missing in the manual loop. If I look at @code_warntype output, I can see that output type is correctly inferred.

Iā€™m not entirely sure whatā€™s going on, but Iā€™m guessing that transducers are compiler-friendly because they aggressively put function boundaries which may help inference.

using Transducers
using BenchmarkTools

# Taken from: https://julialang.org/blog/2018/06/missing
function sum_nonmissing(X::AbstractArray)
    s = zero(eltype(X))
    @inbounds @simd for x in X
        if x !== missing
            s += x
        end
    end
    s
end

function sum_isnotmissing(X::AbstractArray)
    s = zero(eltype(X))
    @inbounds @simd for x in X
        if !ismissing(x)
            s += x
        end
    end
    s
end

# Benchmark:

n = 2^10
xs = [abs(x) > 0.5 ? missing : x for x in randn(n)]

@btime sum_isnotmissing($xs)
# 2.908 Ī¼s (0 allocations: 0 bytes)
@btime sum_nonmissing($xs)
# 772.896 ns (0 allocations: 0 bytes)
@btime mapfoldl($(Filter(!ismissing)), +, $xs, init=0.0)
# 784.798 ns (0 allocations: 0 bytes)
VERSION
# v"1.2.0-DEV.63" (similar result with 1.0)
6 Likes

OK this is very cool, @tkf!

Just one question - it seems that Partition, Filter, Cat, Scan, etc behave like Functions - why is that they are piped into each other via |> (evaluate function with data operator) instead of composed with āˆ˜ (function followed by another function operator)? Is it just to get the order of operations looking correct? (Iā€™ve often wanted to have something like āˆ˜ but writing the functions in the other order).

1 Like

Thanks for the comment!

First, just to clarify, I defined |>(::Transducer, ::Transducer) directly without making Transducer a callable (see below for why).

But this is a good question! And you already found the answer :slight_smile:

Yes, but just in case you havenā€™t gotten to the full explanation yet, it probably requires more words. A confusing (and interesting) part of transducers is that the flow of application is ā€œflipped twiceā€ (See also Glossary in my docs or the explanation in Clojure homepage).

A transducer is a function that maps a reducing function to a reducing function. A reducing function is the op argument you pass to normal foldl (e.g., + or *; a function of the form (Y, X) -> Y in general where Y is the ā€œaccumulatorā€ and X is the ā€œinputā€). Since transducer maps a function to a function, it is natural to define the composition by āˆ˜ (and actually thatā€™s how it works in Clojure). I could have used (and actually was using) Filter(isodd) āˆ˜ Map(double) instead of Filter(isodd) |> Map(double). Note that, as evident when āˆ˜ is used, the output (= a function) of the first transducer Filter(isodd) gets the input first. Maybe it becomes clear if you see how the application of this transducer to a reducing function (say) + works:

double(x) = 2x

# In hypothetical notation:
(Filter(isodd) |> Map(double))(+)(y, x)
== (Filter(isodd) āˆ˜ Map(double))(+)(y, x)  # `|>` actually means `āˆ˜` for transducers
== (Filter(isodd)(Map(double)(+)))(y, x)   # expand `āˆ˜`
== if isodd(x)                             # expand `Filter`
     Map(double)(+)(y, x)
   else
     y
   end
== if isodd(x)
     (+)(y, double(x))                     # expand `Map`
   else
     y
   end

As you can see, input x is Filterā€™ed first and then Mapā€™ed.

I thought it would be ā€œdoublyā€ confusing and it could be easier to start using transducers if I use some ā€œarrow likeā€ symbol that points in the direction that the data flows.

Another reason is to make the API accessible in ASCII (although I totally like coding in Unicode personally).

But at the same time, Iā€™m not entirely sure that this is the right interface, as it changes the semantics of the operator |> for this particular type. Is it something frowned upon in Julia API design? It seems there are not much other examples that ā€œviolateā€ operator semantics.

FYI, I recently learned:

Some authors compose in the opposite order, writing fg or f āˆ˜ g for g āˆ˜ f. Computer scientists using category theory very commonly write f ; g for g āˆ˜ f ā€” Category theory - Wikipedia

(although sadly we canā€™t use it in Julia)

5 Likes

Transducers.jl is now registered :tada:. You can install it via ]add Transducers.

I also added a tutorial which shows how to use transducers while implementing various missing value handling.

16 Likes

The package documentation is really fantastic. Thanks for putting the work into it.

6 Likes

I should thank Documenter and Literate devs since those tools make writing docs super fun!

7 Likes

I coded up something similar - iterator processing functions that didnā€™t have the source bound in. I used the Julia nothing value to represent out-of-input and no-more-output states. I think this is closer to the Julia iteration protocol. This seems simpler than the early termination and completing process mentioned in the Rich Hickey video.

Interesting. Is it something like a framework for higher-order functions composing a function that maps an iterator to an iterator?

If you use iterator protocol or something similar, I suppose thatā€™s still ā€œpullā€-based framework (i.e., the user of the iterator processing functions is the one driving the loop)? If so, my guess is that it has the same pros and cons of the iterators. For example, can it have the performance equivalent to the manual loops for flatten/Cat (iterating over vector-of-vector), zip, product, and BitArray? With transducers, you can do so simply because you can write foldl which can have for loops using whatever the best looping strategy is. Of course, the compiler may be able to re-construct such loops from Base.iterate. But that sounds hard. (But I donā€™t know much about compilers.)

I donā€™t know how does it work in your iterator processing functions, but I think termination for both iterators and transducers are cumbersome enough that youā€™d write a macro for it anyway (there is IterTools.@ifsomething). If you use macros, I donā€™t think there is much difference. But Iā€™d say writing foldl is much easier than writing iterate. See this comparison: https://tkf.github.io/Transducers.jl/dev/examples/reducibles/

Another thought: I think the best ā€œfeatureā€ of transducers for performance-oriented language like Julia is actually not transducers themselves but rather the foldl implementations specialized for container types. I guess thatā€™s not news since Julia Base has very efficient foldl/mapfoldl. However, foldl (or mapfoldl) itself is not really composable ā€” thatā€™s where transducers come in. Transducers are composable ā€œpre-processorsā€ of the ā€œreducing functionā€ op you passed to foldl. I think one of the great observations by Rich Hickey is that this set of pre-processors can be as powerful as the usual iterator tool chain. But, as @arghhhh pointed out, it requires a generalization of foldl for supporting early termination and completion. I think it is worth doing so since it can be compiled away if you donā€™t use it.

6 Likes

First, thanks for writing this package! I read through your code, watched the video, and read through your code again and it is starting to make sense, mostly because you organized and documented everything so nicely.

I have some specific questions:

  1. My understanding is that the current implementation of Base.collect here uses type inference to infer the container type. Do you think it could use some strategy that has the same container type semantics as the default method, which widens on demand? Or does that not compose well with transducers?

  2. Similarly, did you run into the type explosion problem mentioned in the video (edit: corrected video link) in the Julia implementation?

  3. How should one go about implementing a custom container type that can accept output from transducer-mapped collections, what are the necessary primitives? Especially if a widening-on-demand strategy like collect is desired.

4 Likes