Thursday, February 17, 2011

binary by the numbers

New home

I've taken the liberty to fork the darcs repo of binary and put it on github. It contains both the latest released version as well as the new experimental continuation based Get monad a branch called cps.

git clone git://github.com/kolmodin/binary

Performance

It's interesting to run the benchmark of binary on different architectures and with different versions of GHC. Although there recently has been work within the community with fast writing (blaze-builder comes to mind) I've mostly been working on how to read things fast.

The classic binary implementation of the Get monad is a state monad while the new experimental version is continuation based, so fundamentally different. They also perform differently. To produce the numbers below I ran the benchmark suite of binary. It reads either Word8, Word16, Word32 or Word64 in a (hopefully) tight loop and then presents how fast it could do it. For example, see this graph over performance in a 32bit environment;

The nice news is that GHC 7.0.1 always performs better than GHC 6.12.3. Also the experimental cps branch (the wide green line) is faster than the classic master branch.

Things seems to be going well in 32bit land. Let's have a look in a 64bit environment;

This gives a different picture. GHC 7.0.1 still performs better than GHC 6.12.3, but we can also see that the cps branch can't keep up with the state monad based master branch (in contrast to when compiling for 32bits). Future work will include to figure out why, and how to fix it.

Lets have a look at how binary performs at writing too;

Benchmark Environment

The tests have been performed on a Sandy Bridge CPU using GHCs native backend. I wanted to try the LLVM backend too, but unfortunately LLVM crashes when compiling the benchmark executable.

Sunday, January 9, 2011

About binary

About a year ago I started hacking on a project to change the Get monad of the binary package. I've been working off and on since... :) The change will allow us to incrementally provide the Get monad with input, as well as allow backtracking and a more graceful error handling. The code was public, but got moved with the haskell.org infrastructure changes. It's now available again;
darcs get http://code.haskell.org/~kolmodin/code/binary/
Johan Tibell writes about the API update in his recent blog post. Developers familiar with attoparsec code will largely be familiar with the new binary Get monad too, as it's been a heavy influence. The type for the parse function would essentially be something like this:
data Result r =
    Fail ByteString [ByteString] -- an error msg and a trace
  | Partial (ByteString -> Result r) -- incremental input
  | Done r -- finished!
A few forks of binary tries to address this too, all in their own way. Currently I know of cereal and binary-strict.

Performance

When benchmarking cereal and the new binary package, cereal comes out on top, at the expense of not being able to consume the input in incremental chunks. I couldn't find the benchmark suit for binary-strict. The reason for cereal being faster, I think, is due to that its simpler code when having a simpler state, essentially only a single strict ByteString (the input). In binary (and attoparsec) it's a bit more complicated, due to the incremental input (in combination with supporting MonadPlus):
data S =
  S { input      :: !B.ByteString -- the current input chunk
    , next_input :: !B.ByteString -- saved input to be used when backtracking
    , read_all   :: !Bool -- have we requested all input available to parse?
    } deriving Show

newtype Get a =
  C { runCont :: forall r.
                 S ->
                 Failure   r ->
                 Success a r ->
                 Result    r }

type Failure   r = S -> [String] -> String -> Result r
type Success a r = S -> a -> Result r

bindG :: Get a -> (a -> Get b) -> Get b
bindG (C c) f = C $ \st0 kf ks -> c st0 kf (\st1 a -> runCont (f a) st1 kf ks)
Unfortunately, this results in bad performance. I'm guessing that's it's because it's reconstructing the state value (of type S), and the remaining ByteString input for each value consumed, thus a lot of allocations. So, as an experiment, I manually unpacked S;
-- No longer using S
{-
data S = S { input      :: !B.ByteString
           , next_input :: !B.ByteString
           , read_all   :: !Bool
           } deriving Show
-}

newtype Get a =
  C { runCont :: forall r.
                 -- these three were part of S, now they are separate arguments
                 B.ByteString -> -- 1
                 B.ByteString -> -- 2
                 Bool ->         -- 3
                 Failure   r ->
                 Success a r ->
                 Result    r }

type Failure   r = B.ByteString -> B.ByteString -> Bool -> [String] ->String -> Result r
type Success a r = B.ByteString -> B.ByteString -> Bool -> a -> Result r

bindG :: Get a -> (a -> Get b) -> Get b
bindG (C c) f = C $ \inp next eof kf ks ->
                             c inp next eof kf
                               (\inp' next' eof' a -> runCont (f a) inp' next' eof' kf ks)
With ghc-7, this yields a huge speed boost and reaches about half the speed of the old binary library (and ~30% faster than cereal). Unfortunately, I find the code is less readable and harder to maintain. Maybe it's worth it though. I got a hint to see ghc ticket #1349. Duncan Coutts summarizes the issue, this time about the Put monad. There are a lot of details and examples in those mails, suggesting an extension to GHC to control strictness in the arguments of higher order components. It'd allow us to write the prettier version, yet enjoying the nicer properties of the unpacked version. It's unlikely that we'll see the proposal implemented soon, though. It seems there are four options;
  • Go with the manually unpacked code
  • Drop support for backtracking
  • Drop support for incremental input
  • Find something even better, you're all invited :)

Saturday, May 10, 2008

HCAR Deadline

If you haven't followed the mailing lists lately, you might have missed that the HCAR deadline is today (10th May).
The Haskell Communities & Activities Report is a bi-annual overview of the state of Haskell as well as Haskell-related projects over the last, and possibly the upcoming 6 months. [..] If you are working on any project that is in some way related to Haskell, please write a short entry and submit it to the us. Even if the project is very small or unfinished or you think it is not important enough -- please reconsider and submit an entry anyway!
Get the full details here. I'm much looking forward to the next edition!

Sunday, January 20, 2008

The Beginning of a New Era

I still remember the event Jobs in Functional Programming, held here in Göteborg, Sweden, the 14th December last year. It was the first event of its kind, an event to attract hackers to employers, paying for you to hack in functional programming languages! Not only were 8 companies represented in some way, 6 of them had people there explaining why you should go to their company and not someone else's :) With over 100 people registered, and about as many as came, it was a joy. Professor John Hughes, well known for his work with Haskell, was the host for the evening. John ended the event with a speech, I got reminded of it by SPJ's mail. Congratulations, btw! :) They both conclude that Haskell has become much more popular, and that it has happened very fast. Five or ten years ago we would not have dreamed of having such an event as we did. Some students found it humorous when John spoke very enthusiastically about Haskell's new won popularity. But think of it this way, twenty years ago few companies would make a fuzz about FP at all. Today C#, one of the most popular languages out there from one of the (the?) biggest computer companies out there, has lots of ideas from FP. There is also F#: Microsoft's newest addition to the .NET family, a somewhat more evolved version of OCaml, adjusted to fit into the .NET world. It's not difficult to make the prediction that Haskell will get even more attention in the near future. The times are really changing. As Hughes said in his speech, this is the beginning of a new era.

Saturday, January 19, 2008

Wireless on a Thinkpad x61s

I've just configured wireless networking on my laptop, so I'd like to share a little checklist to speed up the process for others in the same situation. As you will see, it is that hard to get it going. It's as simple as setting the kernel modules, drivers, encryption and local settings. What took me the longest was actually to remember to allow my MAC address in the router... bummer :) This guide is specific to Gentoo Linux, but it should not differ too much against other distributions. I also expect you are familiar with Gentoo and how to compile your kernel. # lspci | grep Wireless 03:00.0 Network controller: Intel Corporation PRO/Wireless 4965 AG or AGN Network Connection (rev 61) First, we need to get the network interface working. Enable the new network stack, in the kernel menuconfig, enable Networking -> Wireless -> Generic IEEE 802.11 Networking Stack (mac80211). I used the currently latest stable kernel, gentoo-sources-2.6.23-r3 Also don't forget to compile the required crypto algorithms under Cryptographic API: <M> Cryptographic algorithm manager <M> CBC support <M> ECB support <M> AES cipher algorithms <M> ARC4 cipher algorithm <M> Michael MIC keyed digest algorithm <M> PCBC support This will build modules called mac80211, blkcipher, aes, arc4, ecb, cryptomgr and crypto_algapi. Load them during boot in /etc/modules.autoload.d/kernel-2.6. Also modprobe right away, so we can continue without rebooting. Add to kernel-2.6 like above. Install the network drivers; unmask and unhardmask iwlwifi and iwl4965-ucode, add ipw4965 to your use flags, then run emerge iwlwifi This will install the iwlwifi system and the firmware needed by your hardware. Now run modprobe iwl4965. Check success/failure with ifconfig -a or dmesg, you should have a new interface available. As soon as you've got the interface up and running, check your HW address. If you've got MAC filtering, don't forget to add it to your "Allow list". Better get that out of the way so we don't forget it... I'm using wpa_supplicant to configure for my networks, emerge wpa_supplicant. /etc/conf.d/net: ---------------- #dhcp is default on all devices modules=( "wpa_supplicant" ) wpa_supplicant_wlan0="-Dwext" /etc/wpa_supplicant/wpa_supplicant.conf: ---------------------------------------- ctrl_interface=/var/run/wpa_supplicant # Let any member of the group "wheel" configure the network ctrl_interface_group=wheel ap_scan=1 # Add network block to connect to unsecure networks. # Giving it a low priority will make all other blocks preferred. network={ key_mgmt=NONE priority=-9999999 } # Add a WPA2 network network={ ssid="my ssid" proto=WPA2 key_mgmt=WPA-PSK psk="secret password" } More information about wpa_supplicant, and examples, are available in /usr/share/doc/wpa_supplicant*/.

Thursday, August 23, 2007

Crap mail client

At work we're blessed with a wonderful mail client which we are suppose to use, by policy. And most people do. I try not to. Maybe you've seen this signature in some peoples' mail:
A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? A: Top-posting. Q: What is the most annoying thing in e-mail?
and indeed they are right. This particular mail client encourages top posting by doing two things. The first one is that when you hit reply it formats the new mail in this manner: <cursor here> <your signature> ------<other persons name> wrote:------ <other persons mail body indented> ... where the irritating thing is that it places your signature above the other persons mail. The second thing is that all mails are in HTML, and the client has some limitations in that regard: The text from the mail you're replying to gets indented in a way where you can't inline your replies without having your text indented too. The interesting stuff happens when people in my organization think of how to workaround these limitations. Some use top posting, and forgets to reply to half of the message. The others use a feature that comes with HTML, coloring! That is, the common way to reply is that you pick a previously not used color in that mail, and color your inlining with that. When the mail gets replied for the seventh time there is indeed eight different colors used, and everything is indented seven steps. Yay.... Naturally there is no "standardization" of which color to pick next, so each conversation is colored in a different way. It can get quite tricky to follow. Also, after a while it gets hard to pick a color that is sufficiently different from other colors. Luckily I'm not color blind. Just to make you realize how bad this really is, imagine this with your favorite indention sensitive programming language: In your editor;
  • You can't indent.
  • When you hit the tab key you just get the color for the current indention level.
  • The mapping of "intention level" to color is different for each source file.
A very interesting thought. The first person to implement this in the editor of their choice will get a postcard from Göteborg, by yours truly.

Friday, June 1, 2007

Code vs. Coder

I read a blog this morning, which got a few thoughts started (oh noes, not again!). Rich Skrenta argued that code is our enemy while Jeff Atwood replied that the code itself isn't the problem, but that the real problem is what you see in the mirror. This reminded me of the good professor John Hughes (who taught me Haskell 5 years ago!), who has along with Koen Classen and others, been writing on QuickCheck the past years. It has been rewritten a number of times, each time with more features but fewer LOCs (lines of codes). Bearing in mind that counting LOCs is regarded as a measurement of productivity, Hughes asks,
Have we had negative productivity? We do more with less code!
Another example would be in the newly released xmonad 0.2 where Don (dons) Stewart recently blogged about how he with fewer lines of code did more by moving some of the logic into the data structures. He used a technique called zipper (references in the end of his blog entry) and could thus merge two data structures into one, eliminating the problem of keeping them concise. Easier to write the code and less risk of writing bugs. Did he have negative productivity too? I would have to say no. Written code has to be maintained by someone, depending on what it was written to do. When GHC 6.6 was released the Gentoo Haskell Herd got busy as roughly half of the Haskell packages only compiled with GHC 6.4.2 (about 16 broken out of 40). Naturally we wanted them to work with GHC 6.6 too. It is hard to foresee what will change, no matter how you write the code, thus giving Skrenta a point. Code is the enemy. Reason for the broken packages (2) mostly was (in no particular order)
  • deprecated modules and classes
  • functionality moved to other modules
  • changed type signatures
  • changes in the type system?
  • changes in the build system
  • UTF8 trouble
All this makes me extra jumpy when Erik Hellman, a Java Consultant in Göteborg, blogs about when a 1400 lines game written in 50 min (in Swedish) which was later presented at the JavaOne conference. 500 lines are auto generated getters/setters, along with 900 manually written lines. Assuming writing the manual lines took 40 min, he wrote a line about every three seconds non-stop. I hardly think though that I even could write 900 lines in 40 min even by heart. He agrees, and notes that this is not possible without an IDE, in which case he recommends IntelliJ IDEA 6.0. Maybe Hellman is an extremely talented hacker and that his tools indeed are excellent, thus it's not possible to write the code in less than 1400 lines (in Java) and that it really should have taken some other programmer the whole day. Possibly the job has been solved and no one has to touch the code ever again. Personally though, I would be more interested to see how the game would evolve in 50 hours, days, or weeks. I guess it depends on what you want your app to do. Still impressive to write a game like that in 50 min, but 1400 LOCs? Hellman replies by saying that we are on the same track, and that we should see the other guy's code. How much logic can you write in 40 min? The resulting massive amount of code does not seem to be a problem. I guess that we just have different backgrounds. I have not yet had a look at the code, which recently was put online, but I do hope that the IDE will help to debug and maintain it. This raises the question of how many lines it would be in Haskell, given the corresponding libraries exists. Anyone want to give it a try?