How can i save immediate tensors to a file which I wish to use out of the code?

I have been getting device asserted error, and I wish to inspect the variables before it throws error. So, is there any good way to store tensors and reuse with numpy.



isn’t that to save model and dictionary? I just wish to save 2 variable tensors, should be able to get by numpy as well.

You can use on a tensor as well.


this may help.

import datetime as dt
import sys

import torch
import pickle as pkl

print(10 * "=")
print("Python version: {}".format(sys.version))
print("Pytorch version: {}".format(torch.__version__))
print("Pickle version: {}".format(pkl.format_version))
print(10 * "=")


d = 100
tensor = torch.rand((d, d))
print("Tensor size: {}".format(tensor.shape))

# Store
t0 =, "")
print("Torch save-time: {}".format( - t0))

t0 =
with open("tensor-pickle.pkl", "wb") as fout:
    pkl.dump(tensor, fout, protocol=pkl.HIGHEST_PROTOCOL)
print("Pickle save-time: {}".format( - t0))

# Read
t0 =
tensorx = torch.load("")
print("Torch load-time: {}".format( - t0))

t0 =
with open("tensor-pickle.pkl", "rb") as fout:
    tensor_pkl = pkl.load(fout)
print("Pickle load-time: {}".format( - t0))


Python version: 3.7.0 | packaged by conda-forge | (default, Nov 12 2018, 20:15:55) 
[GCC 7.3.0]
Pytorch version: 1.3.0+cu100
Pickle version: 4.0

small tensor: (100, 100)

Tensor size: torch.Size([100, 100])
Torch save-time: 0:00:00.002519
Pickle save-time: 0:00:00.002136
Torch load-time: 0:00:00.000512
Pickle load-time: 0:00:00.000347

larg tensor: (10^4, 10^4)

Tensor size: torch.Size([10000, 10000])
Torch save-time: 0:00:04.070195
Pickle save-time: 0:00:04.018530
Torch load-time: 0:00:03.638956
Pickle load-time: 0:00:05.501440