如何使用 ppc64le 和 x86 在不同版本的 pytorch(1.3.1 和 1.6.x)之间加载检查点?
正如我在此处概述的那样,由于硬件原因(例如使用 ppc64le IBM 架构),我只能使用旧版本的 pytorch 和 torchvision。
因此,我在不同的计算机、集群和我的个人 Mac 之间发送和接收检查点时遇到问题。我想知道是否有任何方法可以加载模型以避免此问题?例如,在使用 1.6.x 时,也许可以使用旧格式和新格式保存模型。当然,对于 1.3.1 到 1.6.x 来说是不可能的,但至少我希望有些方法可以奏效。
有什么建议吗?当然,我的理想解决方案是我不必担心它,并且我可以随时加载和保存我的检查点以及我通常在所有硬件上统一腌制的所有内容。
我收到的第一个错误是 zip jit 错误:
RuntimeError: /home/miranda9/data/f.pt is a zip archive (did you mean to use torch.jit.load()?)
所以我使用了它(和其他 pickle 库):
# %%
import torch
from pathlib import Path
def load(path):
import torch
import pickle
import dill
path = str(path)
try:
db = torch.load(path)
f = db['f']
except Exception as e:
db = torch.jit.load(path)
f = db['f']
#with open():
# db = pickle.load(open(path, "r+"))
# db = dill.load(open(path, "r+"))
#raise ValueError(f'FAILED: {e}')
return db, f
p = "~/data/f.pt"
path = Path(p).expanduser()
db, f = load(path)
Din, nb_examples = 1, 5
x = torch.distributions.Normal(loc=0.0, scale=1.0).sample(sample_shape=(nb_examples, Din))
y = f(x)
print(y)
print('Success!\a')
但我收到了不同 pytorch 版本的投诉,我被迫使用:
Traceback (most recent call last):
File "hal_pg.py", line 27, in <module>
db, f = load(path)
File "hal_pg.py", line 16, in load
db = torch.jit.load(path)
File "/home/miranda9/.conda/envs/wmlce-v1.7.0-py3.7/lib/python3.7/site-packages/torch/jit/__init__.py", line 239, in load
cpp_module = torch._C.import_ir_module(cu, f, map_location, _extra_files)
RuntimeError: version_number <= kMaxSupportedFileFormatVersion INTERNAL ASSERT FAILED at /opt/anaconda/conda-bld/pytorch-base_1581395437985/work/caffe2/serialize/inline_container.cc:131, please report a bug to PyTorch. Attempted to read a PyTorch file with version 3, but the maximum supported version for reading is 1. Your PyTorch installation may be too old. (init at /opt/anaconda/conda-bld/pytorch-base_1581395437985/work/caffe2/serialize/inline_container.cc:131)
frame #0: c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) + 0xbc (0x7fff7b527b9c in /home/miranda9/.conda/envs/wmlce-v1.7.0-py3.7/lib/python3.7/site-packages/torch/lib/libc10.so)
frame #1: caffe2::serialize::PyTorchStreamReader::init() + 0x1d98 (0x7fff1d293c78 in /home/miranda9/.conda/envs/wmlce-v1.7.0-py3.7/lib/python3.7/site-packages/torch/lib/libtorch.so)
frame #2: caffe2::serialize::PyTorchStreamReader::PyTorchStreamReader(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) + 0x88 (0x7fff1d2950d8 in /home/miranda9/.conda/envs/wmlce-v1.7.0-py3.7/lib/python3.7/site-packages/torch/lib/libtorch.so)
frame #3: torch::jit::import_ir_module(std::shared_ptr<torch::jit::script::CompilationUnit>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, c10::optional<c10::Device>, std::unordered_map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::hash<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::equal_to<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >&) + 0x64 (0x7fff1e624664 in /home/miranda9/.conda/envs/wmlce-v1.7.0-py3.7/lib/python3.7/site-packages/torch/lib/libtorch.so)
frame #4: <unknown function> + 0x70e210 (0x7fff7c0ae210 in /home/miranda9/.conda/envs/wmlce-v1.7.0-py3.7/lib/python3.7/site-packages/torch/lib/libtorch_python.so)
frame #5: <unknown function> + 0x28efc4 (0x7fff7bc2efc4 in /home/miranda9/.conda/envs/wmlce-v1.7.0-py3.7/lib/python3.7/site-packages/torch/lib/libtorch_python.so)
<omitting python frames>
frame #26: <unknown function> + 0x25280 (0x7fff84b35280 in /lib64/libc.so.6)
frame #27: __libc_start_main + 0xc4 (0x7fff84b35474 in /lib64/libc.so.6)
有什么想法可以让所有内容在集群中保持一致?我甚至无法打开 pickle 文件。
也许这对于我被迫使用的当前 pytorch 版本来说是不可能的 :(
RuntimeError: version_number <= kMaxSupportedFileFormatVersion INTERNAL ASSERT FAILED at /opt/anaconda/conda-bld/pytorch-base_1581395437985/work/caffe2/serialize/inline_container.cc:131, please report a bug to PyTorch. Attempted to read a PyTorch file with version 3, but the maximum supported version for reading is 1. Your PyTorch installation may be too old. (init at /opt/anaconda/conda-bld/pytorch-base_1581395437985/work/caffe2/serialize/inline_container.cc:131)
frame #0: c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) + 0xbc (0x7fff83ba7b9c in /home/miranda9/.conda/envs/automl-meta-learning_wmlce-v1.7.0-py3.7/lib/python3.7/site-packages/torch/lib/libc10.so)
frame #1: caffe2::serialize::PyTorchStreamReader::init() + 0x1d98 (0x7fff25993c78 in /home/miranda9/.conda/envs/automl-meta-learning_wmlce-v1.7.0-py3.7/lib/python3.7/site-packages/torch/lib/libtorch.so)
frame #2: caffe2::serialize::PyTorchStreamReader::PyTorchStreamReader(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) + 0x88 (0x7fff259950d8 in /home/miranda9/.conda/envs/automl-meta-learning_wmlce-v1.7.0-py3.7/lib/python3.7/site-packages/torch/lib/libtorch.so)
frame #3: torch::jit::import_ir_module(std::shared_ptr<torch::jit::script::CompilationUnit>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, c10::optional<c10::Device>, std::unordered_map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::hash<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::equal_to<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >&) + 0x64 (0x7fff26d24664 in /home/miranda9/.conda/envs/automl-meta-learning_wmlce-v1.7.0-py3.7/lib/python3.7/site-packages/torch/lib/libtorch.so)
frame #4: <unknown function> + 0x70e210 (0x7fff8472e210 in /home/miranda9/.conda/envs/automl-meta-learning_wmlce-v1.7.0-py3.7/lib/python3.7/site-packages/torch/lib/libtorch_python.so)
frame #5: <unknown function> + 0x28efc4 (0x7fff842aefc4 in /home/miranda9/.conda/envs/automl-meta-learning_wmlce-v1.7.0-py3.7/lib/python3.7/site-packages/torch/lib/libtorch_python.so)
<omitting python frames>
frame #23: <unknown function> + 0x25280 (0x7fff8d335280 in /lib64/libc.so.6)
frame #24: __libc_start_main + 0xc4 (0x7fff8d335474 in /lib64/libc.so.6)
使用代码:
from pathlib import Path
import torch
path = '/home/miranda9/data/dataset/'
path = Path(path).expanduser() / 'fi_db.pt'
path = str(path)
# db = torch.load(path)
# torch.jit.load(path)
db = torch.jit.load(str(path))
print(db)
相关链接:
- 如何使用 ppc64le 和 x86 在不同版本的 pytorch(1.3.1 和 1.6.x)中加载检查点?
- https://discuss.pytorch.org/t/how-to-load-checkpoints-across-different-versions-of-pytorch-1-3-1-and-1-6-x-using-ppc64le-and-x86/97829
- 相关 gitissue: https://github.com/pytorch/pytorch/issues/43766
- reddit: https://www.reddit.com/r/pytorch/comments/jvza7v/how_to_load_checkpoints_across_different_versions/
我相信开发人员的意图是传递一个标志以便将其保存为泡菜。只是默认的行为改变。
对于以前检查过的文件,在较新的环境中重新加载 zip 文件保存的权重(使用 pytorch>=1.6),然后再次将检查点作为 pickle(无需重新训练);
更新您的代码并从下次添加标志
We have switched torch.save to use a zip file-based format by default rather than the old Pickle-based format. torch.load has retained the ability to load the old format, but use of the new format is recommended. The new format is:
more friendly for inspection and building tooling for manipulating the save files fixes a long-standing issue wherein serialization ( getstate , setstate ) functions on Modules that depended on serialized Tensor values were getting the wrong data the same as the TorchScript serialization format, making serialization more consistent across PyTorch
用法如下:
m = MyMod()
torch.save(m.state_dict(), 'mymod.pt') # Saves a zipfile to mymod.pt
要使用旧格式,请传递标志
_use_new_zipfile_serialization=False
m = MyMod()
torch.save(m.state_dict(), 'mymod.pt', _use_new_zipfile_serialization=False) # Saves pickle
这不是一个理想的解决方案,但它适用于将检查点从较新版本转移到较旧版本。
我也使用 ppc64le 并面临同样的问题。可以将模型保存为文本格式,任何 PyTorch 版本都可以读取该格式。我在 ppc64le 机器上安装了 PyTorch v1.3.0,在我的笔记本电脑上安装了 v1.7.0(不需要显卡)。
步骤 1. 通过较新的 PyTorch 版本保存模型
def save_model_txt(model, path):
fout = open(path, 'w')
for k, v in model.state_dict().items():
fout.write(str(k) + '\n')
fout.write(str(v.tolist()) + '\n')
fout.close()
保存之前,我像这样加载模型
checkpoint = torch.load(path, map_location=torch.device('cpu'))
model.load_state_dict(checkpoint, strict=False)
步骤 2. 传输文本文件
步骤 3. 在旧 PyTorch 中加载文本文件
def load_model_txt(model, path):
data_dict = {}
fin = open(path, 'r')
i = 0
odd = 1
prev_key = None
while True:
s = fin.readline().strip()
if not s:
break
if odd:
prev_key = s
else:
print('Iter', i)
val = eval(s)
if type(val) != type([]):
data_dict[prev_key] = torch.FloatTensor([eval(s)])[0]
else:
data_dict[prev_key] = torch.FloatTensor(eval(s))
i += 1
odd = (odd + 1) % 2
# Replace existing values with loaded
print('Loading...')
own_state = model.state_dict()
print('Items:', len(own_state.items()))
for k, v in data_dict.items():
if not k in own_state:
print('Parameter', k, 'not found in own_state!!!')
else:
try:
own_state[k].copy_(v)
except:
print('Key:', k)
print('Old:', own_state[k])
print('New:', v)
sys.exit(0)
print('Model loaded')
加载前必须初始化模型。空模型被传递到函数中。
限制
如果您的模型 state_dict 包含除 (str: torch.Tensor) 值以外的其他内容,则此方法将不起作用。您可以使用
for k, v in model.state_dict().items():
...
检查您的 state_dict 内容>
阅读这些内容以加深理解:
https://pytorch.org/tutorials/recipes/recipes/saving_and_loading_models_for_inference.html
https://discuss.pytorch.org/t/how-to-load-part-of-pre-trained-model/1113
基于@maxim velikanov的回答,我创建了一个单独的OrderedDict,其中的键与模型的原始状态字典相同,但每个张量值都转换为列表。
此OrderedDict被转储到JSON文件中。
def save_model_json(model, path):
actual_dict = OrderedDict()
for k, v in model.state_dict().items():
actual_dict[k] = v.tolist()
with open(path, 'w') as f:
json.dump(actual_dict, f)
然后,加载器可以将文件加载为JSON,并且每个列表/整数将转换回张量,然后将其值复制到原始状态字典中。
def load_model_json(model, path):
data_dict = OrderedDict()
with open(path, 'r') as f:
data_dict = json.load(f)
own_state = model.state_dict()
for k, v in data_dict.items():
print('Loading parameter:', k)
if not k in own_state:
print('Parameter', k, 'not found in own_state!!!')
if type(v) == list or type(v) == int:
v = torch.tensor(v)
own_state[k].copy_(v)
model.load_state_dict(own_state)
print('Model loaded')