You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I apologize if this is a very basic question. I'm using ruby-vips in what I think is a very simplistic way to process a few thousand TIFF files and convert them to PNG. It does convert files to PNG but fairly rapidly gobbles up all available memory:
Is there something I'm doing wrong here? I noticed that if I comment out the write it is able to successfully read in all the images, so it appears to be caused by writing the PNG file?
ruby-vips closes files on GC. Ruby will normally GC when its memory is getting low, but this can take a while to happen, and with libraries like vips which hold sometimes large objects outside the ruby heap, you can exhaust main memory before ruby notices. It's also easy to run out of file descriptors: most systems limit you to 1000 files open at once and this is an easy thing to hit with ruby.
If you GC on every file open you kill performance, so ruby-vips compromises and requests a GC every 100 file operations.
vips also keeps a cache of the most recent 1,000 operations in case one is reused. That's probably not what's causing your high memory use though.
I would guess you are processing fewer, much larger tiffs and the GC is not triggering. Try inserting a GC.start into your loop and see if that fixes it.
I have the same problem. Writers allocate memory that is never released. Try the following example with a large jpeg, like your 10000x10000px wtc.jpg and it will have several gigabytes of memory usage in no time, although a single write only allocates ~60 MB:
#!/usr/bin/env rubyrequire'rubygems'require'vips'includeVIPSrepeat=1000defrss`ps -o rss= -p #{$$}`.chomp.to_i/1024endGC.startputs"RSS at startup with gems loaded: %d MB" % [rss]# you can give vips argument flags to ruby-vips programs, eg.# --vips-progress, make sure we don't try to load thosefilenames=ARGV.reject{ |arg| arg.start_with?"-"}repeat.timesdo |i|
filenames.eachdo |filename|
img=Image.jpegfilename,:sequential=>trueimg=JPEGWriter.new(img,quality: 50)img.write('test.jpg')print"\rIteration: %-8d RSS: %6d MB File: %-32s".freeze % [i+1,rss,filename]endendputsGC.startputs"RSS at exit: %d MB" % [rss]
Tested with MRI 2.2.4, ruby-vips f680013 and vips 8.2.2 with libjpeg-turbo 1.4.2 on Mac OS X 10.11.4.
Other writers like PNG and WEBP have the same issue, I chose JPEG because it's very fast.
Occasionally I see drops in RSS eg. from 6 GB down to 3 GB before climbing up again, I think this is the GC.start in the writer class that's triggered every 100 writes.
Example Output:
RSS at startup with gems loaded: 32 MB
Iteration: 1000 RSS: 6232 MB File: earth10k.jpg
This is interesting: If I remove the GC.start completely from write_gc, ruby seems to never deallocate memory from writers:
RSS at startup with gems loaded: 32 MB
Iteration: 1000 RSS: 9329 MB File: earth10k.jpg
# Ruby spends a huge time here running GC.start at exit
RSS at exit: 1496 MB
I tried your nice test program with ruby-vips8 and it runs in a steady amount of memory, though only because it's forced to GC on every call into libvips because of a reference counting issue in ruby-gnome2 :-(
$ ./write8.rb k2.jpg
RSS at startup with gems loaded: 15 MB
Vips::call running with a buggy gobject-introspection
as a workaround, this gem will GC on every call to libvips
fixing this bug will speed things up a lot
http://sourceforge.net/p/ruby-gnome2/mailman/message/34555949/
Iteration: 47 RSS: 145 MB File: k2.jpg
Iteration: 71 RSS: 144 MB File: k2.jpg
Iteration: 97 RSS: 144 MB File: k2.jpg
Iteration: 126 RSS: 145 MB File: k2.jpg
Iteration: 157 RSS: 144 MB File: k2.jpg
Iteration: 198 RSS: 144 MB File: k2.jpg
Iteration: 232 RSS: 144 MB File: k2.jpg
etc. etc.
I tried a few experiments. With the ruby-vips 0.3.9 gem, 500 iterations and a 2k x 1k image I see:
$ time ./write.rb k2.jpg
RSS at startup with gems loaded: 29 MB
Iteration: 500 RSS: 1228 MB File: k2.jpg
real 0m33.947s
user 0m26.832s
sys 0m18.784s
With a lazy GC, it becomes:
Iteration: 500 RSS: 1661 MB File: k2.jpg
real 0m38.993s
With lazy GC plus GC every 10 writes I see:
Iteration: 500 RSS: 284 MB File: k2.jpg
real 0m24.337s
And with lazy GC plus GC every write I see:
Iteration: 500 RSS: 84 MB File: k2.jpg
real 0m20.761s
GC every write, even a lazy GC, will probably have a bad effect on performance for larger Ruby programs. Does lazy GC every 10 writes seem like a reasonable compromise?
The GC.start in write_gc is supposed to protect against running out of file descriptors, not clean up memory allocations, so it's really a hack to use it for that purpose. I'm not familiar with the Ruby C Ext API, but my guess would be that somethings is wrong with how the C binding interact with the Ruby VM's GC, so it's not freeing memory automatically.
If this were to be added as a temporary workaround it would probably make sense to do some benchmarking with smaller image sizes to see the impacts. In my understanding minor GC (full_mark: false) has very little overhead compared to full GC.
In my opinion there's nothing wrong in the binding, it's just a consequence of the mark-sweep Ruby GC. libvips can only free memory when objects are unreffed, Ruby will only unref objects on GC, and Ruby only runs a GC when it begins to fill its own heap.
This must be a problem for any Ruby gem which manipulates large objects. I wonder how they handle this issue?
I suppose one solution would be to have an explicit .free method which you can call if you wish to release memory associated with an image. It would unref the underlying vips object and set the pointer nil, leaving the Ruby image object in a 'zombie' state, then any subsequent operations on that image would throw an exception. This would be fiddly and error-prone to use though.
We could also GC on every write, but throttle to no more than one GC per second or one GC every 10 writes, whichever is sooner. That might give more 'expected' behaviour.
I think it would make sense to have the choice of either a block based api with automatic cleanup at the end of the block and manual cleanup if this is not possible. This is much like ruby's File and Tempfile classes work.
This would allow to control cleanup when it's important but could still work without changes for existing users, who would get cleanup at next gc.
Btw. I'd prefer close or free over destroy, because it could be mistaken to mean deleting the image, if it has been opened from a file. After freeing, the image probably should throw an exception if any methods are called on it and have a method to check for it similar to rmagick's destroyed?. rmagick also allows inspect, which makes sense, because REPLs tend to call it automatically.
I think this would be much cleaner than manually messing with the gc.
libvips has a thing to send a signal to downstream images (images which depend on this image) which it uses for cache invalidation. We could maybe use it to ask all downstream Ruby objects to .destroy! themselves.
It would need a small API addition. I'll have a look.
Coming full circle, back to this issue, I'm still seeing some pretty crazy memory usage.
I'm using my fork of ruby-vips in which I've also removed the GC.start after write operations (because it shouldn't be necessary). However, even inserting this doesn't always fix the memory usage issues in production.
There is a memsize operation (e.g. ObjectSpace.memsize_of) in CRuby which is used to report the actual memory size of a pointer/value. Otherwise, as you say, the GC doesn't know the impact/heap usage of an image. However, I can't see a way to expose this via FFI which is unfortunate.
I've been playing around with the great memory leak sample given above:
Hey all- Thanks you for your hard works on the ruby-vips gem.
I'm also seeing a strange case when I load pdfs.. I'm converting each page to its own image. After browsing through this thread I removed the write to see if that's where the memory was globbing but it's actually in the read. It looks like every call to pdfload is storing the whole pdf in memory. Not sure if this is a GC issue or this is the right thread to post it.
page_count = Vips::Image.pdfload("test.pdf", access: :sequential).get("n-pages")
page_count.times do |p|
im = Vips::Image.pdfload("test.pdf", page: p, n: 1, access: :sequential)
im.write_to_file("buffer/test.#{p}.png")
end
In this case, I don't actually see a GC happen. The file is 298 pages and 5.5mb
We're doing the same thing as @jalevin, and if I don't manually call GC.start every 10 iterations or so we run out of file handles for large PDFs. An explicit close would be super helpful. The handles still go up with Vips::cache_set_max 0.
And watch in top, memory use stabilises after about 3,000 pages at 2.3gb. After that, it wobbles up and down between 2.3 and 2.4, presumably due to memory fragmentation.
I realize this is a lot of memory, but at least it's stable. File handle use stays low, at least.
Perhaps something can be done to make it stabilize at a lower level, but that should probably be in a new issue.
HEIC and PNG are hilariously slow. PDF looks good here, but that's converting page 0, the title page, which just has a couple of lines of text on. A complex page with a lot of graphics would look very different.
Activity
jcupitt commentedon Jun 26, 2015
Hi @edsu I doubt if you're seeing a leak, it's probably an issue with caching and the GC. I tried this program:
I put 10,000 copies of
cramps.tifintoimage_dir/, ran the program and watched MEM in top. I saw:100 50MB
300 80MB
600 150MB
1000 182MB
1600 230MB
2100 250MB
2400 280MB
2700 260MB
4200 260MB
8400 230MB
ruby-vips closes files on GC. Ruby will normally GC when its memory is getting low, but this can take a while to happen, and with libraries like vips which hold sometimes large objects outside the ruby heap, you can exhaust main memory before ruby notices. It's also easy to run out of file descriptors: most systems limit you to 1000 files open at once and this is an easy thing to hit with ruby.
If you GC on every file open you kill performance, so ruby-vips compromises and requests a GC every 100 file operations.
vips also keeps a cache of the most recent 1,000 operations in case one is reused. That's probably not what's causing your high memory use though.
I would guess you are processing fewer, much larger tiffs and the GC is not triggering. Try inserting a
GC.startinto your loop and see if that fixes it.felixbuenemann commentedon Jan 17, 2016
I have the same problem. Writers allocate memory that is never released. Try the following example with a large jpeg, like your 10000x10000px wtc.jpg and it will have several gigabytes of memory usage in no time, although a single write only allocates ~60 MB:
Tested with MRI 2.2.4, ruby-vips f680013 and vips 8.2.2 with libjpeg-turbo 1.4.2 on Mac OS X 10.11.4.
Other writers like PNG and WEBP have the same issue, I chose JPEG because it's very fast.
Occasionally I see drops in RSS eg. from 6 GB down to 3 GB before climbing up again, I think this is the GC.start in the writer class that's triggered every 100 writes.
Example Output:
felixbuenemann commentedon Jan 17, 2016
If I add a
GC.startafter each write, memory usage stays between 220 and 255 MB RSS.felixbuenemann commentedon Jan 17, 2016
I replaced the
VIPS::Writer#write_gcmethod with a different implementations, that does a minor, lazy GC and it keeps RSS steady at ~189 MB:felixbuenemann commentedon Jan 17, 2016
This is interesting: If I remove the
GC.startcompletely fromwrite_gc, ruby seems to never deallocate memory from writers:jcupitt commentedon Jan 17, 2016
I didn't know about
full_mark: false, immediate_sweep: false. Do you think it would be a good idea to use these options inwrite_gc?Every 100 times might be too long as well, this could maybe come down.
jcupitt commentedon Jan 17, 2016
I tried your nice test program with
ruby-vips8and it runs in a steady amount of memory, though only because it's forced to GC on every call into libvips because of a reference counting issue in ruby-gnome2 :-(And then:
jcupitt commentedon Jan 17, 2016
I tried a few experiments. With the ruby-vips 0.3.9 gem, 500 iterations and a 2k x 1k image I see:
With a lazy GC, it becomes:
With lazy GC plus GC every 10 writes I see:
And with lazy GC plus GC every write I see:
GC every write, even a lazy GC, will probably have a bad effect on performance for larger Ruby programs. Does lazy GC every 10 writes seem like a reasonable compromise?
felixbuenemann commentedon Jan 17, 2016
The
GC.startinwrite_gcis supposed to protect against running out of file descriptors, not clean up memory allocations, so it's really a hack to use it for that purpose. I'm not familiar with the Ruby C Ext API, but my guess would be that somethings is wrong with how the C binding interact with the Ruby VM's GC, so it's not freeing memory automatically.If this were to be added as a temporary workaround it would probably make sense to do some benchmarking with smaller image sizes to see the impacts. In my understanding minor GC (full_mark: false) has very little overhead compared to full GC.
jcupitt commentedon Jan 17, 2016
In my opinion there's nothing wrong in the binding, it's just a consequence of the mark-sweep Ruby GC. libvips can only free memory when objects are unreffed, Ruby will only unref objects on GC, and Ruby only runs a GC when it begins to fill its own heap.
This must be a problem for any Ruby gem which manipulates large objects. I wonder how they handle this issue?
I suppose one solution would be to have an explicit
.freemethod which you can call if you wish to release memory associated with an image. It would unref the underlying vips object and set the pointer nil, leaving the Ruby image object in a 'zombie' state, then any subsequent operations on that image would throw an exception. This would be fiddly and error-prone to use though.We could also GC on every write, but throttle to no more than one GC per second or one GC every 10 writes, whichever is sooner. That might give more 'expected' behaviour.
jcupitt commentedon Jan 17, 2016
Looks like
rmagickhas a.destroy!method for this purpose:https://rmagick.github.io/image1.html#destroy_bang
felixbuenemann commentedon Jan 17, 2016
I think it would make sense to have the choice of either a block based api with automatic cleanup at the end of the block and manual cleanup if this is not possible. This is much like ruby's File and Tempfile classes work.
This would allow to control cleanup when it's important but could still work without changes for existing users, who would get cleanup at next gc.
Btw. I'd prefer
closeorfreeoverdestroy, because it could be mistaken to mean deleting the image, if it has been opened from a file. After freeing, the image probably should throw an exception if any methods are called on it and have a method to check for it similar to rmagick'sdestroyed?. rmagick also allows inspect, which makes sense, because REPLs tend to call it automatically.I think this would be much cleaner than manually messing with the gc.
jcupitt commentedon Jan 17, 2016
I think the block API would only be useful in trivial cases. For example:
Would not free correctly, since the image generated by the
.invertwould not have.destroy!called on it. I suppose you'd have to write:which seems very ugly.
felixbuenemann commentedon Jan 17, 2016
That would be weird. But maybe we could track all allocations inside the block?
jcupitt commentedon Jan 17, 2016
That's a good idea, maybe we could.
libvips has a thing to send a signal to downstream images (images which depend on this image) which it uses for cache invalidation. We could maybe use it to ask all downstream Ruby objects to
.destroy!themselves.It would need a small API addition. I'll have a look.
30 remaining items
tune GC a bit
more GC tuning
ioquatix commentedon Mar 24, 2020
Coming full circle, back to this issue, I'm still seeing some pretty crazy memory usage.
I'm using my fork of
ruby-vipsin which I've also removed the GC.start after write operations (because it shouldn't be necessary). However, even inserting this doesn't always fix the memory usage issues in production.There is a memsize operation (e.g.
ObjectSpace.memsize_of) in CRuby which is used to report the actual memory size of a pointer/value. Otherwise, as you say, the GC doesn't know the impact/heap usage of an image. However, I can't see a way to expose this via FFI which is unfortunate.I've been playing around with the great memory leak sample given above:
https://github.com/ioquatix/vips-thumbnail/blob/master/examples/memory/leak.rb
In the worst case, it basically keeps on chewing through data, which is never returned, even after the final GC:
I would have expected calling
img.close(vips_image_invalidate_all) should release memory:The only thing that works is GC after each iteration:
Thoughts?
ioquatix commentedon Mar 24, 2020
Okay, I was playing around with it a bit more. It turns out if you inform the GC of the buffer size, it will do a better job.
What we need is a way to tell the GC the correct buffer size/memory usage.
felixbuenemann commentedon Mar 24, 2020
@ioquatix How did you arrive at the 30 MiB buffer size and shouldn't the value in release be negative?
Btw. a shortcut for specifying KiB, MiB etc.:
1<<10KiB,1<<20MiB,1<<30GiB.ioquatix commentedon Mar 24, 2020
@felixbuenemann I just took a random stab based on the 4MiB JPEG + 32MiB frame buffer (decoded).
Yeah, it should be negative. I'll fix it. But it was just a typo, it still works in the actual code.
jalevin commentedon May 27, 2020
Hey all- Thanks you for your hard works on the ruby-vips gem.
I'm also seeing a strange case when I load pdfs.. I'm converting each page to its own image. After browsing through this thread I removed the write to see if that's where the memory was globbing but it's actually in the read. It looks like every call to pdfload is storing the whole pdf in memory. Not sure if this is a GC issue or this is the right thread to post it.
In this case, I don't actually see a GC happen. The file is 298 pages and 5.5mb
ioquatix commentedon May 27, 2020
That is definitely some kind of memory explosion.
jcupitt commentedon May 27, 2020
Could it be the libvips cache? Try:
It could also be your libvips not being configured with pdfload and falling back to converting via imagemagick. At the bash prompt, try:
To check that you have a pdf loader. I guess it could also be a bug in poppler --- we'd need a test image to verify that.
tpendragon commentedon Aug 6, 2020
We're doing the same thing as @jalevin, and if I don't manually call
GC.startevery 10 iterations or so we run out of file handles for large PDFs. An explicit close would be super helpful. The handles still go up withVips::cache_set_max 0.jcupitt commentedon Aug 7, 2020
I had a go at improving the behaviour of the PDF loader with file handles, if anyone has time to test.
libvips/libvips#1770
It has some other useful improvements as well around default cache sizing.
jcupitt commentedon Sep 27, 2020
That improvement to the PDF loader has been merged to git master libvips. I made a small benchmark:
If I run like this:
And watch in
top, memory use stabilises after about 3,000 pages at 2.3gb. After that, it wobbles up and down between 2.3 and 2.4, presumably due to memory fragmentation.I realize this is a lot of memory, but at least it's stable. File handle use stays low, at least.
Perhaps something can be done to make it stabilize at a lower level, but that should probably be in a new issue.
jcupitt commentedon Sep 27, 2020
I should have said, that high memory use is just for the PDF loader. If I try:
ie. repeatedly convert a single file to JPG, I see:
HEIC and PNG are hilariously slow. PDF looks good here, but that's converting page 0, the title page, which just has a couple of lines of text on. A complex page with a lot of graphics would look very different.