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

[ONNX] Reduce exporter memory usage by removing intermediate values #101148

Conversation

ilyasher
Copy link
Contributor

This commit reduces the exporter memory usage by as much as 50%. During the shape inference step, the exporter caches the values of intermediate tensors in a ConstantValueMap. This can use as much memory as the model itself, or even more. For example, model weight tensors are often fed to a Transpose layer, and the output of that is the same size of the weights. This commit fixes the issue by removing the intermediate tensor values after they are used by all consumers.

The cached values are only used for shape inference, so removing them after use should be safe. ConstantValueMap is cleared anyways once shape inference is complete for the entire graph.

As an example, here is the model from issue #61263:

import torch
import math

# Size in GB
tensor_size = 1 
model_size = 8

layers_num = model_size // tensor_size
kB = 1024
MB = kB * kB
GB = MB * kB
precision_size = 4 # bytes per float
activation_size = math.floor(math.sqrt(tensor_size * GB / precision_size))

class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        for i in range(layers_num):
            name = "fc_%d" % i
            linear = torch.nn.Linear(activation_size, activation_size)
            setattr(self, name, linear)
    def forward(self, x):
        for i in range(layers_num):
            name = "fc_%d" % i
            linear = getattr(self, name)
            x = linear(x)
        return x

model = Net().cuda()
input = torch.zeros(activation_size, requires_grad=True).cuda()
with torch.no_grad():
    torch.onnx.export(model, (input, ), './model_large.onnx', do_constant_folding=False, opset_version=13)

It is just some large linear layers stacked together. Before this commit, my max GPU usage during export was about 16.7 GB, twice the model size. With this commit in combination with #101134, it was only about 9.5 GB.

Together with #101134, fixes issue #61263

@pytorch-bot pytorch-bot bot added the release notes: onnx torch.onnx related changes that should show up in the release notes label May 11, 2023
@pytorch-bot
Copy link

pytorch-bot bot commented May 11, 2023

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/101148

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 35b26fd:
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@mikaylagawarecki mikaylagawarecki added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label May 11, 2023
@ilyasher ilyasher force-pushed the dev-isherstyuk-onnx-reduce-memory-usage branch from f6c2ba5 to f3da754 Compare May 12, 2023 20:33
@BowenBao BowenBao added the topic: performance topic category label May 20, 2023
@ilyasher
Copy link
Contributor Author

@pytorchbot rebase

@pytorchmergebot
Copy link
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

This commit reduces the exporter memory usage by as much as 50%.
During the shape inference step, the exporter caches the values
of intermediate tensors. This can use as much memory as the model
itself, or even more. For example, model weight tensors are often
fed to a Transpose layer, and the output of that is the same size
of the weights. This commit fixes the issue by removing the
intermediate tensor values after they are used by all consumers.
@pytorchmergebot
Copy link
Collaborator

Successfully rebased dev-isherstyuk-onnx-reduce-memory-usage onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout dev-isherstyuk-onnx-reduce-memory-usage && git pull --rebase)

@pytorchmergebot pytorchmergebot force-pushed the dev-isherstyuk-onnx-reduce-memory-usage branch from f3da754 to 35b26fd Compare May 30, 2023 22:07
@ilyasher
Copy link
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot bot added the ciflow/trunk Trigger trunk jobs on your pull request label May 31, 2023
@pytorchmergebot
Copy link
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

shaoyf42 pushed a commit to shaoyf42/pytorch that referenced this pull request Jun 1, 2023
…ytorch#101148)

This commit reduces the exporter memory usage by as much as 50%. During the shape inference step, the exporter caches the values of intermediate tensors in a `ConstantValueMap`. This can use as much memory as the model itself, or even more. For example, model weight tensors are often fed to a Transpose layer, and the output of that is the same size of the weights. This commit fixes the issue by removing the intermediate tensor values after they are used by all consumers.

The cached values are only used for shape inference, so removing them after use should be safe. `ConstantValueMap` is cleared anyways once shape inference is complete for the entire graph.

As an example, here is the model from issue pytorch#61263:
```python
import torch
import math

# Size in GB
tensor_size = 1
model_size = 8

layers_num = model_size // tensor_size
kB = 1024
MB = kB * kB
GB = MB * kB
precision_size = 4 # bytes per float
activation_size = math.floor(math.sqrt(tensor_size * GB / precision_size))

class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        for i in range(layers_num):
            name = "fc_%d" % i
            linear = torch.nn.Linear(activation_size, activation_size)
            setattr(self, name, linear)
    def forward(self, x):
        for i in range(layers_num):
            name = "fc_%d" % i
            linear = getattr(self, name)
            x = linear(x)
        return x

model = Net().cuda()
input = torch.zeros(activation_size, requires_grad=True).cuda()
with torch.no_grad():
    torch.onnx.export(model, (input, ), './model_large.onnx', do_constant_folding=False, opset_version=13)
```
It is just some large linear layers stacked together. Before this commit, my max GPU usage during export was about 16.7 GB, twice the model size. With this commit in combination with pytorch#101134, it was only about 9.5 GB.

Together with pytorch#101134, fixes issue pytorch#61263

Pull Request resolved: pytorch#101148
Approved by: https://github.com/BowenBao
alimoezzi pushed a commit to alimoezzi/pytorch that referenced this pull request Jun 3, 2023
…ytorch#101148)

This commit reduces the exporter memory usage by as much as 50%. During the shape inference step, the exporter caches the values of intermediate tensors in a `ConstantValueMap`. This can use as much memory as the model itself, or even more. For example, model weight tensors are often fed to a Transpose layer, and the output of that is the same size of the weights. This commit fixes the issue by removing the intermediate tensor values after they are used by all consumers.

The cached values are only used for shape inference, so removing them after use should be safe. `ConstantValueMap` is cleared anyways once shape inference is complete for the entire graph.

As an example, here is the model from issue pytorch#61263:
```python
import torch
import math

# Size in GB
tensor_size = 1
model_size = 8

layers_num = model_size // tensor_size
kB = 1024
MB = kB * kB
GB = MB * kB
precision_size = 4 # bytes per float
activation_size = math.floor(math.sqrt(tensor_size * GB / precision_size))

class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        for i in range(layers_num):
            name = "fc_%d" % i
            linear = torch.nn.Linear(activation_size, activation_size)
            setattr(self, name, linear)
    def forward(self, x):
        for i in range(layers_num):
            name = "fc_%d" % i
            linear = getattr(self, name)
            x = linear(x)
        return x

model = Net().cuda()
input = torch.zeros(activation_size, requires_grad=True).cuda()
with torch.no_grad():
    torch.onnx.export(model, (input, ), './model_large.onnx', do_constant_folding=False, opset_version=13)
```
It is just some large linear layers stacked together. Before this commit, my max GPU usage during export was about 16.7 GB, twice the model size. With this commit in combination with pytorch#101134, it was only about 9.5 GB.

Together with pytorch#101134, fixes issue pytorch#61263

Pull Request resolved: pytorch#101148
Approved by: https://github.com/BowenBao
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: onnx torch.onnx related changes that should show up in the release notes topic: performance topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

5 participants