Skip to content
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

Memory usage steadily increasing when using back propagation with sparse CSR parameter matrices on CPU #109445

Open
julius-frenzel opened this issue Sep 16, 2023 · 5 comments
Labels
module: memory usage PyTorch is using more memory than it should, or it is leaking memory module: sparse Related to torch.sparse triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Comments

@julius-frenzel
Copy link

julius-frenzel commented Sep 16, 2023

🐛 Description of the Bug

I encountered steadily increasing RAM usage when using back propagation with sparse CSR matrices on CPU. Below is the reduced code, which for me produces this behavior. As you can see, I was trying to train an RNN network with sparse parameter matrices (then they were actually sparse). When running this code with the non-working line RAM usage keeps increasing at a rate of about 100 MB/s on my machine.

import torch

class my_net(torch.nn.Module):
    def __init__(self):
        super(my_net, self).__init__()
        #self.A = torch.nn.Parameter(torch.rand(100, 100))                  # works
        #self.A = torch.nn.Parameter(torch.rand(100, 100).to_sparse_coo())  # works
        self.A = torch.nn.Parameter(torch.rand(100, 100).to_sparse_csr())   # doesn't work
        self.B = torch.nn.Parameter(torch.rand(1, 100))

    def forward(self, u, state): # u not used for simplicity
        state = torch.sparse.mm(self.A, state)
        y = torch.sparse.mm(self.B, state)
        return state, y

rnn_net = my_net()

for epoch in range(1000000):
    print(f"epoch {epoch}")

    rnn_net.zero_grad()
    state = torch.zeros(100,1)
    for ii in range(2):
        state, output = rnn_net.forward(torch.tensor([[0]]), state)
    output.backward()

Notably when using a dense or sparse COO layout, it works just fine. I tried some possible solutions, like manual garbage collection and detaching the state and output variables from the computational graph in the outer loop. Nothing short of using detach() on the state in the inner loop worked for me, which obviously would defeat the purpose of an RNN. I therefore concluded that this likely is unintended behavior.

My setup is in no way special. I just installed PyTorch using pip and ran my code.

Versions

PyTorch version: 2.0.1+cu117
Is debug build: False
CUDA used to build PyTorch: 11.7
ROCM used to build PyTorch: N/A

OS: Linux Mint 21.2 (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: 14.0.0-1ubuntu1.1
CMake version: version 3.27.0
Libc version: glibc-2.35

Python version: 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-83-generic-x86_64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Address sizes: 39 bits physical, 48 bits virtual
Byte Order: Little Endian
CPU(s): 8
On-line CPU(s) list: 0-7
Vendor ID: GenuineIntel
Model name: Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz
CPU family: 6
Model: 142
Thread(s) per core: 2
Core(s) per socket: 4
Socket(s): 1
Stepping: 10
CPU max MHz: 3400,0000
CPU min MHz: 400,0000
BogoMIPS: 3600.00
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust sgx bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp md_clear flush_l1d arch_capabilities
Virtualisation: VT-x
L1d cache: 128 KiB (4 instances)
L1i cache: 128 KiB (4 instances)
L2 cache: 1 MiB (4 instances)
L3 cache: 6 MiB (1 instance)
NUMA node(s): 1
NUMA node0 CPU(s): 0-7
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit: KVM: Mitigation: VMX disabled
Vulnerability L1tf: Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown: Mitigation; PTI
Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed: Mitigation; IBRS
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2: Mitigation; IBRS, IBPB conditional, STIBP conditional, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds: Mitigation; Microcode
Vulnerability Tsx async abort: Not affected

Versions of relevant libraries:
[pip3] flake8==6.0.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.21.5
[pip3] numpydoc==1.5.0
[pip3] pytorch-ranger==0.1.1
[pip3] torch==2.0.1
[pip3] torchsparsegradutils==0.1.2
[pip3] torchvision==0.15.2
[pip3] triton==2.0.0
[conda] No relevant packages

cc @alexsamardzic @nikitaved @pearu @cpuhrsch @amjames @bhosmer

@julius-frenzel julius-frenzel changed the title Memory increasing when using back propagation with sparse CSR parameter matrices on CPU Memory usage steadily increasing when using back propagation with sparse CSR parameter matrices on CPU Sep 16, 2023
@malfet malfet added module: sparse Related to torch.sparse module: memory usage PyTorch is using more memory than it should, or it is leaking memory triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Sep 19, 2023
@cpuhrsch
Copy link
Contributor

Hello @julius-frenzel, thank you for submitting the issue. Does this persist with the most recent nightly?

Thank you

@julius-frenzel
Copy link
Author

julius-frenzel commented Sep 19, 2023

Hello, thanks for the reply.
I ran the above code with the nightly build and the issue has remained unchanged.
To make sure I used the right version I first uninstalled torch using pip and then reinstalled with the command from the link you provided.

pip3 install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cpu

Regards

Julius

@julius-frenzel
Copy link
Author

julius-frenzel commented Sep 30, 2023

I did some more experimentation and found that the problem only occurs when using torch.sparse.mm(). It goes away when using torch.mm(), which isn't very useful in this case as it leads to dense gradients.
Putting the forward method in a different thread also leads to the memory being freed properly, whenever it returns. However this approach is very inefficient, since sparse CSR tensors currently can't be shared between threads.

@julius-frenzel
Copy link
Author

Just wanted to confirm that the problem persists with version 2.2.1.
Using sparse_mm from torchsparsegradutils also doesn't change anything.
It's a shame, because the CSR layout seems to be so much more efficient than the COO layout for matrix multiplication.

@braydenyip
Copy link

braydenyip commented Jun 21, 2024

I've been doing a similar thing and it's resulting in a segfault actually -- I pass sparse.mm two CSR tensors and it simply leads to a segfault, no other context. In my case, the tensors are big enough that they would probably cause an out of memory error if they were accidentally being duplicated or something like that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
module: memory usage PyTorch is using more memory than it should, or it is leaking memory module: sparse Related to torch.sparse triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module
Projects
None yet
Development

No branches or pull requests

4 participants