提交 73830eb2 编写于 作者: J jiangjiajun

modify code format

上级 0edcc783
...@@ -5,12 +5,14 @@ model_dir = sys.argv[1] ...@@ -5,12 +5,14 @@ model_dir = sys.argv[1]
new_model_dir = sys.argv[2] new_model_dir = sys.argv[2]
exe = fluid.Executor(fluid.CPUPlace()) exe = fluid.Executor(fluid.CPUPlace())
[inference_program, feed_target_names, [inference_program, feed_target_names,
fetch_targets] = fluid.io.load_inference_model(dirname=model_dir, executor=exe) fetch_targets] = fluid.io.load_inference_model(
dirname=model_dir, executor=exe)
print(feed_target_names) print(feed_target_names)
fluid.io.save_inference_model(dirname=new_model_dir, fluid.io.save_inference_model(
feeded_var_names=feed_target_names, dirname=new_model_dir,
target_vars=fetch_targets, feeded_var_names=feed_target_names,
executor=exe, target_vars=fetch_targets,
main_program=inference_program, executor=exe,
params_filename="__params__") main_program=inference_program,
params_filename="__params__")
...@@ -46,8 +46,8 @@ class Layer(object): ...@@ -46,8 +46,8 @@ class Layer(object):
for input in self.inputs: for input in self.inputs:
if isinstance(input, GraphNode): if isinstance(input, GraphNode):
if hasattr(input, "index"): if hasattr(input, "index"):
in_list += (input.layer_name + in_list += (input.layer_name + "[{}]".format(
"[{}]".format(input.index) + ", ") input.index) + ", ")
else: else:
in_list += (input.layer_name + ", ") in_list += (input.layer_name + ", ")
elif isinstance(input, six.string_types): elif isinstance(input, six.string_types):
...@@ -71,8 +71,8 @@ class Layer(object): ...@@ -71,8 +71,8 @@ class Layer(object):
layer_code = layer_code + key + "={}, ".format(input) layer_code = layer_code + key + "={}, ".format(input)
elif isinstance(self.inputs, GraphNode): elif isinstance(self.inputs, GraphNode):
if hasattr(self.inputs, "index"): if hasattr(self.inputs, "index"):
layer_code += (self.inputs.layer_name + layer_code += (
"[{}]".format(self.inputs.index)) self.inputs.layer_name + "[{}]".format(self.inputs.index))
else: else:
layer_code += (self.inputs.layer_name) layer_code += (self.inputs.layer_name)
if self.op != "=": if self.op != "=":
......
...@@ -64,10 +64,8 @@ def run_net(param_dir="./"): ...@@ -64,10 +64,8 @@ def run_net(param_dir="./"):
b = os.path.exists(os.path.join(param_dir, var.name)) b = os.path.exists(os.path.join(param_dir, var.name))
return b return b
fluid.io.load_vars(exe, fluid.io.load_vars(
param_dir, exe, param_dir, fluid.default_main_program(), predicate=if_exist)
fluid.default_main_program(),
predicate=if_exist)
class OpMapper(object): class OpMapper(object):
...@@ -98,8 +96,8 @@ class OpMapper(object): ...@@ -98,8 +96,8 @@ class OpMapper(object):
def add_codes(self, codes, indent=0): def add_codes(self, codes, indent=0):
if isinstance(codes, list): if isinstance(codes, list):
for code in codes: for code in codes:
self.paddle_codes += (self.tab * indent + code.strip('\n') + self.paddle_codes += (
'\n') self.tab * indent + code.strip('\n') + '\n')
elif isinstance(codes, str): elif isinstance(codes, str):
self.paddle_codes += (self.tab * indent + codes.strip('\n') + '\n') self.paddle_codes += (self.tab * indent + codes.strip('\n') + '\n')
else: else:
...@@ -135,24 +133,25 @@ class OpMapper(object): ...@@ -135,24 +133,25 @@ class OpMapper(object):
os.path.join(os.path.join(py_code_dir, var.name))) os.path.join(os.path.join(py_code_dir, var.name)))
return b return b
fluid.io.load_vars(exe, fluid.io.load_vars(
py_code_dir, exe,
fluid.default_main_program(), py_code_dir,
predicate=if_exist) fluid.default_main_program(),
predicate=if_exist)
if params_merge: if params_merge:
fluid.io.save_inference_model(dirname=os.path.join( fluid.io.save_inference_model(
save_dir, "inference_model"), dirname=os.path.join(save_dir, "inference_model"),
feeded_var_names=input_names, feeded_var_names=input_names,
target_vars=outputs, target_vars=outputs,
executor=exe, executor=exe,
params_filename="__params__") params_filename="__params__")
else: else:
fluid.io.save_inference_model(dirname=os.path.join( fluid.io.save_inference_model(
save_dir, "inference_model"), dirname=os.path.join(save_dir, "inference_model"),
feeded_var_names=input_names, feeded_var_names=input_names,
target_vars=outputs, target_vars=outputs,
executor=exe, executor=exe,
params_filename=None) params_filename=None)
except: except:
raise Exception( raise Exception(
"Paddle code was saved in {}/model.py, but seems there's wrong exist, please check model.py manually." "Paddle code was saved in {}/model.py, but seems there's wrong exist, please check model.py manually."
......
...@@ -34,8 +34,8 @@ class CaffeResolver(object): ...@@ -34,8 +34,8 @@ class CaffeResolver(object):
if not os.path.isfile(self.caffe_proto): if not os.path.isfile(self.caffe_proto):
raise Exception( raise Exception(
"The .py file compiled by caffe.proto is not exist.") "The .py file compiled by caffe.proto is not exist.")
(filepath, (filepath, tempfilename) = os.path.split(
tempfilename) = os.path.split(os.path.abspath(self.caffe_proto)) os.path.abspath(self.caffe_proto))
(filename, extension) = os.path.splitext(tempfilename) (filename, extension) = os.path.splitext(tempfilename)
sys.path.append(filepath) sys.path.append(filepath)
out = __import__(filename) out = __import__(filename)
...@@ -49,13 +49,13 @@ class CaffeResolver(object): ...@@ -49,13 +49,13 @@ class CaffeResolver(object):
class CaffeGraphNode(GraphNode): class CaffeGraphNode(GraphNode):
def __init__(self, layer, type_str, layer_name=None): def __init__(self, layer, type_str, layer_name=None):
if layer_name is None: if layer_name is None:
super(CaffeGraphNode, super(CaffeGraphNode, self).__init__(
self).__init__(layer, layer,
layer.name.replace('/', '_').replace('-', '_')) layer.name.replace('/', '_').replace('-', '_'))
else: else:
super(CaffeGraphNode, super(CaffeGraphNode, self).__init__(
self).__init__(layer, layer,
layer_name.replace('/', '_').replace('-', '_')) layer_name.replace('/', '_').replace('-', '_'))
self.layer_type = type_str self.layer_type = type_str
self.fluid_code = FluidCode() self.fluid_code = FluidCode()
self.data = None self.data = None
...@@ -268,8 +268,8 @@ class CaffeDecoder(object): ...@@ -268,8 +268,8 @@ class CaffeDecoder(object):
c_i = blob.channels c_i = blob.channels
h = blob.height h = blob.height
w = blob.width w = blob.width
data = np.asarray(list(blob.data), data = np.asarray(
dtype=np.float32).reshape(c_o, c_i, h, w) list(blob.data), dtype=np.float32).reshape(c_o, c_i, h, w)
transformed.append(data) transformed.append(data)
return transformed return transformed
此差异已折叠。
...@@ -71,9 +71,8 @@ class ONNXGraphNode(GraphNode): ...@@ -71,9 +71,8 @@ class ONNXGraphNode(GraphNode):
if attr.type == onnx.AttributeProto.TENSOR: if attr.type == onnx.AttributeProto.TENSOR:
dtype = np.dtype(TENSOR_TYPE_TO_NP_TYPE[attr.t.data_type]) dtype = np.dtype(TENSOR_TYPE_TO_NP_TYPE[attr.t.data_type])
data = attr.t.raw_data data = attr.t.raw_data
value = np.frombuffer(data, value = np.frombuffer(
dtype=dtype, data, dtype=dtype, count=(len(data) // dtype.itemsize))
count=(len(data) // dtype.itemsize))
elif attr.type == onnx.AttributeProto.STRING: elif attr.type == onnx.AttributeProto.STRING:
value = attr.s value = attr.s
value = value.decode() if isinstance(value, bytes) else value value = value.decode() if isinstance(value, bytes) else value
...@@ -205,9 +204,8 @@ class ONNXGraph(Graph): ...@@ -205,9 +204,8 @@ class ONNXGraph(Graph):
self.node_map[name].weight = weight self.node_map[name].weight = weight
self.node_map[name].embeded_as = [] self.node_map[name].embeded_as = []
else: else:
self.node_map[name] = ONNXGraphDataNode(initializer, self.node_map[name] = ONNXGraphDataNode(
layer_name=name, initializer, layer_name=name, is_global_input=False)
is_global_input=False)
self.node_map[name].weight = weight self.node_map[name].weight = weight
self.node_map[name].embeded_as = [] self.node_map[name].embeded_as = []
......
...@@ -120,13 +120,13 @@ class TFGraph(Graph): ...@@ -120,13 +120,13 @@ class TFGraph(Graph):
def build(self): def build(self):
for layer in self.model.node: for layer in self.model.node:
self.node_map[layer.name.replace('/', '_').replace( self.node_map[layer.name.replace('/', '_').replace(
'-', '_')] = TFGraphNode(layer, data_format=self.tf_data_format) '-', '_')] = TFGraphNode(
layer, data_format=self.tf_data_format)
for layer_name, node in self.node_map.items(): for layer_name, node in self.node_map.items():
for in_node in node.layer.input: for in_node in node.layer.input:
in_node = in_node.replace('/', in_node = in_node.replace('/', '_').replace('-', '_').replace(
'_').replace('-', '^', '')
'_').replace('^', '')
if in_node not in self.node_map: if in_node not in self.node_map:
if in_node.strip().split(':')[0] in self.node_map: if in_node.strip().split(':')[0] in self.node_map:
self.connect(in_node.strip().split(':')[0], layer_name) self.connect(in_node.strip().split(':')[0], layer_name)
...@@ -390,10 +390,10 @@ class TFDecoder(object): ...@@ -390,10 +390,10 @@ class TFDecoder(object):
shape=shape, shape=shape,
name="x2paddle_{}".format(layer.name)) name="x2paddle_{}".format(layer.name))
except: except:
x2paddle_input = tf.placeholder(dtype=dtype, x2paddle_input = tf.placeholder(
shape=shape, dtype=dtype,
name="x2paddle_{}".format( shape=shape,
layer.name)) name="x2paddle_{}".format(layer.name))
input_map["{}:0".format(layer.name)] = x2paddle_input input_map["{}:0".format(layer.name)] = x2paddle_input
if shape.count(None) > 0: if shape.count(None) > 0:
......
...@@ -120,18 +120,19 @@ def convolutiondepthwise_layer(inputs, ...@@ -120,18 +120,19 @@ def convolutiondepthwise_layer(inputs,
dila_len) dila_len)
c_in = input_shape[0][1] c_in = input_shape[0][1]
c_out = num_output if num_output is not None else input_shape[0][1] c_out = num_output if num_output is not None else input_shape[0][1]
group = int(c_in / (c_in / c_out)) if c_in > c_out else int(c_in / group = int(c_in / (c_in / c_out)) if c_in > c_out else int(
(c_out / c_in)) c_in / (c_out / c_in))
out = fluid.layers.conv2d(input, out = fluid.layers.conv2d(
dilation=[dila_h, dila_w], input,
filter_size=[k_h, k_w], dilation=[dila_h, dila_w],
stride=[s_h, s_w], filter_size=[k_h, k_w],
padding=[p_h, p_w], stride=[s_h, s_w],
groups=group, padding=[p_h, p_w],
num_filters=c_out, groups=group,
param_attr=name + '_weights', num_filters=c_out,
bias_attr=name + '_bias', param_attr=name + '_weights',
name=name) bias_attr=name + '_bias',
name=name)
return out return out
...@@ -142,7 +143,8 @@ def convolutiondepthwise_weights(name, data=None): ...@@ -142,7 +143,8 @@ def convolutiondepthwise_weights(name, data=None):
return weights_name return weights_name
register(kind='ConvolutionDepthwise', register(
shape=convolutiondepthwise_shape, kind='ConvolutionDepthwise',
layer=convolutiondepthwise_layer, shape=convolutiondepthwise_shape,
weights=convolutiondepthwise_weights) layer=convolutiondepthwise_layer,
weights=convolutiondepthwise_weights)
...@@ -37,8 +37,8 @@ def detectionoutput_layer(inputs, ...@@ -37,8 +37,8 @@ def detectionoutput_layer(inputs,
pbv = fluid.layers.reshape(x=pbv, shape=[-1, 4]) pbv = fluid.layers.reshape(x=pbv, shape=[-1, 4])
mbox_loc = inputs[0] mbox_loc = inputs[0]
mbox_loc = fluid.layers.reshape(x=mbox_loc, shape=[-1, pb.shape[0], 4]) mbox_loc = fluid.layers.reshape(x=mbox_loc, shape=[-1, pb.shape[0], 4])
mbox_conf_flatten = fluid.layers.reshape(x=mbox_conf_flatten, mbox_conf_flatten = fluid.layers.reshape(
shape=[0, pb.shape[0], -1]) x=mbox_conf_flatten, shape=[0, pb.shape[0], -1])
default = {"nms_threshold": 0.3, "top_k": 10, "eta": 1.0} default = {"nms_threshold": 0.3, "top_k": 10, "eta": 1.0}
fields = ['eta', 'top_k', 'nms_threshold'] fields = ['eta', 'top_k', 'nms_threshold']
...@@ -64,7 +64,8 @@ def detectionoutput_weights(name, data=None): ...@@ -64,7 +64,8 @@ def detectionoutput_weights(name, data=None):
return weights_name return weights_name
register(kind='DetectionOutput', register(
shape=detectionoutput_shape, kind='DetectionOutput',
layer=detectionoutput_layer, shape=detectionoutput_shape,
weights=detectionoutput_weights) layer=detectionoutput_layer,
weights=detectionoutput_weights)
...@@ -20,9 +20,8 @@ def normalize_layer(inputs, ...@@ -20,9 +20,8 @@ def normalize_layer(inputs,
attr=name + '_scale') attr=name + '_scale')
scale_param = fluid.layers.reshape(x=scale_param, \ scale_param = fluid.layers.reshape(x=scale_param, \
shape=[1] if channel_shared else [input_shape[0][1]]) shape=[1] if channel_shared else [input_shape[0][1]])
out = fluid.layers.elementwise_mul(x=l2_norm, out = fluid.layers.elementwise_mul(
y=scale_param, x=l2_norm, y=scale_param, axis=-1 if channel_shared else 1)
axis=-1 if channel_shared else 1)
return out return out
...@@ -31,7 +30,8 @@ def normalize_weights(name, data=None): ...@@ -31,7 +30,8 @@ def normalize_weights(name, data=None):
return weights_name return weights_name
register(kind='Normalize', register(
shape=normalize_shape, kind='Normalize',
layer=normalize_layer, shape=normalize_shape,
weights=normalize_weights) layer=normalize_layer,
weights=normalize_weights)
...@@ -23,7 +23,8 @@ def permute_weights(name, data=None): ...@@ -23,7 +23,8 @@ def permute_weights(name, data=None):
return weights_name return weights_name
register(kind='Permute', register(
shape=permute_shape, kind='Permute',
layer=permute_layer, shape=permute_shape,
weights=permute_weights) layer=permute_layer,
weights=permute_weights)
...@@ -30,18 +30,19 @@ def priorbox_layer(inputs, ...@@ -30,18 +30,19 @@ def priorbox_layer(inputs,
steps = tuple(step) if type(step) is list or type(step) is tuple else (step, steps = tuple(step) if type(step) is list or type(step) is tuple else (step,
step) step)
box, variance_ = fluid.layers.prior_box(input, box, variance_ = fluid.layers.prior_box(
image, input,
min_sizes=min_size, image,
max_sizes=max_size, min_sizes=min_size,
aspect_ratios=aspect_ratio, max_sizes=max_size,
variance=variance, aspect_ratios=aspect_ratio,
flip=flip, variance=variance,
clip=clip, flip=flip,
steps=steps, clip=clip,
offset=offset, steps=steps,
name=name, offset=offset,
min_max_aspect_ratios_order=True) name=name,
min_max_aspect_ratios_order=True)
box = fluid.layers.reshape(box, [1, 1, -1]) box = fluid.layers.reshape(box, [1, 1, -1])
variance_ = fluid.layers.reshape(variance_, [1, 1, -1]) variance_ = fluid.layers.reshape(variance_, [1, 1, -1])
out = fluid.layers.concat([box, variance_], axis=1) out = fluid.layers.concat([box, variance_], axis=1)
...@@ -53,7 +54,8 @@ def priorbox_weights(name, data=None): ...@@ -53,7 +54,8 @@ def priorbox_weights(name, data=None):
return weights_name return weights_name
register(kind='PriorBox', register(
shape=priorbox_shape, kind='PriorBox',
layer=priorbox_layer, shape=priorbox_shape,
weights=priorbox_weights) layer=priorbox_layer,
weights=priorbox_weights)
...@@ -21,11 +21,12 @@ def roipooling_layer(inputs, ...@@ -21,11 +21,12 @@ def roipooling_layer(inputs,
input = inputs[0] input = inputs[0]
roi = inputs[1] roi = inputs[1]
roi = fluid.layers.slice(roi, axes=[1], starts=[1], ends=[5]) roi = fluid.layers.slice(roi, axes=[1], starts=[1], ends=[5])
out = fluid.layers.roi_pool(input, out = fluid.layers.roi_pool(
roi, input,
pooled_height=pooled_h, roi,
pooled_width=pooled_w, pooled_height=pooled_h,
spatial_scale=spatial_scale) pooled_width=pooled_w,
spatial_scale=spatial_scale)
return out return out
...@@ -34,7 +35,8 @@ def roipooling_weights(name, data=None): ...@@ -34,7 +35,8 @@ def roipooling_weights(name, data=None):
return weights_name return weights_name
register(kind='ROIPooling', register(
shape=roipooling_shape, kind='ROIPooling',
layer=roipooling_layer, shape=roipooling_shape,
weights=roipooling_weights) layer=roipooling_layer,
weights=roipooling_weights)
...@@ -30,11 +30,12 @@ def select_layer(inputs, ...@@ -30,11 +30,12 @@ def select_layer(inputs,
out = [] out = []
for i in range(len(slice_point)): for i in range(len(slice_point)):
out.append( out.append(
fluid.layers.slice(input, fluid.layers.slice(
axes=[axis], input,
starts=[slice_point[i]], axes=[axis],
ends=[slice_point[i + 1]], starts=[slice_point[i]],
name=name + '_' + str(i))) ends=[slice_point[i + 1]],
name=name + '_' + str(i)))
if i == len(slice_point) - 2: if i == len(slice_point) - 2:
break break
return out return out
...@@ -45,7 +46,8 @@ def select_weights(name, data=None): ...@@ -45,7 +46,8 @@ def select_weights(name, data=None):
return weights_name return weights_name
register(kind='Select', register(
shape=select_shape, kind='Select',
layer=select_layer, shape=select_shape,
weights=select_weights) layer=select_layer,
weights=select_weights)
...@@ -17,7 +17,8 @@ def shufflechannel_weights(name, data=None): ...@@ -17,7 +17,8 @@ def shufflechannel_weights(name, data=None):
return weights_name return weights_name
register(kind='ShuffleChannel', register(
shape=shufflechannel_shape, kind='ShuffleChannel',
layer=shufflechannel_layer, shape=shufflechannel_shape,
weights=shufflechannel_weights) layer=shufflechannel_layer,
weights=shufflechannel_weights)
...@@ -67,10 +67,10 @@ def get_strided_kernel_output_shape(params, input_shape, round_func): ...@@ -67,10 +67,10 @@ def get_strided_kernel_output_shape(params, input_shape, round_func):
i_w = input_shape[3] i_w = input_shape[3]
dila_h, dila_w, pad_h, pad_w, kernel_h, kernel_w, stride_h, stride_w = get_kernel_parameters( dila_h, dila_w, pad_h, pad_w, kernel_h, kernel_w, stride_h, stride_w = get_kernel_parameters(
params) params)
o_h = (i_h + 2 * pad_h - (dila_h * o_h = (i_h + 2 * pad_h -
(kernel_h - 1) + 1)) / float(stride_h) + 1 (dila_h * (kernel_h - 1) + 1)) / float(stride_h) + 1
o_w = (i_w + 2 * pad_w - (dila_w * o_w = (i_w + 2 * pad_w -
(kernel_w - 1) + 1)) / float(stride_w) + 1 (dila_w * (kernel_w - 1) + 1)) / float(stride_w) + 1
o_h = int(round_func(o_h)) o_h = int(round_func(o_h))
o_w = int(round_func(o_w)) o_w = int(round_func(o_w))
has_c_o = hasattr(params, 'num_output') has_c_o = hasattr(params, 'num_output')
......
...@@ -24,21 +24,18 @@ def InstanceNormalization_layer(inputs, name=None): ...@@ -24,21 +24,18 @@ def InstanceNormalization_layer(inputs, name=None):
epsilon = 1e-5 epsilon = 1e-5
input_ = inputs[0] input_ = inputs[0]
mean = fluid.layers.reduce_mean(input_, dim=[2, 3], keep_dim=True) mean = fluid.layers.reduce_mean(input_, dim=[2, 3], keep_dim=True)
var = fluid.layers.reduce_mean(fluid.layers.square(input_ - mean), var = fluid.layers.reduce_mean(
dim=[2, 3], fluid.layers.square(input_ - mean), dim=[2, 3], keep_dim=True)
keep_dim=True)
if name is not None: if name is not None:
scale_name = name + "_scale" scale_name = name + "_scale"
offset_name = name + "_offset" offset_name = name + "_offset"
scale_param = inputs[1] scale_param = inputs[1]
offset_param = inputs[2] offset_param = inputs[2]
scale = fluid.layers.create_parameter(name=scale_param.name, scale = fluid.layers.create_parameter(
shape=input_.shape[1:2], name=scale_param.name, shape=input_.shape[1:2], dtype="float32")
dtype="float32") offset = fluid.layers.create_parameter(
offset = fluid.layers.create_parameter(name=offset_param.name, name=offset_param.name, shape=input_.shape[1:2], dtype="float32")
shape=input_.shape[1:2],
dtype="float32")
tmp = fluid.layers.elementwise_mul(x=(input_ - mean), y=scale, axis=1) tmp = fluid.layers.elementwise_mul(x=(input_ - mean), y=scale, axis=1)
tmp = tmp / fluid.layers.sqrt(var + epsilon) tmp = tmp / fluid.layers.sqrt(var + epsilon)
...@@ -51,8 +48,9 @@ def InstanceNormalization_weights(name, data=None): ...@@ -51,8 +48,9 @@ def InstanceNormalization_weights(name, data=None):
return weights_name return weights_name
register(kind='InstanceNormalization', register(
shape=InstanceNormalization_shape, kind='InstanceNormalization',
layer=InstanceNormalization_layer, shape=InstanceNormalization_shape,
child_func=None, layer=InstanceNormalization_layer,
weights=InstanceNormalization_weights) child_func=None,
weights=InstanceNormalization_weights)
此差异已折叠。
...@@ -41,10 +41,11 @@ class CaffeOptimizer(object): ...@@ -41,10 +41,11 @@ class CaffeOptimizer(object):
if is_delete_node: if is_delete_node:
parent_node.fluid_code.clear() parent_node.fluid_code.clear()
node.fluid_code.clear() node.fluid_code.clear()
node.fluid_code.add_layer("batch_norm", node.fluid_code.add_layer(
inputs=input, "batch_norm",
output=node, inputs=input,
param_attr=parent_param_attr) output=node,
param_attr=parent_param_attr)
def merge_op_activation(self): def merge_op_activation(self):
for node_name in self.graph.topo_sort: for node_name in self.graph.topo_sort:
...@@ -62,7 +63,8 @@ class CaffeOptimizer(object): ...@@ -62,7 +63,8 @@ class CaffeOptimizer(object):
if is_delete_node: if is_delete_node:
parent_node.fluid_code.clear() parent_node.fluid_code.clear()
node.fluid_code.clear() node.fluid_code.clear()
node.fluid_code.add_layer(op, node.fluid_code.add_layer(
inputs=input, op,
output=node, inputs=input,
param_attr=parent_param_attr) output=node,
param_attr=parent_param_attr)
...@@ -554,10 +554,11 @@ class TFOptimizer(object): ...@@ -554,10 +554,11 @@ class TFOptimizer(object):
node.fluid_code.layers[0].param_attr["shape"] = shape node.fluid_code.layers[0].param_attr["shape"] = shape
node.fluid_code.layers[0].output = "nhwc_" + name node.fluid_code.layers[0].output = "nhwc_" + name
attr = {"perm": [0, 2, 3, 1]} attr = {"perm": [0, 2, 3, 1]}
node.fluid_code.add_layer("transpose", node.fluid_code.add_layer(
inputs="nhwc_" + name, "transpose",
output=node, inputs="nhwc_" + name,
param_attr=attr) output=node,
param_attr=attr)
self.graph.input_nodes[i] = "nhwc_" + name self.graph.input_nodes[i] = "nhwc_" + name
for i, name in enumerate(self.graph.output_nodes): for i, name in enumerate(self.graph.output_nodes):
node = self.graph.get_node(name) node = self.graph.get_node(name)
...@@ -972,10 +973,8 @@ class TFOptimizer(object): ...@@ -972,10 +973,8 @@ class TFOptimizer(object):
"bias_after_scale": True, "bias_after_scale": True,
"act": act "act": act
} }
node.fluid_code.add_layer("scale", node.fluid_code.add_layer(
inputs=in_node, "scale", inputs=in_node, output=node, param_attr=attr)
output=node,
param_attr=attr)
del self.graph.node_map[in_nodes0[0].layer_name] del self.graph.node_map[in_nodes0[0].layer_name]
del self.graph.node_map[in_nodes0[1].layer_name] del self.graph.node_map[in_nodes0[1].layer_name]
...@@ -1055,29 +1054,32 @@ class TFOptimizer(object): ...@@ -1055,29 +1054,32 @@ class TFOptimizer(object):
"shape": [channel], "shape": [channel],
"name": string(node.layer_name + "_scale") "name": string(node.layer_name + "_scale")
} }
node.fluid_code.add_layer("create_parameter", node.fluid_code.add_layer(
inputs=None, "create_parameter",
output=node.layer_name + "_scale", inputs=None,
param_attr=attr) output=node.layer_name + "_scale",
param_attr=attr)
attr = { attr = {
"dtype": string(scale.dtype), "dtype": string(scale.dtype),
"shape": [channel], "shape": [channel],
"name": string(node.layer_name + "_bias") "name": string(node.layer_name + "_bias")
} }
node.fluid_code.add_layer("create_parameter", node.fluid_code.add_layer(
inputs=None, "create_parameter",
output=node.layer_name + "_bias", inputs=None,
param_attr=attr) output=node.layer_name + "_bias",
param_attr=attr)
inputs = { inputs = {
"x": in_node, "x": in_node,
"scale": node.layer_name + "_scale", "scale": node.layer_name + "_scale",
"bias": node.layer_name + "_bias" "bias": node.layer_name + "_bias"
} }
attr = {"act": act} attr = {"act": act}
node.fluid_code.add_layer("affine_channel", node.fluid_code.add_layer(
inputs=inputs, "affine_channel",
output=node, inputs=inputs,
param_attr=attr) output=node,
param_attr=attr)
del self.graph.node_map[in_nodes0[0].layer_name] del self.graph.node_map[in_nodes0[0].layer_name]
del self.graph.node_map[in_nodes0[1].layer_name] del self.graph.node_map[in_nodes0[1].layer_name]
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册