Write tensor to .t7 file

I am using a simple image classification example for my code.I would like to extract the tensor values in the net.state_dict(). So far, I am able to extract the keys and the values separately using .keys and .values.I would like to write these values to a .t7 file. Is it possible to do the same with torch .save, such that it can be loaded later on to get the key value.

You could store the state_dict directly or alternatively wrap the odict_keys and odict_values into lists and store them:

model = nn.Linear(1, 1)
sd = model.state_dict()

torch.save(list(sd.keys()), 'tmp1.pth') # use list, otherwise: TypeError: can't pickle odict_keys objects
torch.save(list(sd.values()), 'tmp2.pth')

Let me know, if I misunderstood your use case.

@ptrblck
Thank you for the reply.
I saved the state dictionary values into files with their names as the respective keys.
I would like to know if there is any way to know the structure of a respective file to get the values of the weights and biases in binary;

torch.save uses pickle by default as seen here, so you could probably use io.BytesIO to read the file, but I haven’t tested it. :wink: