art with code

2008-09-09

"Shared Memory" Parallelism

One thing that amazes me in discussions extolling the performance benefit of shared memory over message passing is that no one has apparently looked at the hardware in use. Because hardware has no shared memory. None. Nada. Zilch.

How a computer works in a nutshell

Accessing memory:

CPU: Hey, I'd like to read eight bytes from memory position 0x8008 to register %RAX.
Cache manager: Sure thing, wait a couple cycles. Hey L1, have you got the cache line with 0x8008?
L1: Sorry! (2 cycles if hit)
Cache manager: Hm, how about you L2? Got 0x8008?
L2: Oh, uh, sec, lemme see... nope. (9 cycles if hit)
Cache manager: Argh, OK, shit happens. DRAM, gimme 0x8008.
DRAM: Durr, 0x8008, yeah, 0x8008, yeah...
Cache manager: DRAM?
DRAM: ...
Cache manager: DRAM! 0x8008!
DRAM: Huh? Oh. Here you go. (200 cycles if hit, a couple dozen million if read from disk)

Shared memory in a cache coherent SMP machine:

CPU A: Read 0x8000!
L1: Here!
CPU B: Write %RAX to 0x8001!
Cache manager: Oh nuts. Hey CPU A, CPU B just wrote to a cache line you have, here's the new version.
CPU A: Ghh, OK. Write 0x8000!
Cache manager: CPU B! CPU A just wrote in 0x8000, you need a new version of the cache line!
CPU B: Damn it A, stop writing on my cache line!
CPU A: Your cache line? I'm so sorry, I didn't see your name on it!
...
Significant performance loss later:
Cache manager: The person who wrote this algorithm must be a some kind of retard.

Does that look like a shared memory architecture to you? No way. It's a message passing architecture, communicating in 64-byte cache lines. Treating it as shared memory will lead to performance problems.

Theoretically, a message passing system will yield the highest performance for present-day hardware. That is, if a compiler compiles the message passing in terms of CPUs talking to memory via cache lines. Anyone know whether such a mythical beast exists?

Related reading: What every programmer should know about memory, part 2: CPU caches by Ulrich Drepper.

2008-09-08

Non-copying forked workers using Bigarrays

Prelude.ml: Wrote some utils for Bigarrays and a parallel Bigarray init pbainit that uses mmapped /dev/zero as shared memory (thanks to mfp for the pointer) to allow the worker processes to write into a shared array, eliminating result copying overhead.

Here's a small program that averages two string arrays:

open Prelude

let () =
let sz = parseInt Sys.argv.(1) in
let s1 = String.create sz in
let s2 = String.create sz in
let ba = pbainit Bigarray.char
(fun i -> char ((ord (suget s1 i) + ord (suget s2 i)) / 2) )
sz in
puts (showInt (balen ba))

I tested it with sz=1G, which creates two 1GB strings and a third 1GB string/array created by averaging the two strings together. I have 4GB of RAM, so any copying will easily cause swapping to disk. I timed versions using sequential and parallel Bigarray and String inits:
  • bainit: 24.5s (sequential Bigarray init)

  • pbainit: 16.1s (parallel Bigarray init)

  • sinit: 9.5s (sequential String init)

  • psinit: started swapping, killed it after 80s (parallel String init)

As you can see from the above, while mmapped Bigarrays aren't faster than native strings, they can share results without copying. To tip the balance towards Bigarrays, let's make the compute kernel do more work:

open Prelude

let () =
let sz = parseInt Sys.argv.(1) in
let s1 = String.create sz in
let s2 = String.create sz in
let ba = pbainit Bigarray.char
begin fun i -> (* average of 11-wide averages *)
let a = saverageSlice (max 0 (i-5)) (min (sz-1) (i+5)) s1 in
let b = saverageSlice (max 0 (i-5)) (min (sz-1) (i+5)) s2 in
char ((a+b) / 2)
end
sz in
ignore ba

And the results with 1G strings:
  • bainit: 213s

  • pbainit: 111s

  • sinit: 188s

  • psinit: Killed after 240s as it had pushed swapfile use to 1G.

Now we actually see a 70% speedup with using parallel Bigarray init compared to sequential string init.

Conclusions: Bigarrays are helpful when you need to process large in-memory structures in parallel, provided that you do enough computation to mask the parallelisation overhead. Bigarrays are also good for communicating with libraries written in C or FORTRAN.

2008-09-06

Constant-space parallel combinators in OCaml

Updated prelude.ml with a couple new parallel iterators: pfoldl, pfoldlSeqN and piterSeqN. The pfoldl function is a two-phase foldl, it splits the list into process_count pieces, foldls each and foldls the results. To convey that, it takes two functions : the normal fold function and the reduce function.

The *SeqN functions are partially sequential, they synchronize after every N elements. To use the Mandelbrot example, if you're rendering a 64000 x 64000 image, it would take more than 4 gigs of RAM to do it with pbinit. For a sequential renderer that is no problem, since you can output each byte after it's computed. A parallel renderer can't really use that strategy, since the pixels are computed in parallel and outputting them as they come would lead to an unsorted image.


Sequential output:
# iter (fun i -> sleep (3-i); puts (showInt i)) (0--3);;
0
1
2
3
- : unit = ()

Parallel output:
# piter ~process_count:4 (fun i -> sleep (3-i); puts (showInt i)) (0--3);;
3
2
1
0
- : unit = ()


What we can do is turn the problem into a sequential iteration of internally parallel blocks. E.g. render a 1MB block of pixels in parallel, print it out before doing the next block. This way memory use is limited to block size and we still get a decent parallelization speedup.


Partially sequential iteration:
# iter (fun l -> iter puts @@ pmap (fun i -> sleep (3-i); showInt i) l) (groupsOf 2 (0--3));;
0
1
2
3

Or using piterSeqN:
# piterSeqN 2 puts (fun i -> sleep (3-i); showInt i) (0--3);;
0
1
2
3


Here's a larger example, using the already familiar Mandelbrot renderer. Starting with a sequential version:

open Prelude

let niter = 64
let limit = 4.0

let mandelbrot z x y =
let cr = 2.0 *. float x /. z -. 1.5 in
let ci = 2.0 *. float y /. z -. 1.0 in
let rec aux i zr zi = if i >= niter then 0 else
let nzr = zr *. zr -. zi *. zi +. cr
and nzi = 2.0 *. zr *. zi +. ci in
if nzr *. nzr +. nzi *. nzi > limit
then int (ceil (255. *. (float (niter-i) /. float niter)))
else aux (i+1) nzr nzi in
aux 0 0.0 0.0


(*vvv Interesting part starts here vvv*)

let draw_fractal z w h =
for y = 0 to h-1 do
for x = 0 to w-1 do
output_byte stdout (mandelbrot z x y)
done
done

let print_fractal w h =
puts (sprintf "P5 %i %i 255" w h);
draw_fractal (float (min w h)) w h

let () = print_fractal (parseInt Sys.argv.(1)) (parseInt Sys.argv.(1))


To make it parallel, we make draw_fractal create all scanlines and print them out:


let draw_scanline z w y =
binit (fun x -> mandelbrot z x y) w

let draw_fractal z w h =
let scanlines = pmap (fun y -> draw_scanline z w y) (0--(h-1)) in
iter putStr scanlines


And to make it constant-space parallel (well, O(width*256)), let's process in blocks of 256 scanlines:


let draw_fractal z w h =
piterSeqN 256 putStr (fun y -> draw_scanline z w y) (0--(h-1))


Done! Let's put it all together one more time:


open Prelude

let niter = 64
let limit = 4.0

let mandelbrot z x y =
let cr = 2.0 *. float x /. z -. 1.5 in
let ci = 2.0 *. float y /. z -. 1.0 in
let rec aux i zr zi = if i >= niter then 0 else
let nzr = zr *. zr -. zi *. zi +. cr
and nzi = 2.0 *. zr *. zi +. ci in
if nzr *. nzr +. nzi *. nzi > limit
then int (ceil (255. *. (float (niter-i) /. float niter)))
else aux (i+1) nzr nzi in
aux 0 0.0 0.0

let draw_scanline z w y =
binit (fun x -> mandelbrot z x y) w

let draw_fractal z w h =
piterSeqN 256 putStr (fun y -> draw_scanline z w y) (0--(h-1))

let print_fractal w h =
puts (sprintf "P5 %i %i 255" w h);
draw_fractal (float (min w h)) w h

let () = print_fractal (parseInt Sys.argv.(1)) (parseInt Sys.argv.(1))


We replaced five lines of sequential code with three lines of parallel code and got a version that scales nearly linearly with the number of cores. Not too bad, eh?

2008-09-04

Haskell on parallel hardware

Haskell for multicores - links to different ways to do parallel programming in Haskell.

GpuGen: Bringing the Power of GPUs into the Haskell World - they compile map, scan, fold, filter, zipWith, permute, bpermute, etc. to CUDA and run it on the GPU. 10x+ performance on large matrix multiplication.

2008-09-02

Almost Burning Ship

Have an almost Burning Ship fractal.




open Prelude

let niter = 32
let limit = 4.0

let burning_ship z x y =
let cr = 2.0 *. float x /. z -. 2.1 in
let ci = 2.0 *. float y /. z -. 1.8 in
let rec aux i zr zi = if i >= niter then 0 else
let nzr = absf (zr *. zr -. zi *. zi +. cr)
and nzi = 2.0 *. absf (zr *. zi +. ci) in
if nzr *. nzr +. nzi *. nzi > limit then niter-i
else aux (i+1) nzr nzi in
aux 0 0.0 0.0

let pbinit2D f w h = pbinit (fun i -> let y,x = quot_rem i w in f x y) (w*h)
let draw_fractal z w h = pbinit2D (burning_ship (float z *. 0.8)) w h
let pgm_fractal w h = sprintf "P5 %i %i %i\n" w h niter ^ draw_fractal (min w h) w h

let () = print_string @@ pgm_fractal (parseInt Sys.argv.(1)) (parseInt Sys.argv.(2))

2008-09-01

Adaptive blur filter Mandelbrot

To finish off today's Mandelbrot madness, here's a version that does a ghetto 2D box filter with kernel size controlled by the second image (i.e. blur more where second image is white, don't blur where it's black.) Using a second core gives an 80% speed boost.



open Prelude

let niter = 255
let limit = 4.0

let mandelbrot x y w h =
let cr = 2.0 *. x /. w -. 1.5 in
let ci = 2.0 *. y /. h -. 1.0 in
let rec aux i zr zi = if i >= niter then 0 else
let nzr = zr *. zr -. zi *. zi +. cr
and nzi = 2.0 *. zr *. zi +. ci in
if nzr *. nzr +. nzi *. nzi > limit then 255-i
else aux (i+1) nzr nzi in
aux 0 0.0 0.0

let draw_fractal xoff yoff w h =
pbinit (fun i ->
let y, x = quot_rem i w in
mandelbrot (float (xoff+x)) (float (yoff+y)) (float w) (float h)
) (w*h)

let blend a b w h =
let c = pbinit (fun i ->
let y, x = quot_rem i w in
let r = ord (suget b i) / 32 in
let x1 = max (x-r) 0
and x2 = min (x+r) (w-1) in
saverage (ssub (y*w+x1) (x2-x1+1) a)
) (slen a) in
pbinit (fun i ->
let y, x = quot_rem i w in
let r = ord (suget b i) / 32 in
let y1 = max (y-r) 0
and y2 = min (y+r) (h-1) in
saverage (ssubStride w (y1*w+x) (y2-y1+1) c)
) (slen a)

let square_fractal d =
let frac1 = draw_fractal 0 0 d d in
let frac2 = draw_fractal (d/4) (-d/4) d d in
let header = sprintf "P5 %i %i 255\n" d d in
header ^ (blend frac1 frac2 d d)

let () =
let img = square_fractal (parseInt Sys.argv.(1)) in
output_string stdout img

Prelude.ml - more multicore mandelbrot


Continuing from yesterday, landed a bunch of new parallel combinators in prelude.ml along with a small smattering of convenience functions for working with arrays and strings.

The following version of the parallel mandelbrot drawer demonstrates byte strings:

open Prelude

let mandelbrot w h x y =
let cr = 2.0 *. float x /. float w -. 1.0 in
let ci = 2.0 *. float y /. float h -. 1.5 in
let rec aux i zr zi = if i >= niter then 0 else
let nzr = zr *. zr -. zi *. zi +. cr
and nzi = 2.0 *. zr *. zi +. ci in
if nzr *. nzr +. nzi *. nzi > limit then 255-i
else aux (i+1) nzr nzi in
aux 0 0.0 0.0

(* pbinit f = psinit (fun i -> char (f i)) *)
let draw_fractal xoff yoff w h =
pbinit (fun i ->
let y,x = quot_rem i w in
mandelbrot w h (x+xoff) (y+yoff)
) (w*h)

(* blend the two images by averaging the values at each pixel *)
(* pbZipWith f = psZipWith (fun x y -> char (f (ord x) (ord y))) *)
let blend a b = pbZipWith average2

let blended_fractal d =
let a = draw_fractal 0 0 d d in
let b = draw_fractal (d/4) (-d/4) d d in
blend a b

let square_fractal d =
let header = sprintf "P5 %i %i 255\n" d d in
header ^ (blended_fractal d)

And we can further refactor draw_fractal into the following:

let pbinit2D f w h = pbinit (fun i -> let y,x = quot_rem i w in f x y) (w*h)
let draw_fractal w h = pbinit2D (mandelbrot w h) w h

We could also write the drawer in terms of arrays instead of strings:

let painit2D f w h = painit (fun i -> let y,x = quot_rem i w in f x y) (w*h)
let draw_fractal w h = painit2D (mandelbrot w h) w h
let blend a b = paZipWith (chr @.. average2)
let blended_fractal d =
let a = draw_fractal 0 0 d d in
let b = draw_fractal (d/4) (-d/4) d d in
implodeArray (blend a b)

But that's not a very good idea since ints are 4-8 times wider than chars, further lowering our ratio of computation to memory accesses.

One thing I found out in writing the blend was that it doesn't really get any noticeable speed-up from using the parallel zip vs. normal zip. I suppose it's because the copying overhead is so large compared to the very trivial arithmetic: if the copy takes 4 cycles per byte and the iteration takes 3 cycles per byte, doing it with a single thread would take 3 cycles per byte, while doing it with two threads would take 1.5+4= 5.5 cycles per byte (assuming linear speed boost in iteration.)

By comparison, the mandelbrot function is very multicore-happy since it's self-contained and does no memory reads. As all it does is run a few hundred cycles worth of math in the CPU registers for every byte that it writes to memory, it scales in a very linear fashion.

Blog Archive