修复和加速 API 相似性
Haskell repa 库用于在 CPU 上自动进行并行数组计算。加速库是 GPU 上的自动数据并行性。API 非常相似,具有相同的 N 维数组表示。fromRepa
甚至可以使用和toRepa
in在加速和 repa 数组之间切换Data.Array.Accelerate.IO
:
fromRepa :: (Shapes sh sh', Elt e) => Array A sh e -> Array sh' e
toRepa :: Shapes sh sh' => Array sh' e -> Array A sh e
有多个用于加速的后端,包括 LLVM、CUDA 和 FPGA(参见http://www.cse.unsw.edu.au/~keller/Papers/acc-cuda.pdf的图 2 )。我发现了一个用于加速的repa 后端,尽管该库似乎没有得到维护。鉴于repa 和Accelerator 编程模型相似,我希望有一种优雅的方式在它们之间切换,即编写一次的函数可以使用repa 的R.computeP 或Accel 的后端之一执行,例如使用CUDA运行函数。
两个非常相似的功能:南瓜上的 Repa 和 Accelerate
取一个简单的图像处理阈值函数。如果灰度像素值小于 50,则将其设置为 0,否则保留其值。这是它对南瓜的作用:


以下代码介绍了 repa 和加速实现:
module Main where
import qualified Data.Array.Repa as R
import qualified Data.Array.Repa.IO.BMP as R
import qualified Data.Array.Accelerate as A
import qualified Data.Array.Accelerate.IO as A
import qualified Data.Array.Accelerate.Interpreter as A
import Data.Word
-- Apply threshold over image using accelerate (interpreter)
thresholdAccelerate :: IO ()
thresholdAccelerate = do
img <- either (error . show) id `fmap` A.readImageFromBMP "pumpkin-in.bmp"
let newImg = A.run $ A.map evalPixel (A.use img)
A.writeImageToBMP "pumpkin-out.bmp" newImg
where
-- *** Exception: Prelude.Ord.compare applied to EDSL types
evalPixel :: A.Exp A.Word32 -> A.Exp A.Word32
evalPixel p = if p > 50 then p else 0
-- Apply threshold over image using repa
thresholdRepa :: IO ()
thresholdRepa = do
let arr :: IO (R.Array R.U R.DIM2 (Word8,Word8,Word8))
arr = either (error . show) id `fmap` R.readImageFromBMP "pumpkin-in.bmp"
img <- arr
newImg <- R.computeP (R.map applyAtPoint img)
R.writeImageToBMP "pumpkin-out.bmp" newImg
where
applyAtPoint :: (Word8,Word8,Word8) -> (Word8,Word8,Word8)
applyAtPoint (r,g,b) =
let [r',g',b'] = map applyThresholdOnPixel [r,g,b]
in (r',g',b')
applyThresholdOnPixel x = if x > 50 then x else 0
data BackendChoice = Repa | Accelerate
main :: IO ()
main = do
let userChoice = Repa -- pretend this command line flag
case userChoice of
Repa -> thresholdRepa
Accelerate -> thresholdAccelerate
问题:我可以只写一次吗?
thresholdAccelerate
和的实现thresholdRepa
非常相似。是否有一种优雅的方法可以编写一次数组处理函数,然后以编程方式在交换机中选择多核 CPU(repa)或 GPU(加速)?我可以考虑根据我想要 CPU 还是 GPU 来选择我的导入,即导入或者Data.Array.Accelerate.CUDA
执行Data.Array.Repa
以下类型的操作Acc a
:
run :: Arrays a => Acc a -> a
或者,使用类型类,例如大致如下:
main :: IO ()
main = do
let userChoice = Repa -- pretend this is a command line flag
action <- case userChoice of
Repa -> applyThreshold :: RepaBackend ()
Accelerate -> applyThreshold :: CudaBackend ()
action
或者是这样的情况,对于我希望为 CPU 和 GPU 表达的每个并行数组函数,我必须实现它两次——一次使用 repa 库,另一次使用加速库?