19

i've been trying to read a large file in haskell.

I need to compress it using a custom algorithm for a university project. Everything works fine untill i start to compress big files.

I extracted what was going wrong out of my program, and i expose it here in the form of a "Hello big file":

import System
import qualified Data.ByteString.Lazy as BL
import Data.Word

fold_tailrec :: (a -> b -> a) -> a -> [b] -> a
fold_tailrec _ acc [] =
    acc
fold_tailrec foldFun acc (x : xs) =
    fold_tailrec foldFun (foldFun acc x) xs

fold_tailrec' :: (a -> b -> a) -> a -> [b] -> a
fold_tailrec' _ acc [] =
    acc
fold_tailrec' foldFun acc (x : xs) =
    let forceEval = fold_tailrec' foldFun (foldFun acc x) xs in
    seq forceEval forceEval

main :: IO ()
main =
    do
        args <- System.getArgs
        let filename = head args
        byteString <- BL.readFile filename
        let wordsList = BL.unpack byteString
        -- wordsList is supposed to be lazy (bufferized)
        let bytesCount = fold_tailrec (\acc word -> acc + 1) 0 wordsList
        print ("Total bytes in " ++ filename ++ ": " 
               ++ (show bytesCount))

I name this file Test.hs, then do the following:

$ ls -l toto
-rwxrwxrwx 1 root root 5455108 2011-03-23 19:08 toto
$ ghc --make -O Test.hs
[1 of 1] Compiling Main             ( Test.hs, Test.o )
Linking Test ...
$ ./Test toto
Stack space overflow: current size 8388608 bytes.
Use `+RTS -Ksize -RTS' to increase it.
$ ./Test toto +RTS -K50M -RTS
Stack space overflow: current size 50000000 bytes.
Use `+RTS -Ksize -RTS' to increase it.
$ ./Test toto +RTS -K500M -RTS
"Total bytes in toto: 5455108"
$ time ./Test toto +RTS -K500M -RTS
"Total bytes in toto: 5455108"

real    0m33.453s
user    0m8.917s
sys 0m10.433s

Could anyone please explain why i need 500 Megabytes of RAM and 30 seconds of CPU in order to browse a miserable 5 Megabytes file ? Please what am i doing wrong ? Why isn't the [word8] bufferized as the ByteString documentation states. And how to fix this ?

I tried to define my own tail recursive fold instead of foldl, foldr, or foldl'. I tried to unfreeze the thunks as well with seq. I got no result so far.

Thanks for any kind of help because i'm stuck.

Don Stewart
  • 137,316
  • 36
  • 365
  • 468
Joel
  • 3,427
  • 5
  • 38
  • 60
  • 1
    @FUZxxl, presumably this is a simple reproducer; if we had his compression code to deal with too, it'd be that much harder to reason about the program. If all Joel really wanted was the length, might as well ask the os with `stat(2)` and save all that disk IO. – sarnold Mar 23 '11 at 20:07
  • 1
    What do you need your own fold for? The ones in the standard libraries should work fine. Tail recursion isn't always the right thing in Haskell, due to laziness. I think what you want for computing the length is a strict left fold that is also strict in the accumulator. You should be able to get that via foldl' and possibly a seq. – Jason Dagit Mar 23 '11 at 20:10
  • 1
    @FUZxxl `length` will cause a memory leak. You have to keep the entire thing in memory because it can't be garbage collected until it calls `length`. – Ezra Mar 23 '11 at 20:10
  • 1
    I would suggest you look at the enumerator package instead of using lazy IO. – Jason Dagit Mar 23 '11 at 20:12
  • Hello, it's only an example. My code is spread into many modules, dealing with compressions stuff. Here i extracted what was going wrong out of my program. I don't need to use my own fold, i was just showing that i tried this with tail recursion, and then strictness, and it didn't solve the problem. And i'm not trying to count the file size, but i need to browse it byte by byte, as in the example. Thank you if you can help. – Joel Mar 23 '11 at 20:12
  • @Ezra: Nope. Try something like `length [1..100000000] it will complete in O(1), since Haskell can already garbage collect the beginning of the string while length is iterating through the list. It's only an issue if you're using the list again afterwards. – fuz Mar 23 '11 at 20:16
  • @FUZxxl: Maybe things have changed, or we're talking about different things. See http://broadcast.oreilly.com/2009/01/why-you-should-learn-haskell.html about half-way down. s/length/. Also, `length [1..100000000000000000]` is taking a *long* time on my system. Also http://stackoverflow.com/questions/2517079/in-haskell-will-calling-length-on-a-lazy-bytestring-force-the-entire-string-into – Ezra Mar 23 '11 at 20:22
  • @Ezra: EValauting the length of a list of length 10 quadrillion will take a lot time regardless of which way you do it. With O(1), I meant the memory. – fuz Mar 23 '11 at 20:26
  • @FUZxxl: Sorry for the misunderstanding. We were talking about different things. All I can suggest to @Joel is to check out http://www.haskell.org/haskellwiki/Performance, which is not very directed advice. – Ezra Mar 23 '11 at 20:36

1 Answers1

34

The construct "seq x x" is always useless. If y = seq x x and I force y then this forces x then returns x. This is equivalent to y=x and forcing y. Thus "seq forceEval forceEval" does nothing more than "forceEval".

The error with your use of a fold is a common one.

You are using a fold to perform a count of the bytes in the input. You should be using a strict left fold for such a sum, but your hand written fold is a lazy left fold. The (acc+1) is not getting evaluated, so it builds 5 million nested applications: (((...(0+1)+1)+1)+1)+1)+1)...+1). Then it is forced when printing, and the evaluation tries to descend into 5 million parentheses.

Thus the pending stack has one entry for each Word8. For short inputs it reaches the end and sees 0. For long inputs it runs out of stack space with GHC because the creators and most users of GHC think that trying to allocate 5 million stack frames is usually a design error by the programmer.

I predict that you can use "seq" to fix this:

fold_tailrec' foldFun acc (x : xs) =
    let acc' = foldFun acc x
    in seq acc' (fold_tailrec' foldFun acc' xs)
Chris Kuklewicz
  • 8,123
  • 22
  • 33
  • 1
    thanks a lot, it works! i'm a newbie here, how to mark a question as solved please ? – Joel Mar 23 '11 at 20:27
  • 1
    @Joel: There should be an outline of a checkmark at the top left of the answer, just below the score for the answer. Click there to mark as solved. – Boris Mar 23 '11 at 20:53
  • 2
    They could probably add a warning for such cases. – fuz Mar 23 '11 at 21:21
  • 1
    A more in depth explanation here: http://www.haskell.org/haskellwiki/Foldr_Foldl_Foldl' (short summary: you almost always want either `foldr` or `foldl'`). – porges Mar 23 '11 at 21:42