Repository navigation
Description
Problem
A fairly common operation on vectors is the outer product (
outer :: (Elt a, Elt b, Elt c)
=> (Exp a -> Exp b -> Exp c)
-> Acc (Vector a)
-> Acc (Vector b)
-> Acc (Matrix c)
outer f xs ys =
let xs' = replicate (Z_ ::. All_ ::. length ys) xs
ys' = replicate (Z_ ::. length xs ::. All_) ys
in zipWith f xs' ys'However, you need to write a separate version for each combination of array ranks you want to use this operation on, which is far from ideal.
Potential solutions
If we do want to add this, I see 3 options:
Manually written variations for low-rank arrays
This is similar to stencils are done currently. Alternatively, we could use Template Haskell to do the work for us.
This is the simplest, but not particularly extensible.
Append shapes using a type family
This way, we only need to write a single function, which will support arrays of any rank. It is also the closest to the mathematical definition of the outer product on tensors. It might look a bit like this:
type family xs ++ ys where
xs ++ Z = xs
xs ++ (ys :. y) = (xs ++ ys) :. y
outer :: (Shape sh, Shape sh', Elt a, Elt b, Elt c)
=> (Exp a -> Exp b -> Exp c)
-> Acc (Array sh a)
-> Acc (Array sh' b)
-> Acc (Array (sh ++ sh') c) I am not entirely sure if this approach will play nice with type classes. In particular, the constraint solver may not be able to infer (Shape sh, Shape sh') => Shape (sh ++ sh'). That would mean instead putting the proof obligation on the user, especially when writing rank-polymorphic functions.
I have used this method myself in a more general setting (which supports indexing using non-integer keys, in contrast to Accelerate), where this issue exists. However, supporting only shapes with integer components, as is currently the case in Accelerate, might simplify it enough.
A type-level description of the operation
This would follow a pattern similar to the way slice and replicate work. The user would supply a type that is an instance of a type class, and an associated type then describes the result type. This would allow describing to perform the outer product over a subset of the dimensions, zipping over the others.
I am not sure about the concrete implementation of this though, nor if it will entirely avoid the issues of the previous idea.
Conclusion
Is it desirable to have this functionality in the Accelerate standard library? If so, we should discuss the design. There may of course be other solutions than the ones I mentioned here.
Either way, if we decide we want this functionality in Accelerate, I would be willing to work on adding it.
Activity