New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix a memory leak on exception (caused by the stored traceback) #11572

Open
wants to merge 1 commit into
base: master
from

Conversation

Projects
None yet
5 participants
@stas00
Copy link

stas00 commented Jan 22, 2019 •

Currently ipython stores the traceback on exception. The problem is that it creates a circular reference to locals() in each frame of the traceback. And until next exception arrives gc.collect() will fail to collect. If locals() happened to be huge variables, like 8GB of GPU RAM, the user has no choice but to restart ipython/jupyter to recover.

Solution - cleanse the saved tb from any references to locals() by running it through: traceback.clear_frames(tb)

My fix was made to only one such location in the ipython code and there is a dozen other places where it does that. So please kindly review for other similar situations.

I wrote a test case that demonstrates the problem and putting this fix in that particular location fixed that leak. But I don't know whether they are other situations where a similar fix needs to be applied.

You can see the test case here (run it with Alt-F so it runs all cells ignoring the errors)
https://hub.mybinder.org/user/stas00-fastai-misc-xbrsnjae/notebooks/debug/ipython/locals_leak_on_exc.ipynb
It shows how if there is a local variable that is of 128MB in size, an exception involving that function will leak that much RAM. And it shows how the next exception will release the previously held locals() allowing gc.collect() to recover that leaked memory.

The source of the test case is here:
https://github.com/stas00/fastai-misc/blob/master/debug/ipython/locals_leak_on_exc.ipynb

and here it is in straight ipython's output:

In [1]: import numpy as np                                                                                                                                                  

In [2]: def consume_cpu_ram(n): return np.ones((n, n)) 
   ...: def consume_cpu_ram_128mb():  return consume_cpu_ram(2**12)                                                                                                         

In [3]: import gc, os, sys, time, psutil 
   ...: process = psutil.Process(os.getpid()) 
   ...: def cpu_ram_used():  return process.memory_info().rss                                                                                                               

In [4]: def fail(): 
   ...:     x = consume_cpu_ram_128mb() 
   ...:     raise ValueError("Ouch") 
   ...:                                                                                                                                                                     

In [5]: before = cpu_ram_used() 
   ...: fail()                                                                                                                                                              
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-3b8b03759f74> in <module>
      1 before = cpu_ram_used()
----> 2 fail()

<ipython-input-4-e846ddbe1c18> in fail()
      1 def fail():
      2     x = consume_cpu_ram_128mb()
----> 3     raise ValueError("Ouch")
      4 

ValueError: Ouch

In [6]: gc.collect() 
   ...: after = cpu_ram_used() 
   ...: print(f"Difference { (after-before)/2**20}")                                                                                                                        
Out[6]: 1105
Difference 128.62890625

In [7]: # force ipython to reset its %tb 
   ...: raise ValueError("Reset")                                                                                                                                           
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-31374e7d7384> in <module>
      1 # force ipython to reset its %tb
----> 2 raise ValueError("Reset")

ValueError: Reset

In [8]: gc.collect() 
   ...: after = cpu_ram_used() 
   ...: print(f"Difference { (after-before)/2**20}")                                                                                                                        
Out[8]: 418
Difference 0.77734375
@stas00

This comment has been minimized.

Copy link

stas00 commented Jan 22, 2019

I see that it affected a few tests, which fail since the traceback printout got affected.

I trust you will know whether the tests need to be adjusted or perhaps you have a different solution to avoid this very problematic leak.

Thanks.

@rgbkrk

rgbkrk approved these changes Jan 22, 2019

Copy link
Member

rgbkrk left a comment

Thank you so much for investigating and fixing this one! Are you able to update the tests too, to make them less strict about the output?

@rgbkrk rgbkrk added this to the 7.3 milestone Jan 22, 2019

@spott

This comment has been minimized.

Copy link

spott commented Jan 22, 2019

Is there a test to check if the %debug magic is affected by this? I would expect it would be (the %debug magic kind of needs to know the current frame so it can work...)

Since the workaround is to raise another exception, it might make sense to just note that in the text for the OutOfMemory exception, or to only clear the frames when an oom exception is raised.

@stas00

This comment has been minimized.

Copy link

stas00 commented Jan 22, 2019 •

Yes, someone else has just mentioned to me that %debug is affected, since it relies on the locals() to be set. So more work needs to be done. I don't know anything about ipython's internals, but for its devs it should be an easy task to figure out.

Note that my patch was applied to a helper function _get_exc_info(), which is called in various places. It's possible that there is a better place to do traceback.clear_frames(tb), that perhaps won't affect %debug. (i.e. in some specific location in the code, rather than in that helper function).

It's possible that %debug magic needs to activate a flag that doesn't call traceback.clear_frames(tb) if needed, but by default it should be done. I hope it makes sense.

Since the workaround is to raise another exception, it might make sense to just note that in the text for the OutOfMemory exception, or to only clear the frames when an oom exception is raised.

And while in the user code we can make a special case for OOM, it is definitely not an option on ipython level, since the leakage affects all exceptions!

For example, jupyter notebook via ipython leaks memory on keyboard interrupt.

@stas00

This comment has been minimized.

Copy link

stas00 commented Jan 22, 2019

Thank you so much for investigating and fixing this one! Are you able to update the tests too, to make them less strict about the output?

:)

First, help is needed to figure out how ipython can avoid this leak w/o affecting %debug magic

@stas00

This comment has been minimized.

Copy link

stas00 commented Jan 23, 2019

Found a solution for making %pdb on magic work correctly, by simply checking the flag and not stripping then:

--- a/IPython/core/interactiveshell.py
+++ b/IPython/core/interactiveshell.py
@@ -1950,7 +1950,7 @@ def _get_exc_info(self, exc_tuple=None):
         else:
             etype, value, tb = exc_tuple
         # must not create circular reference to locals() in each frame of stored tb
-        traceback.clear_frames(tb)
+        #traceback.clear_frames(tb)

         if etype is None:
             if hasattr(sys, 'last_type'):
@@ -2026,6 +2026,9 @@ def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
                         # in the engines. This should return a list of strings.
                         stb = value._render_traceback_()
                     except Exception:
+                        if not self.call_pdb:
+                            traceback.clear_frames(tb)
+
                         stb = self.InteractiveTB.structured_traceback(etype,
                                             value, tb, tb_offset=tb_offset)

the problem with %debug magic, is that it happens in the next cell, so there is no way to predict the user will want to enter the debugger after the exception. So it's a bit of a chicken and egg problem. It almost looks like the user will need to declare if they want to run a debugger. New magic: %savetb, which will work like %pdb, except won't invoke the debugger automatically?

Are there any other cases this change needs to be concerned about, other than %debug and %pdb magic?

@stas00

This comment has been minimized.

Copy link

stas00 commented Jan 23, 2019

Thank you so much for investigating and fixing this one! Are you able to update the tests too, to make them less strict about the output?

@rgbkrk, once I was able to figure out how to run the tests, (which is not documented #11573), the failures are the same in all tests, because the tb no longer contains the locals(), we get, after stripping parts that do match:

Expected:
    ... in bar(mode='div')
Got:
    ~/github/00jupyter/ipython-leak-on-exc/IPython/core/tests/simpleerr.py in bar(***failed resolving arguments***)

So I'm not sure it's just about fixing the tests to be more forgiving. It could be a real issue that changing tests would then mask it.

It's the same issue as with %debug magic - how do we know ahead of time whether the user will need that data or not.

Though in the particular case of the backtrace in the failing tests - it can be made into a string while locals() are still present, free them, and then pass on just the printable tb.

@fperez

This comment has been minimized.

Copy link
Member

fperez commented Jan 23, 2019

I wanted to stop by and first, thank you for this! It sounds like getting to the bottom of it was quite the nightmare...

I unfortunately don't have time to look for a cleaner implementation, but perhaps the following on the intent behind %debug can help you... Originally IPython only had %pdb, which could be toggled if you knew that you needed it in advance, but was useless if you had an expensive exception pop up and hadn't thought of activating it first.

At some point we realized that, if we saved enough tb state, we could provide a better UX with a new magic that could be activated at any time, without any work in advance, to dig back into a previous exception. Thus was %debug born.

This explains why it's so aggressive at storing exception state. Now, don't know for sure if the problem you've encountered can be mitigated in a way that saves less state and still allows %debug to work, but I suspect not. In that case, I think the cleanest solution is to add new flags to %debug, --on and --off that toggle exception state storage.

The question that remains is then what to do by default; we have two options:

a) Preserve current default behavior so %debug works out of the box, but users on GPU workflows would need to toggle it off on startup or in their config files.

b) Toggle it off by default (basically consider the current behavior a bad enough bug worth breaking backward expectations of behavior). Users could still configure it to force on if desired, and a naked %debug call with no exception storage active could print an informative error toggling it on and explaining the situation.

I'm slightly inclined towards (a) as this, while problematic, still seems to be a slightly specialized bug and changing the behavior may confuse many existing users. But I could see a good argument going the other way too, happy to hear others' thoughts.

Many thanks again for the hard work you've put into it, probably one of the craziest bug fixes in terms of time invested vs. final lines of code :)

@stas00

This comment has been minimized.

Copy link

stas00 commented Jan 23, 2019

Thank you for your follow up, @fperez, and sharing the history of %debug and suggesting a way to move forward.

The question that remains is then what to do by default; we have two options:

a) Preserve current default behavior so %debug works out of the box, but users on GPU workflows would need to toggle it off on startup or in their config files.

I personally am fine with (a), because debugging should be as easy as possible and your explanation of why %debug was born supports that. In which case we need an easy way to clear the %tb, which currently can be done with 'assert True' as a workaround, so something like %tb clear since we already have %tb magic or a new command would do.

We just need to make it easy for users to find out this information. Perhaps a very compact notice should be printed at the end of the exception if debug is on? To give users some breadcrumbs to follow.

So the new workflow will be:

Scenario: An exception occurred and the gpu card is unusable.

Was %debug off set in the first cell of the notebook?

  • Yes? All is good
  • No? ipython prints tb and suggests: run %tb clear and setup %debug off in the first cell of the notebook for permanent solution.

Many thanks again for the hard work you've put into it, probably one of the craziest bug fixes in terms of time invested vs. final lines of code :)

Well, to support %pdb out of the box it's double the lines (2) :)
But seriously, that patch probably should be integrated too in the final version, since it's the easiest of them all and will be backward compatible no matter what the community decides.

Thank you for the kind words, everybody. I knew it was a big problem, but I didn't realize that it was so big.

@stas00

This comment has been minimized.

Copy link

stas00 commented Jan 23, 2019

BTW, through trial and error I learned that the leak had to do with saving the exception object, but this is how I stumbled upon traceback.clear_frames(tb). I saw it quite a few times in the traceback manpage, but I had no idea what it was meant for. Until I stumbled upon this bug report from 2006 https://bugs.python.org/issue1565525 which took 8 years to resolve! So thanks to Greg Hazel who started that battle and all involved who over the years contributed to having a solution.

@rgbkrk

This comment has been minimized.

Copy link
Member

rgbkrk commented Jan 23, 2019

(b) Toggle it off by default (basically consider the current behavior a bad enough bug worth breaking backward expectations of behavior). Users could still configure it to force on if desired, and a naked %debug call with no exception storage active could print an informative error toggling it on and explaining the situation.

Just leaving a note that I'm in favor of (b), especially because the source of kernel death is really hard to track down in these cases. It makes me wonder about all the times I've had to tell a user to "just" restart when it was something they could have diagnosed themselves.

@spott

This comment has been minimized.

Copy link

spott commented Jan 23, 2019

I'm in favor of (a). It would inexplicably break a lot of common behavior if suddenly %debug failed to work. Considering there is a pretty simple workaround (raise another exception) that can be used to fix the problem after the fact, it doesn't seem to warrant the breakage. I think documentation is a much better way to solve this problem, especially cause the fix would make %debug not work by default, but it would only solve it when the kernel crashes due to an out of memory exception.

@stas00

This comment has been minimized.

Copy link

stas00 commented Jan 24, 2019 •

I think documentation is a much better way to solve this problem, especially cause the fix would make %debug not work by default, but it would only solve it when the kernel crashes due to an out of memory exception.

Just to clarify: the problem affects any exception, not just CUDA OOM, i.e. any exception leaks memory (temporarily until the next exception arrives if ever). The only special thing about CUDA OOM exception is that it prevents the user from being able to continue 100% of the cases. But, otherwise, any exception could lead to an almost 100% RAM usage, as it'd leak all locals(), and the OOM is just around the corner. For example, if you hit Interrupt during the training, the memory leaks just the same. And it's very likely that the next training loop will OOM, and it wouldn't have happened w/o the interrupt exception that leaked memory a call earlier.

So, no, it'd solve it for many more situations than just CUDA OOM. Nevertheless, I'm with you on (a).

@Carreau

This comment has been minimized.

Copy link
Member

Carreau commented Jan 24, 2019

Thanks for the bug report and the PR. As you said there may be many places where the clear_frames need to be applied. So maybe we should open an issue to track those.

As we are still in a minor release cycle I'm in favor of not changing the behavior, and postponing thee change of behavior (if any) to IPython 8.

Though I've only scanned though the issue and need to get a better deeper look.

I'm in the process of releasing 7.3 soon, which is overdue by ~a month. But I'm hopping to do minor releases monthly when possible anyway.

@stas00

This comment has been minimized.

Copy link

stas00 commented Jan 24, 2019

From my experimentation it seems to be that a more precise location for it is here: #11572 (comment) as compared to the original PR commit. But as I said earlier someone who knows the insides of ipython will have a much better judgement.

Indeed, since this PR will require more work by one of your devs, to integrate the new %debug behavior it makes sense to move it into a PR. So please feel free to do what you think is the best. You no longer need my input as I think the issue is very clear and you have the test case to go with it.

Personally, I don't think there is a rush to squeeze the solution into the next minor release, since we have solid workarounds and we will still need those to support users with older ipython versions. As long as there is a champion on your dev team to ensure that this does get resolved.

And thank you.

@stas00

This comment has been minimized.

Copy link

stas00 commented Jan 24, 2019 •

One thing would be useful to rush in in the minor release, and that's an ipython magic to clear %tb, so that we don't have to make a manual assertion to free the memory. If it is sensible, of course.

@spott

This comment has been minimized.

Copy link

spott commented Jan 24, 2019

Just to clarify: the problem affects any exception, not just CUDA OOM...

That makes sense. Then I would like to propose a (c), which might be a good compromise:

(c) If an exception occurs, the traceback is cleared at the beginning of the next cell execution if:
1) The next cell is not a %debug call.
2) A special flag (%debug save or similar) is not set. If the flag is set, then we get current behavior (where the traceback is kept around indefinitely). If the flag is not set, then the traceback is cleared, avoiding future OOM problems.

%debug save could even have options (keep debug traces around for n executions or something similar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment