MATLAB out of memory on linux despite regular "clear all" - matlab

I am batch processing a bunch of files (~200) on MATLAB, in essence
for i = 1:n, process(i); end
where process(i) opens a file, reads it and writes out the output to another file. (I am not posting details about process here because it is hundreds of lines long and I readily admit I don't fully understand the code, having obtained it from someone else).
This runs out of memory after every dozen of files or so. Of course, on Linux, the memory function is not available so we have to figure it out "by hand". Well, I thought there is some memory leak, so let's issue a clear all after every run, i.e.
for i = 1:n, process(i); clear all; end
No luck, this still runs out of memory. At the point where this happens, who says there's just two small arrays in memory (<100 elements). Note that quitting MATLAB and restarting solves the problem, so the computer certainly has enough memory to process a single item.
Any ideas to help me detect where the error comes from would be welcome.

This is probable not the solution you are hoping for but as a workaround you could have a shell script that loops over several calls to Matlab.

Related

Matlab Process Memory Leak Over 16 Days

I'm running a real-time data assimilation program written in Matlab, and there seems to be a slow memory leak. Over the course of about 16 days, the average memory usage has increased by about 40% (see the figure below) from about 1.1GB to 1.5GB. The program loops every 15 minutes, and there is a peak in memory usage for about 30 seconds during the data assimilation step (visible in the figure).
At the end of each 15 minute cycle, I'm saving the names, sizes, and types of all variables in the currently active workspace to a .mat file using the whos function. There are just over 100 variables, and after running the code for about 16 days, there is no clear trend in the amount of memory used by any of the variables.
Some variables are cleared at the end of each cycle, but some of them are not. I'm also calling close all to make sure there are no figures sitting in memory, and I made sure that when I'm writing ASCII files, I always fclose(fileID) the file.
I'm stumped...I'm wondering if anyone here has any suggestions about things I should look for or tools that could help track down the issue. Thanks in advance!
Edit, system info:
RHEL 6.8
Matlab R2014b
I figured out the problem. It turns out that the figure handles were hidden, and close('all') only works on figures that are visible. I assume they're hidden because the figures are created outside the scope of where I was trying to close the figures. The solution was to replace close('all') with close all hidden, which closes all figures including those with hidden handles.
I'll go ahead and restate what #John and #horchler mentioned in their comments, in case their suggestions can help people with similar issues:
Reusing existing figures can increase performance and reduce the potential for memory leaks.
Matlab has an undocumented memory profiler that could help debug performance related issues.
For processes that are running indefinitely, it's good practice to separate data collection/processing and product generation (figures etc). The first reads in and processes the data and saves it to a DB or file. The second allows you to "view/access/query" the data.
If you are calling compiled mex functions in your code, the memory leak could be coming from the Fortran or C/C++ code. Not cleaning up a single variable could cause a leak, and would explain linear memory growth.
The Matlab function whos is great for looking at the size in memory of each variable in the workspace. This can be useful for tracking down which variable is the culprit of a memory leak.
Thanks #John and #horchler!

Debugging Matlab avoids memory leak

I have a memory intensive Matlab script.
What puzzles me is that if I run this code it will leak memory at the very first iteration (out of the 46 expected). The leak will eventually become so big that it will require forcing Matlab to quit:
Trying to find the leak point, I set a breakpoint at the first line in the loop but as I hit "Continue" the execution ran through the first loop and stopped again at the breakpoint and produced no leak. Removing the breakpoint and continuing from that point reintroduces the leak.
Using the breakpoint to execute the code one loop at the time avoids the leak and the code terminates with no issues (fig.2).
Now, I would like to:
1) understand whether this leak is due to something I introduced or whether it could be a Matlab specific issue,
2) get an idea of how to find the leak (I cannot use the debugger as it removes the problem).
I would love to provide the code but it is quite a big chunk (>100 lines), so my question is more about the general approach than the actual debugging of the specific issue.
Thanks for the suggestions.
My approach has been to isolate the portion of code that was causing the problem with printouts above each line of code so that before the leaky crash I could see where the execution stopped.
The culprit was a zeros(100k) line where I tried to pre-allocate a big matrix.
I tried executing the same line on a newer version of Matlab (2015b vs 2014b) and found that while the older version lets you instantiate big matrices (over ~ 50k by 50k) and freezes when it sucks all the memory, the newer version returns the following error:
Error using zeros
Requested 50000x50000 (18.6GB) array exceeds maximum array size preference. Creation of arrays greater than this limit may take a long time and cause MATLAB to become unresponsive.
See array size limit or preference panel for more
information.
In my case the limits for a NxN matrix are:
N > ~60000 on Matlab2014b on 16GB RAM
N >= 46341 on Matlab2015b on 12GB RAM
With the difference that my 2014 version lets me at least try to create them and collapses when they are too big and the 2015 version prevented me from trying at all.
The puzzling bit is that, on the 2014b version, if I debug the code the compilers lets the zeros(100k) line run and everything works just fine.
The problem appears again if I try to visualise the contents of the matrix in Matlab Variables Tab.

Growing memory usage in MATLAB

I use MATLAB for programming some meta-heuristics. Recently, I have been working on an algorithm for solving an industrial engineering problem. My problem with MATLAB is getting "out of memory" errors. Now I'm trying some suggestions from Mathworks and Stackoverflow (Hope they will work). However, there is one thing I did not understand.
During the run of the algorithm in MATLAB (it takes 4000-5000 cpu sec for a medium sized problem), even though I preallocate variables, code does not demand dynamic array resizing and does not add new variables, I observe that the memory usage of the algorithm grows continuously. The main function calls some other functions written by me. What could be the reason of increase of the memory usage?
The computer I use for the running of the algorithm has 8GBs of memory and win8 64bit installed.
The only way to figure this out is to see where the memory is going.
I think you may accidentally store results that you don't need, or that you underestimate the size of your output/intermediate variables.
Here is how I would proceed:
Turn on dbstop if error
Run the code till you get the out of memory error
See how much memory is being used (make sure to check all work spaces)
Probably you now know where the extra memory is going. If you don't find much memory being used, continue with this:
Check the memory command to see how much memory is still available
Carefully look at the line being executed, perhaps you actually need a huge amount of memory for it
If all else fails share your findings here and others can help you look for it.
The reason of memory usage growth is CPlex. I tried many alternatives but I couldn't find any other useful solution than increasing virtual memory to several hundred GBs. If you don't have special reasons to insist on CPlex (commercial usage, licensing etc.), I would suggest anyone, who encounter this problem, to use GUROBI. It is free and unlimited for academic usage, totally integrable with MATLAB. That's the solution I have found for my problem with Cplex. I hope this solution works for everybody.

MATLAB - Force quit (CTRL+C) not working?

I run a pretty computationally expensive genetic algorithm with MATLAB. The code has been running for 3 whole days, and I am pretty sure it gets stuck somewhere, because it is not printing out the progress information for debugging purpose.
I now wish to stop it. I did CTRL+C, but no luck. The bottom left of the window still displays "Busy".
I cannot simply quit the whole MATLAB, because I need to find out where it gets stuck by inspecting the variables in the variable window.
Given the CTRL+C is not working, how can I
stop the execution, OR
save the variables for inspection purpose?
Sometimes ctrl-C stops working if you have a memory over-allocation problem -- if you are trying to allocate a matrix that doesn't fit in memory, and so virtual memory begins thrashing.
It's also likely that crtl-C won't work while execution is passed to COMSOL.
I think you have little choice now but to kill matlab and try to debug by either stepping through the code or inserting fprintf statements.

Why does Matlab run faster after a script is "warmed up"?

I have noticed that the first time I run a script, it takes considerably more time than the second and third time1. The "warm-up" is mentioned in this question without an explanation.
Why does the code run faster after it is "warmed up"?
I don't clear all between calls2, but the input parameters change for every function call. Does anyone know why this is?
1. I have my license locally, so it's not a problem related to license checking.
2. Actually, the behavior doesn't change if I clear all.
One reason why it would run faster after the first time is that many things are initialized once, and their results are cached and reused the next time. For example in the M-side, variables can be defined as persistent in functions that can be locked. This can also occur on the MEX-side of things.
In addition many dependencies are loaded after the first time and remain so in memory to be re-used. This include M-functions, OOP classes, Java classes, MEX-functions, and so on. This applies to both builtin and user-defined ones.
For example issue the following command before and after running your script for the first run, then compare:
[M,X,C] = inmem('-completenames')
Note that clear all does not necessarily clear all of the above, not to mention locked functions...
Finally let us not forget the role of the accelerator. Instead of interpreting the M-code every time a function is invoked, it gets compiled into machine code instructions during runtime. JIT compilation occurs only for the first invocation, so ideally the efficiency of running object code the following times will overcome the overhead of re-interpreting the program every time it runs.
Matlab is interpreted. If you don't warm up the code, you will be losing a lot of time due to interpretation instead of the actual algorithm. This can skew results of timings significantly.
Running the code at least once will enable Matlab to actually compile appropriate code segments.
Besides Matlab-specific reasons like JIT-compilation, modern CPUs have large caches, branch predictors, and so on. Warming these up is an issue for benchmarking even in assembly language.
Also, more importantly, modern CPUs usually idle at low clock speed, and only jump to full speed after several milliseconds of sustained load.
Intel's Turbo feature gets even more funky: when power and thermal limits allow, the CPU can run faster than its sustainable max frequency. So the first ~20 seconds to 1 minute of your benchmark may run faster than the rest of it, if you aren't careful to control for these factors.
Another issue not mensioned by Amro and Marc is memory (pre)allocation.
If your script does not pre-allocate its memory it's first run would be very slow due to memory allocation. Once it completed its first iteration all memory is allocated, so consecutive invokations of the script would be more efficient.
An illustrative example
for ii = 1:1000
vec(ii) = ii; %// vec grows inside loop the first time this code is executed only
end