解决方法
这是一个在保存时不会失败的修补版本:
from keras.layers import Lambda, concatenate
from keras import Model
import tensorflow as tf
def multi_gpu_model(model, gpus):
if isinstance(gpus, (list, tuple)):
num_gpus = len(gpus)
target_gpu_ids = gpus
else:
num_gpus = gpus
target_gpu_ids = range(num_gpus)
def get_slice(data, i, parts):
shape = tf.shape(data)
batch_size = shape[:1]
input_shape = shape[1:]
step = batch_size // parts
if i == num_gpus - 1:
size = batch_size - step * i
else:
size = step
size = tf.concat([size, input_shape], axis=0)
stride = tf.concat([step, input_shape * 0], axis=0)
start = stride * i
return tf.slice(data, start, size)
all_outputs = []
for i in range(len(model.outputs)):
all_outputs.append([])
# Place a copy of the model on each GPU,
# each getting a slice of the inputs.
for i, gpu_id in enumerate(target_gpu_ids):
with tf.device('/gpu:%d' % gpu_id):
with tf.name_scope('replica_%d' % gpu_id):
inputs = []
# Retrieve a slice of the input.
for x in model.inputs:
input_shape = tuple(x.get_shape().as_list())[1:]
slice_i = Lambda(get_slice,
output_shape=input_shape,
arguments={'i': i,
'parts': num_gpus})(x)
inputs.append(slice_i)
# Apply model on slice
# (creating a model replica on the target device).
outputs = model(inputs)
if not isinstance(outputs, list):
outputs = [outputs]
# Save the outputs for merging back together later.
for o in range(len(outputs)):
all_outputs[o].append(outputs[o])
# Merge outputs on CPU.
with tf.device('/cpu:0'):
merged = []
for name, outputs in zip(model.output_names, all_outputs):
merged.append(concatenate(outputs,
axis=0, name=name))
return Model(model.inputs, merged)
您可以使用这个multi_gpu_model 函数,直到在 keras 中修复该错误。另外,在加载模型时,提供 tensorflow 模块对象很重要:
model = load_model('multi_gpu_model.h5', {'tf': tf})
工作原理
问题在于import tensorflow 位于multi_gpu_model 中间的行:
def multi_gpu_model(model, gpus):
...
import tensorflow as tf
...
这会为get_slice lambda 函数创建一个闭包,其中包括 gpus(可以)和 tensorflow 模块(不可以)的数量。模型保存尝试序列化所有层,包括调用 get_slice 的层,但由于 tf 在闭包中而失败。
解决方案是将导入移出multi_gpu_model,以便tf 成为一个全局对象,尽管get_slice 仍然需要它才能工作。这解决了保存问题,但在加载时必须明确提供tf。