I have problem with clear GPU memory
Show older comments
After executing this code, the GPU memory is use by 2 GB. Only the D matrix in GPU memory...
A=fix(gpuArray(rand(1,1000))*99)+1;
B=fix(gpuArray(rand(1,1000))*99)+1;
C=gpuArray(rand(100000,100));
E=C(:,A);
F=C(:,B);
D=E.*F;
clear E F C A B
However, if I execute this code.
D=gpuArray(rand(100000,1000));
There we see D matrix (same size) in GPU memory, but now it only use 1 GB of GPU memory. Why is there a difference? and how to clear the memory in the first variant?
2 Comments
Raymond Norris
on 29 Oct 2020
Hi Vitaly,
I don't have a GPU at my disposal. Your code, A..D, consumes 2.37 GB. D alone is 763 MB. So I think that aligns with what you're seeing, except I'm not sure why you think only D is in the GPU memory.
Have you called reset to clear the GPU?
reset(gpuDevice)
Are you using nvidia-smi to check if the memory goes up and down?
Raymond
Vitaly Bur
on 30 Oct 2020
Edited: Vitaly Bur
on 30 Oct 2020
Answers (1)
Joss Knight
on 2 Nov 2020
2 votes
MATLAB does not clear all GPU memory unless all variables are released because allocating memory is a performance bottleneck. So MATLAB instead pools memory for later allocations.
To force the GPU to release all memory, you can call reset(gpuDevice).
7 Comments
Vitaly Bur
on 2 Nov 2020
Joss Knight
on 2 Nov 2020
Edited: Joss Knight
on 2 Nov 2020
You can force MATLAB to stop pooling memory with this feature command:
feature('GpuAllocPoolSizeKb',0);
Vitaly Bur
on 2 Nov 2020
Edited: Vitaly Bur
on 2 Nov 2020
Joss Knight
on 2 Nov 2020
What does the red arrow represent? You calling clear E F C A B?
Vitaly Bur
on 2 Nov 2020
Joss Knight
on 2 Nov 2020
Oh I see now. This is just because D hasn't been evaluated yet, which means E and F are still being held in memory, as is C because E and F are just slices of C which means it's being held in memory until we attempt to modify them. We use a lazy evaluation optimization and you haven't actually required D to be used or displayed. Insert gather(D) or wait(gpu) to force evaluation, and the memory will be freed.
Vitaly Bur
on 2 Nov 2020
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


