prompt
stringlengths
94
42.6k
completion
stringlengths
6
120
api
stringlengths
14
68
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph =
GraphInference(modified_model)
megengine.utils.comp_graph_tools.GraphInference
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a =
Tensor([1, 2])
megengine.tensor.Tensor
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b =
Tensor([3, 4])
megengine.tensor.Tensor
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @
trace(symbolic=True, capture_as_const=True)
megengine.jit.tracing.trace
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph =
Net.load(orig_model)
megengine.utils.network.Network.load
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out =
F.add(varo, inp_c)
megengine.functional.add
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph =
GraphInference(modified_model)
megengine.utils.comp_graph_tools.GraphInference
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a =
Tensor([1.0, 2.0])
megengine.tensor.Tensor
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b =
Tensor([3.0, 4.0])
megengine.tensor.Tensor
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @
trace(symbolic=True, capture_as_const=True)
megengine.jit.tracing.trace
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net =
Net.load(orig_model)
megengine.utils.network.Network.load
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 =
F.sigmoid(var_a + var_b)
megengine.functional.sigmoid
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g =
GraphInference(modified_model)
megengine.utils.comp_graph_tools.GraphInference
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @
trace(symbolic=True, capture_as_const=True)
megengine.jit.tracing.trace
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph =
Net.load(orig_model)
megengine.utils.network.Network.load
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @
trace(symbolic=True, capture_as_const=True)
megengine.jit.tracing.trace
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net =
Net.load(orig_model)
megengine.utils.network.Network.load
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res =
G.load_graph(optimize_model)
megengine.core.tensor.megbrain_graph.load_graph
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @
trace(symbolic=True, capture_as_const=True)
megengine.jit.tracing.trace
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net =
Net.load(orig_model)
megengine.utils.network.Network.load
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 =
Net.load(modified_model)
megengine.utils.network.Network.load
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @
trace(symbolic=True, capture_as_const=True)
megengine.jit.tracing.trace
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net =
Net.load(orig_model)
megengine.utils.network.Network.load
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 =
Net.load(modified_model)
megengine.utils.network.Network.load
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().name == "net1.net.a" def test_dump_cond_take(): a =
Tensor([1.0, 2.0])
megengine.tensor.Tensor
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().name == "net1.net.a" def test_dump_cond_take(): a = Tensor([1.0, 2.0]) @
trace(symbolic=True, capture_as_const=True)
megengine.jit.tracing.trace
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().name == "net1.net.a" def test_dump_cond_take(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.cond_take(a > 1, a) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net =
Net.load(orig_model)
megengine.utils.network.Network.load
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().name == "net1.net.a" def test_dump_cond_take(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.cond_take(a > 1, a) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.input_vars[0] val, idx =
F.cond_take(var_a > 1, var_a)
megengine.functional.cond_take
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().name == "net1.net.a" def test_dump_cond_take(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.cond_take(a > 1, a) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.input_vars[0] val, idx = F.cond_take(var_a > 1, var_a) net.remove_output(*net.output_vars) val.name = "value" idx.name = "index" net.add_output(val, idx) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g =
GraphInference(modified_model)
megengine.utils.comp_graph_tools.GraphInference
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().name == "net1.net.a" def test_dump_cond_take(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.cond_take(a > 1, a) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.input_vars[0] val, idx = F.cond_take(var_a > 1, var_a) net.remove_output(*net.output_vars) val.name = "value" idx.name = "index" net.add_output(val, idx) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy()) data = a.numpy() mask = a.numpy() > 1 np.testing.assert_equal(out["index"], np.where(mask.reshape(-1))[0]) np.testing.assert_equal(out["value"], data[mask]) def test_set_symbolic_shape(): a =
Tensor([1.0, 2.0])
megengine.tensor.Tensor
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().name == "net1.net.a" def test_dump_cond_take(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.cond_take(a > 1, a) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.input_vars[0] val, idx = F.cond_take(var_a > 1, var_a) net.remove_output(*net.output_vars) val.name = "value" idx.name = "index" net.add_output(val, idx) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy()) data = a.numpy() mask = a.numpy() > 1 np.testing.assert_equal(out["index"], np.where(mask.reshape(-1))[0]) np.testing.assert_equal(out["value"], data[mask]) def test_set_symbolic_shape(): a = Tensor([1.0, 2.0]) @
trace(symbolic=True, capture_as_const=True)
megengine.jit.tracing.trace
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().name == "net1.net.a" def test_dump_cond_take(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.cond_take(a > 1, a) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.input_vars[0] val, idx = F.cond_take(var_a > 1, var_a) net.remove_output(*net.output_vars) val.name = "value" idx.name = "index" net.add_output(val, idx) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy()) data = a.numpy() mask = a.numpy() > 1 np.testing.assert_equal(out["index"], np.where(mask.reshape(-1))[0]) np.testing.assert_equal(out["value"], data[mask]) def test_set_symbolic_shape(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.relu(a * 2) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o"], optimize_for_inference=False, ) orig_model.seek(0) net =
Net.load(orig_model)
megengine.utils.network.Network.load
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().name == "net1.net.a" def test_dump_cond_take(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.cond_take(a > 1, a) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.input_vars[0] val, idx = F.cond_take(var_a > 1, var_a) net.remove_output(*net.output_vars) val.name = "value" idx.name = "index" net.add_output(val, idx) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy()) data = a.numpy() mask = a.numpy() > 1 np.testing.assert_equal(out["index"], np.where(mask.reshape(-1))[0]) np.testing.assert_equal(out["value"], data[mask]) def test_set_symbolic_shape(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.relu(a * 2) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.input_vars[0] saved_symbolic_shape =
set_symbolic_shape(True)
megengine.utils.network.set_symbolic_shape
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().name == "net1.net.a" def test_dump_cond_take(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.cond_take(a > 1, a) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.input_vars[0] val, idx = F.cond_take(var_a > 1, var_a) net.remove_output(*net.output_vars) val.name = "value" idx.name = "index" net.add_output(val, idx) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy()) data = a.numpy() mask = a.numpy() > 1 np.testing.assert_equal(out["index"], np.where(mask.reshape(-1))[0]) np.testing.assert_equal(out["value"], data[mask]) def test_set_symbolic_shape(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.relu(a * 2) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.input_vars[0] saved_symbolic_shape = set_symbolic_shape(True) assert isinstance(var_a.shape, VarNode)
set_symbolic_shape(False)
megengine.utils.network.set_symbolic_shape
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().name == "net1.net.a" def test_dump_cond_take(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.cond_take(a > 1, a) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.input_vars[0] val, idx = F.cond_take(var_a > 1, var_a) net.remove_output(*net.output_vars) val.name = "value" idx.name = "index" net.add_output(val, idx) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy()) data = a.numpy() mask = a.numpy() > 1 np.testing.assert_equal(out["index"], np.where(mask.reshape(-1))[0]) np.testing.assert_equal(out["value"], data[mask]) def test_set_symbolic_shape(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.relu(a * 2) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.input_vars[0] saved_symbolic_shape = set_symbolic_shape(True) assert isinstance(var_a.shape, VarNode) set_symbolic_shape(False) assert var_a.shape == var_a.partial_shape
set_symbolic_shape(saved_symbolic_shape)
megengine.utils.network.set_symbolic_shape
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return
F.exp(x)
megengine.functional.exp
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(
Tensor(5.0)
megengine.tensor.Tensor
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return
F.exp(x)
megengine.functional.exp
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return
F.exp(x)
megengine.functional.exp
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().name == "net1.net.a" def test_dump_cond_take(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return
F.cond_take(a > 1, a)
megengine.functional.cond_take
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 = M.Conv2d(32, 32, 3) def forward(self, data): x = self.conv1(data) x = self.conv2(x) x = self.conv3(x) return x n = Model() @trace(symbolic=True, capture_as_const=True) def fwd(data): return n(data) fwd(Tensor(np.random.random((1, 3, 224, 224)))) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["data"], output_names="o", keep_opr_name=True, keep_var_name=True, optimize_for_inference=False, ) orig_model.seek(0) graph = Net.load(orig_model) r = graph.data_providers_filter.as_count() assert r == 1 opr = graph.get_opr_by_type(Host2DeviceCopy) assert isinstance(opr, Host2DeviceCopy) r1 = graph.params_filter.as_count() assert r1 == 6 r2 = graph.opr_filter.type(N.ConvolutionForward).as_count() assert r2 == 3 r3 = graph.opr_filter.not_type(N.ConvolutionForward).as_count() assert r3 == len(graph.all_oprs) - r2 var = graph.var_filter.name("data").as_unique() r4 = graph.opr_filter.has_input(var).as_count() assert r4 == 1 r5 = graph.opr_filter.name("data").as_count() assert r5 == 1 opr = graph.get_opr_by_name("data") assert isinstance(opr, Host2DeviceCopy) var = graph.get_var_by_name("data") assert isinstance(var, VarNode) r6 = graph.var_filter.name("*bias").as_count() assert r6 == 3 def test_optimize_for_inference(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(5.0)) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) optimize_model = io.BytesIO() net = Net.load(orig_model) net.dump(optimize_model, enable_io16xc32=True) optimize_model.seek(0) res = G.load_graph(optimize_model) computing_input = res.output_vars_list[0].owner.inputs[0] assert computing_input.dtype == np.float16 def test_reset_batchsize(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.reset_batch_size(1) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().shape[0] == 1 def test_modify_opr_name(): @trace(symbolic=True, capture_as_const=True) def f(x): return F.exp(x) orig_model = io.BytesIO() f(Tensor(np.random.random((3, 3, 224, 224)))) f.dump(orig_model, arg_names=["a"], optimize_for_inference=False) orig_model.seek(0) modified_model = io.BytesIO() net = Net.load(orig_model) net.modify_opr_names("net") net.modify_opr_names(lambda x: "net1." + x) net.dump(modified_model, optimize_for_inference=False) modified_model.seek(0) net1 = Net.load(modified_model) assert net1.data_providers_filter.as_unique().name == "net1.net.a" def test_dump_cond_take(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return F.cond_take(a > 1, a) fwd(a) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.input_vars[0] val, idx = F.cond_take(var_a > 1, var_a) net.remove_output(*net.output_vars) val.name = "value" idx.name = "index" net.add_output(val, idx) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy()) data = a.numpy() mask = a.numpy() > 1 np.testing.assert_equal(out["index"], np.where(mask.reshape(-1))[0]) np.testing.assert_equal(out["value"], data[mask]) def test_set_symbolic_shape(): a = Tensor([1.0, 2.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a): return
F.relu(a * 2)
megengine.functional.relu
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 =
M.Conv2d(3, 32, 3)
megengine.module.Conv2d
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 =
M.Conv2d(32, 32, 3)
megengine.module.Conv2d
import io import numpy as np import megengine.core.tensor.megbrain_graph as G import megengine.functional as F import megengine.module as M import megengine.utils.network_node as N from megengine.jit.tracing import trace from megengine.tensor import Tensor from megengine.utils.comp_graph_tools import GraphInference from megengine.utils.network import Network as Net from megengine.utils.network import as_oprnode, set_symbolic_shape from megengine.utils.network_node import Host2DeviceCopy, VarNode def test_metadata(): x = Tensor(0) @trace(symbolic=True, capture_as_const=True) def fwd(x): return x * 2 fwd(x) orig_model = io.BytesIO() fwd.dump(orig_model, user_info="test", optimize_for_inference=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": "test", "graph_modified": False, # False: tracing.dump "optimized_for_inference": False, } orig_model.seek(0) graph.dump( orig_model, user_info={"str": "x", "tensor": x, "module": M.Module, "none": None}, optimize_for_inference=True, enable_nchw4=True, enable_ioc16=True, ) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata == { "user_info": {"str": "x", "tensor": x, "module": M.Module, "none": None}, "graph_modified": True, # True: Network.dump "optimized_for_inference": True, "enable_nchw4": True, "enable_ioc16": True, } orig_model.seek(0) fwd.dump(orig_model, enable_metadata=False) orig_model.seek(0) graph = Net.load(orig_model) assert graph.metadata is None def test_replace_var(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out = F.mul(vara, varb) out = F.relu(out) opnode = list(graph.opr_filter.has_input(vara)) repl_dict = {opnode[0].outputs[0]: out} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [6, 16]) def test_replace_opr(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) vara = graph.var_filter.name("a").as_unique() varb = graph.var_filter.name("b").as_unique() out1 = F.sub(vara, varb) out1 = F.relu(out1) out1 = graph.add_dep_oprs(out1) orig_opr = graph.opr_filter.has_input(vara).as_unique() repl_dict = {orig_opr: out1[0].owner} graph.replace_oprs(repl_dict) modified_model1 = io.BytesIO() graph.dump(modified_model1) modified_model1.seek(0) load_graph = GraphInference(modified_model1) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [0, 0]) def test_splice_network(): x = F.ones((2,)) y = F.ones((2,)) @trace(symbolic=True, capture_as_const=True) def fun1(a, b): return (a + b) * 2 @trace(symbolic=True, capture_as_const=True) def fun2(a): return a * 2 - 1 model = io.BytesIO() fun1(x, y) fun2(x) fun1.dump( model, arg_names=["net1_i0", "net1_i1"], output_names=["net1_o0"], optimize_for_inference=False, ) model.seek(0) net1 = Net.load(model) model.seek(0) fun2.dump( model, arg_names=["net2_i0"], output_names=["net2_o0"], optimize_for_inference=False, ) model.seek(0) net2 = Net.load(model) net1.add_output(*net2.output_vars) var = net1.var_filter.name("net1_i0").as_unique() repl_var = net2.var_filter.name("net2_o0").as_unique() net1.replace_vars({var: repl_var}) assert "net1_i0" not in [var.name for var in net1.all_vars] assert "net2_i0" in [var.name for var in net1.all_vars] model.seek(0) net1.dump(model, keep_var_name=2, optimize_for_inference=False) model.seek(0) net = Net.load(model) assert "net1_i0" not in [var.name for var in net.all_vars] assert "net2_i0" in [var.name for var in net.all_vars] def test_modify_params(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) param_const = graph.params_filter.as_unique() param_const.set_value(3) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b) np.testing.assert_equal(out["o"], [12, 18]) def test_make_const(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) const_b = graph.make_const(np.array([0.0, 0.0]), name="b") varb = graph.var_filter.name("b").as_unique() repl_dict = {varb: const_b} graph.replace_vars(repl_dict) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a) np.testing.assert_equal(out["o"], [2, 4]) def test_add_input(): a = Tensor([1, 2]) b = Tensor([3, 4]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2 fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names="o", optimize_for_inference=False ) orig_model.seek(0) graph = Net.load(orig_model) inp_c = graph.make_input_node((2,), np.int32, name="c") varo = graph.var_filter.name("o").as_unique() out = F.add(varo, inp_c) out.name = "o1" graph.remove_output(varo) graph.add_output(out) modified_model = io.BytesIO() graph.dump(modified_model) modified_model.seek(0) load_graph = GraphInference(modified_model) out = load_graph.run(a, b, a) np.testing.assert_equal(out["o1"], ((a + b) * 2 + a).numpy()) def test_add_remove_output(): a = Tensor([1.0, 2.0]) b = Tensor([3.0, 4.0]) @trace(symbolic=True, capture_as_const=True) def fwd(a, b): return (a + b) * 2, (a - b) fwd(a, b) orig_model = io.BytesIO() fwd.dump( orig_model, arg_names=["a", "b"], output_names=["o1", "o2"], optimize_for_inference=False, ) orig_model.seek(0) net = Net.load(orig_model) var_a = net.var_filter.name("a").as_unique() var_b = net.var_filter.name("b").as_unique() y1 = (var_a + var_b) * 3 y2 = F.sigmoid(var_a + var_b) net.remove_output(*net.output_vars) y1.name = "new_o1" y2.name = "new_o2" net.add_output(y1, y2) modified_model = io.BytesIO() net.dump(modified_model) modified_model.seek(0) g = GraphInference(modified_model) out = g.run(a.numpy(), b.numpy()) np.testing.assert_equal(out["new_o1"], ((a + b) * 3).numpy()) np.testing.assert_equal(out["new_o2"], (F.sigmoid((a + b))).numpy()) def test_query(): class Model(M.Module): def __init__(self): super().__init__() self.conv1 = M.Conv2d(3, 32, 3) self.conv2 = M.Conv2d(32, 32, 3) self.conv3 =
M.Conv2d(32, 32, 3)
megengine.module.Conv2d
import math import megengine.module as M import megengine.functional as F class PositionEncodingSine(M.Module): """ This is a sinusoidal position encoding that generalized to 2-dimensional images """ def __init__(self, d_model, max_shape=(256, 256)): """ Args: max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels """ super().__init__() pe =
F.zeros((d_model, *max_shape))
megengine.functional.zeros
import math import megengine.module as M import megengine.functional as F class PositionEncodingSine(M.Module): """ This is a sinusoidal position encoding that generalized to 2-dimensional images """ def __init__(self, d_model, max_shape=(256, 256)): """ Args: max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels """ super().__init__() pe = F.zeros((d_model, *max_shape)) y_position = F.expand_dims(F.cumsum(F.ones(max_shape), 0), 0) x_position = F.expand_dims(F.cumsum(F.ones(max_shape), 1), 0) div_term = F.exp( F.arange(0, d_model // 2, 2) * (-math.log(10000.0) / d_model // 2) ) div_term =
F.expand_dims(div_term, (1, 2))
megengine.functional.expand_dims
import math import megengine.module as M import megengine.functional as F class PositionEncodingSine(M.Module): """ This is a sinusoidal position encoding that generalized to 2-dimensional images """ def __init__(self, d_model, max_shape=(256, 256)): """ Args: max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels """ super().__init__() pe = F.zeros((d_model, *max_shape)) y_position = F.expand_dims(F.cumsum(F.ones(max_shape), 0), 0) x_position = F.expand_dims(F.cumsum(F.ones(max_shape), 1), 0) div_term = F.exp( F.arange(0, d_model // 2, 2) * (-math.log(10000.0) / d_model // 2) ) div_term = F.expand_dims(div_term, (1, 2)) # [C//4, 1, 1] pe[0::4, :, :] =
F.sin(x_position * div_term)
megengine.functional.sin
import math import megengine.module as M import megengine.functional as F class PositionEncodingSine(M.Module): """ This is a sinusoidal position encoding that generalized to 2-dimensional images """ def __init__(self, d_model, max_shape=(256, 256)): """ Args: max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels """ super().__init__() pe = F.zeros((d_model, *max_shape)) y_position = F.expand_dims(F.cumsum(F.ones(max_shape), 0), 0) x_position = F.expand_dims(F.cumsum(F.ones(max_shape), 1), 0) div_term = F.exp( F.arange(0, d_model // 2, 2) * (-math.log(10000.0) / d_model // 2) ) div_term = F.expand_dims(div_term, (1, 2)) # [C//4, 1, 1] pe[0::4, :, :] = F.sin(x_position * div_term) pe[1::4, :, :] =
F.cos(x_position * div_term)
megengine.functional.cos
import math import megengine.module as M import megengine.functional as F class PositionEncodingSine(M.Module): """ This is a sinusoidal position encoding that generalized to 2-dimensional images """ def __init__(self, d_model, max_shape=(256, 256)): """ Args: max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels """ super().__init__() pe = F.zeros((d_model, *max_shape)) y_position = F.expand_dims(F.cumsum(F.ones(max_shape), 0), 0) x_position = F.expand_dims(F.cumsum(F.ones(max_shape), 1), 0) div_term = F.exp( F.arange(0, d_model // 2, 2) * (-math.log(10000.0) / d_model // 2) ) div_term = F.expand_dims(div_term, (1, 2)) # [C//4, 1, 1] pe[0::4, :, :] = F.sin(x_position * div_term) pe[1::4, :, :] = F.cos(x_position * div_term) pe[2::4, :, :] =
F.sin(y_position * div_term)
megengine.functional.sin
import math import megengine.module as M import megengine.functional as F class PositionEncodingSine(M.Module): """ This is a sinusoidal position encoding that generalized to 2-dimensional images """ def __init__(self, d_model, max_shape=(256, 256)): """ Args: max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels """ super().__init__() pe = F.zeros((d_model, *max_shape)) y_position = F.expand_dims(F.cumsum(F.ones(max_shape), 0), 0) x_position = F.expand_dims(F.cumsum(F.ones(max_shape), 1), 0) div_term = F.exp( F.arange(0, d_model // 2, 2) * (-math.log(10000.0) / d_model // 2) ) div_term = F.expand_dims(div_term, (1, 2)) # [C//4, 1, 1] pe[0::4, :, :] = F.sin(x_position * div_term) pe[1::4, :, :] = F.cos(x_position * div_term) pe[2::4, :, :] = F.sin(y_position * div_term) pe[3::4, :, :] =
F.cos(y_position * div_term)
megengine.functional.cos
import math import megengine.module as M import megengine.functional as F class PositionEncodingSine(M.Module): """ This is a sinusoidal position encoding that generalized to 2-dimensional images """ def __init__(self, d_model, max_shape=(256, 256)): """ Args: max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels """ super().__init__() pe = F.zeros((d_model, *max_shape)) y_position = F.expand_dims(F.cumsum(F.ones(max_shape), 0), 0) x_position = F.expand_dims(F.cumsum(F.ones(max_shape), 1), 0) div_term = F.exp( F.arange(0, d_model // 2, 2) * (-math.log(10000.0) / d_model // 2) ) div_term = F.expand_dims(div_term, (1, 2)) # [C//4, 1, 1] pe[0::4, :, :] = F.sin(x_position * div_term) pe[1::4, :, :] = F.cos(x_position * div_term) pe[2::4, :, :] = F.sin(y_position * div_term) pe[3::4, :, :] = F.cos(y_position * div_term) self.pe =
F.expand_dims(pe, 0)
megengine.functional.expand_dims
import math import megengine.module as M import megengine.functional as F class PositionEncodingSine(M.Module): """ This is a sinusoidal position encoding that generalized to 2-dimensional images """ def __init__(self, d_model, max_shape=(256, 256)): """ Args: max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels """ super().__init__() pe = F.zeros((d_model, *max_shape)) y_position = F.expand_dims(F.cumsum(
F.ones(max_shape)
megengine.functional.ones
import math import megengine.module as M import megengine.functional as F class PositionEncodingSine(M.Module): """ This is a sinusoidal position encoding that generalized to 2-dimensional images """ def __init__(self, d_model, max_shape=(256, 256)): """ Args: max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels """ super().__init__() pe = F.zeros((d_model, *max_shape)) y_position = F.expand_dims(F.cumsum(F.ones(max_shape), 0), 0) x_position = F.expand_dims(F.cumsum(
F.ones(max_shape)
megengine.functional.ones
import math import megengine.module as M import megengine.functional as F class PositionEncodingSine(M.Module): """ This is a sinusoidal position encoding that generalized to 2-dimensional images """ def __init__(self, d_model, max_shape=(256, 256)): """ Args: max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels """ super().__init__() pe = F.zeros((d_model, *max_shape)) y_position = F.expand_dims(F.cumsum(F.ones(max_shape), 0), 0) x_position = F.expand_dims(F.cumsum(F.ones(max_shape), 1), 0) div_term = F.exp(
F.arange(0, d_model // 2, 2)
megengine.functional.arange
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. import cv2 import megengine.functional as F import numpy as np __all__ = [ "preprocess", "postprocess", ] def preprocess(image, input_size, mean, std, swap=(2, 0, 1)): if len(image.shape) == 3: padded_img = np.ones((input_size[0], input_size[1], 3)) * 114.0 else: padded_img = np.ones(input_size) * 114.0 img = np.array(image) r = min(input_size[0] / img.shape[0], input_size[1] / img.shape[1]) resized_img = cv2.resize( img, (int(img.shape[1] * r), int(img.shape[0] * r)), interpolation=cv2.INTER_LINEAR, ).astype(np.float32) padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img image = padded_img image = image.astype(np.float32) image = image[:, :, ::-1] image /= 255.0 if mean is not None: image -= mean if std is not None: image /= std image = image.transpose(swap) image = np.ascontiguousarray(image, dtype=np.float32) return image, r def postprocess(prediction, num_classes, conf_thre=0.7, nms_thre=0.45): box_corner =
F.zeros_like(prediction)
megengine.functional.zeros_like
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. import cv2 import megengine.functional as F import numpy as np __all__ = [ "preprocess", "postprocess", ] def preprocess(image, input_size, mean, std, swap=(2, 0, 1)): if len(image.shape) == 3: padded_img = np.ones((input_size[0], input_size[1], 3)) * 114.0 else: padded_img = np.ones(input_size) * 114.0 img = np.array(image) r = min(input_size[0] / img.shape[0], input_size[1] / img.shape[1]) resized_img = cv2.resize( img, (int(img.shape[1] * r), int(img.shape[0] * r)), interpolation=cv2.INTER_LINEAR, ).astype(np.float32) padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img image = padded_img image = image.astype(np.float32) image = image[:, :, ::-1] image /= 255.0 if mean is not None: image -= mean if std is not None: image /= std image = image.transpose(swap) image = np.ascontiguousarray(image, dtype=np.float32) return image, r def postprocess(prediction, num_classes, conf_thre=0.7, nms_thre=0.45): box_corner = F.zeros_like(prediction) box_corner[:, :, 0] = prediction[:, :, 0] - prediction[:, :, 2] / 2 box_corner[:, :, 1] = prediction[:, :, 1] - prediction[:, :, 3] / 2 box_corner[:, :, 2] = prediction[:, :, 0] + prediction[:, :, 2] / 2 box_corner[:, :, 3] = prediction[:, :, 1] + prediction[:, :, 3] / 2 prediction[:, :, :4] = box_corner[:, :, :4] output = [None for _ in range(len(prediction))] for i, image_pred in enumerate(prediction): # If none are remaining => process next image if not image_pred.shape[0]: continue # Get score and class with highest confidence class_conf = F.max(image_pred[:, 5 : 5 + num_classes], 1, keepdims=True) class_pred = F.argmax(image_pred[:, 5 : 5 + num_classes], 1, keepdims=True) class_conf_squeeze =
F.squeeze(class_conf)
megengine.functional.squeeze
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. import cv2 import megengine.functional as F import numpy as np __all__ = [ "preprocess", "postprocess", ] def preprocess(image, input_size, mean, std, swap=(2, 0, 1)): if len(image.shape) == 3: padded_img = np.ones((input_size[0], input_size[1], 3)) * 114.0 else: padded_img = np.ones(input_size) * 114.0 img = np.array(image) r = min(input_size[0] / img.shape[0], input_size[1] / img.shape[1]) resized_img = cv2.resize( img, (int(img.shape[1] * r), int(img.shape[0] * r)), interpolation=cv2.INTER_LINEAR, ).astype(np.float32) padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img image = padded_img image = image.astype(np.float32) image = image[:, :, ::-1] image /= 255.0 if mean is not None: image -= mean if std is not None: image /= std image = image.transpose(swap) image = np.ascontiguousarray(image, dtype=np.float32) return image, r def postprocess(prediction, num_classes, conf_thre=0.7, nms_thre=0.45): box_corner = F.zeros_like(prediction) box_corner[:, :, 0] = prediction[:, :, 0] - prediction[:, :, 2] / 2 box_corner[:, :, 1] = prediction[:, :, 1] - prediction[:, :, 3] / 2 box_corner[:, :, 2] = prediction[:, :, 0] + prediction[:, :, 2] / 2 box_corner[:, :, 3] = prediction[:, :, 1] + prediction[:, :, 3] / 2 prediction[:, :, :4] = box_corner[:, :, :4] output = [None for _ in range(len(prediction))] for i, image_pred in enumerate(prediction): # If none are remaining => process next image if not image_pred.shape[0]: continue # Get score and class with highest confidence class_conf = F.max(image_pred[:, 5 : 5 + num_classes], 1, keepdims=True) class_pred = F.argmax(image_pred[:, 5 : 5 + num_classes], 1, keepdims=True) class_conf_squeeze = F.squeeze(class_conf) conf_mask = image_pred[:, 4] * class_conf_squeeze >= conf_thre detections =
F.concat((image_pred[:, :5], class_conf, class_pred), 1)
megengine.functional.concat
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. import cv2 import megengine.functional as F import numpy as np __all__ = [ "preprocess", "postprocess", ] def preprocess(image, input_size, mean, std, swap=(2, 0, 1)): if len(image.shape) == 3: padded_img = np.ones((input_size[0], input_size[1], 3)) * 114.0 else: padded_img = np.ones(input_size) * 114.0 img = np.array(image) r = min(input_size[0] / img.shape[0], input_size[1] / img.shape[1]) resized_img = cv2.resize( img, (int(img.shape[1] * r), int(img.shape[0] * r)), interpolation=cv2.INTER_LINEAR, ).astype(np.float32) padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img image = padded_img image = image.astype(np.float32) image = image[:, :, ::-1] image /= 255.0 if mean is not None: image -= mean if std is not None: image /= std image = image.transpose(swap) image = np.ascontiguousarray(image, dtype=np.float32) return image, r def postprocess(prediction, num_classes, conf_thre=0.7, nms_thre=0.45): box_corner = F.zeros_like(prediction) box_corner[:, :, 0] = prediction[:, :, 0] - prediction[:, :, 2] / 2 box_corner[:, :, 1] = prediction[:, :, 1] - prediction[:, :, 3] / 2 box_corner[:, :, 2] = prediction[:, :, 0] + prediction[:, :, 2] / 2 box_corner[:, :, 3] = prediction[:, :, 1] + prediction[:, :, 3] / 2 prediction[:, :, :4] = box_corner[:, :, :4] output = [None for _ in range(len(prediction))] for i, image_pred in enumerate(prediction): # If none are remaining => process next image if not image_pred.shape[0]: continue # Get score and class with highest confidence class_conf = F.max(image_pred[:, 5 : 5 + num_classes], 1, keepdims=True) class_pred = F.argmax(image_pred[:, 5 : 5 + num_classes], 1, keepdims=True) class_conf_squeeze = F.squeeze(class_conf) conf_mask = image_pred[:, 4] * class_conf_squeeze >= conf_thre detections = F.concat((image_pred[:, :5], class_conf, class_pred), 1) detections = detections[conf_mask] if not detections.shape[0]: continue nms_out_index = F.vision.nms( detections[:, :4], detections[:, 4] * detections[:, 5], nms_thre, ) detections = detections[nms_out_index] if output[i] is None: output[i] = detections else: output[i] =
F.concat((output[i], detections))
megengine.functional.concat
import argparse import megengine.core.tensor.megbrain_graph as G import megengine.utils.comp_graph_tools as cgtools from megengine.core._imperative_rt import make_h2d def change_batch_and_dump(inp_file, oup_file): cg, _, outputs =
G.load_graph(inp_file)
megengine.core.tensor.megbrain_graph.load_graph
import argparse import megengine.core.tensor.megbrain_graph as G import megengine.utils.comp_graph_tools as cgtools from megengine.core._imperative_rt import make_h2d def change_batch_and_dump(inp_file, oup_file): cg, _, outputs = G.load_graph(inp_file) inputs =
cgtools.get_dep_vars(outputs[0], "Host2DeviceCopy")
megengine.utils.comp_graph_tools.get_dep_vars
import argparse import megengine.core.tensor.megbrain_graph as G import megengine.utils.comp_graph_tools as cgtools from megengine.core._imperative_rt import make_h2d def change_batch_and_dump(inp_file, oup_file): cg, _, outputs = G.load_graph(inp_file) inputs = cgtools.get_dep_vars(outputs[0], "Host2DeviceCopy") replace_dict = {} for var in inputs: n_shape = list(var.shape) n_shape[0] = 1 new_input = make_h2d(cg, "xpux", var.dtype, n_shape, var.name) replace_dict[var] = new_input new_outputs =
cgtools.replace_vars(outputs, replace_dict)
megengine.utils.comp_graph_tools.replace_vars
import argparse import megengine.core.tensor.megbrain_graph as G import megengine.utils.comp_graph_tools as cgtools from megengine.core._imperative_rt import make_h2d def change_batch_and_dump(inp_file, oup_file): cg, _, outputs = G.load_graph(inp_file) inputs = cgtools.get_dep_vars(outputs[0], "Host2DeviceCopy") replace_dict = {} for var in inputs: n_shape = list(var.shape) n_shape[0] = 1 new_input =
make_h2d(cg, "xpux", var.dtype, n_shape, var.name)
megengine.core._imperative_rt.make_h2d
import os import math import numpy as np import six import megengine._internal as mgb from enum import Enum from py_proto import mace_pb2 from transform import base_converter from transform.base_converter import PoolingType from transform.base_converter import ActivationType from transform.base_converter import EltwiseType from transform.base_converter import FrameworkType from transform.base_converter import ReduceType from transform.base_converter import DataFormat from transform.base_converter import MaceOp from transform.base_converter import MaceKeyword from transform.base_converter import ConverterUtil from transform.base_converter import RoundMode from utils.util import mace_check mge_kernel_h_str = "window_h" mge_kernel_w_str = "window_w" mge_stride_h_str = "stride_h" mge_stride_w_str = "stride_w" mge_pad_h_str = "pad_h" mge_pad_w_str = "pad_w" mge_dilate_h_str = "dilate_h" mge_dilate_w_str = "dilate_w" MGESupportedOps = [ "AxisAddRemove", "BatchNormForward", "Concat", "ConvolutionForward", "ConvolutionBackwardData", "Dimshuffle", "Elemwise", "GetVarShape", "Host2DeviceCopy", "Identity", "MarkNoBroadcastElemwise", "MatrixMul", "PoolingForward", "Reduce", "Reshape", "SharedDeviceTensor", "Subtensor", ] MGEOpType = Enum("MGEOpType", [(op, op) for op in MGESupportedOps], type=str) def get_symvar_value(mge_symvar): if mge_symvar.inferred_value is not None: val = mge_symvar.inferred_value else: cg = mge_symvar.owner_graph func = cg.compile_outonly(mge_symvar) val = func() return val def is_consumer_group_conv(mge_symvar, var2oprs, map_oprs): consumer_ids = var2oprs[mge_symvar.id] n_consumers = len(consumer_ids) for consumer_id in consumer_ids: consumer_op = map_oprs[consumer_id[0]] if (mgb.cgtools.get_opr_type(consumer_op) in ("ConvolutionForward", "ConvolutionBackwardData") and consumer_op.params["sparse"] == "GROUP"): mace_check(n_consumers == 1, "This tensor should only feed depthwise conv/deconv") return True return False class MegengineConverter(base_converter.ConverterInterface): """A class for convert megengine dumped model to mace model.""" compute_format_type = { "NCHW": DataFormat.NCHW, "NHWC": DataFormat.NHWC, "DEFAULT": DataFormat.NCHW, } reduce_math_type = { "SUM": ReduceType.SUM, "PROD": ReduceType.PROD, "MIN": ReduceType.MIN, "MAX": ReduceType.MAX, } # SQE_DIFF, CLIP, SIGN maybe needed eltwise_type = { "ADD": EltwiseType.SUM, "SUB": EltwiseType.SUB, "MUL": EltwiseType.PROD, "TRUE_DIV": EltwiseType.DIV, "MIN": EltwiseType.MIN, "MAX": EltwiseType.MAX, "NEGATE": EltwiseType.NEG, "ABS": EltwiseType.ABS, "POW": EltwiseType.POW, "EQ": EltwiseType.EQUAL, "FLOOR_DIV": EltwiseType.FLOOR_DIV, "EXP": EltwiseType.POW, } activation_type = { "RELU": ActivationType.RELU, "TANH": ActivationType.TANH, "SIGMOID": ActivationType.SIGMOID, } def __init__(self, option, src_model_file): self._op_converters = { MGEOpType.AxisAddRemove.name: self.convert_axisaddrm, MGEOpType.BatchNormForward.name: self.convert_batchnorm, MGEOpType.Concat.name: self.convert_concat, MGEOpType.ConvolutionForward.name: self.convert_conv2d, MGEOpType.ConvolutionBackwardData.name: self.convert_deconv2d, MGEOpType.Dimshuffle.name: self.convert_dimshuffle, MGEOpType.Elemwise.name: self.convert_elemwise, MGEOpType.GetVarShape.name: self.convert_shape, MGEOpType.Host2DeviceCopy.name: self.convert_nop, MGEOpType.Identity.name: self.convert_identity, MGEOpType.MarkNoBroadcastElemwise.name: self.convert_identity, MGEOpType.MatrixMul.name: self.convert_matmul, MGEOpType.PoolingForward.name: self.convert_pooling, MGEOpType.Reduce.name: self.convert_reduce, MGEOpType.Reshape.name: self.convert_reshape, MGEOpType.SharedDeviceTensor.name: self.convert_nop, MGEOpType.Subtensor.name: self.convert_subtensor, } self._option = option self._mace_net_def = mace_pb2.NetDef() ConverterUtil.set_filter_format(self._mace_net_def, DataFormat.OIHW) ConverterUtil.add_data_format_arg(self._mace_net_def, DataFormat.NCHW) cg, _, outputs =
mgb.load_comp_graph_from_file(src_model_file)
megengine._internal.load_comp_graph_from_file
import os import math import numpy as np import six import megengine._internal as mgb from enum import Enum from py_proto import mace_pb2 from transform import base_converter from transform.base_converter import PoolingType from transform.base_converter import ActivationType from transform.base_converter import EltwiseType from transform.base_converter import FrameworkType from transform.base_converter import ReduceType from transform.base_converter import DataFormat from transform.base_converter import MaceOp from transform.base_converter import MaceKeyword from transform.base_converter import ConverterUtil from transform.base_converter import RoundMode from utils.util import mace_check mge_kernel_h_str = "window_h" mge_kernel_w_str = "window_w" mge_stride_h_str = "stride_h" mge_stride_w_str = "stride_w" mge_pad_h_str = "pad_h" mge_pad_w_str = "pad_w" mge_dilate_h_str = "dilate_h" mge_dilate_w_str = "dilate_w" MGESupportedOps = [ "AxisAddRemove", "BatchNormForward", "Concat", "ConvolutionForward", "ConvolutionBackwardData", "Dimshuffle", "Elemwise", "GetVarShape", "Host2DeviceCopy", "Identity", "MarkNoBroadcastElemwise", "MatrixMul", "PoolingForward", "Reduce", "Reshape", "SharedDeviceTensor", "Subtensor", ] MGEOpType = Enum("MGEOpType", [(op, op) for op in MGESupportedOps], type=str) def get_symvar_value(mge_symvar): if mge_symvar.inferred_value is not None: val = mge_symvar.inferred_value else: cg = mge_symvar.owner_graph func = cg.compile_outonly(mge_symvar) val = func() return val def is_consumer_group_conv(mge_symvar, var2oprs, map_oprs): consumer_ids = var2oprs[mge_symvar.id] n_consumers = len(consumer_ids) for consumer_id in consumer_ids: consumer_op = map_oprs[consumer_id[0]] if (mgb.cgtools.get_opr_type(consumer_op) in ("ConvolutionForward", "ConvolutionBackwardData") and consumer_op.params["sparse"] == "GROUP"): mace_check(n_consumers == 1, "This tensor should only feed depthwise conv/deconv") return True return False class MegengineConverter(base_converter.ConverterInterface): """A class for convert megengine dumped model to mace model.""" compute_format_type = { "NCHW": DataFormat.NCHW, "NHWC": DataFormat.NHWC, "DEFAULT": DataFormat.NCHW, } reduce_math_type = { "SUM": ReduceType.SUM, "PROD": ReduceType.PROD, "MIN": ReduceType.MIN, "MAX": ReduceType.MAX, } # SQE_DIFF, CLIP, SIGN maybe needed eltwise_type = { "ADD": EltwiseType.SUM, "SUB": EltwiseType.SUB, "MUL": EltwiseType.PROD, "TRUE_DIV": EltwiseType.DIV, "MIN": EltwiseType.MIN, "MAX": EltwiseType.MAX, "NEGATE": EltwiseType.NEG, "ABS": EltwiseType.ABS, "POW": EltwiseType.POW, "EQ": EltwiseType.EQUAL, "FLOOR_DIV": EltwiseType.FLOOR_DIV, "EXP": EltwiseType.POW, } activation_type = { "RELU": ActivationType.RELU, "TANH": ActivationType.TANH, "SIGMOID": ActivationType.SIGMOID, } def __init__(self, option, src_model_file): self._op_converters = { MGEOpType.AxisAddRemove.name: self.convert_axisaddrm, MGEOpType.BatchNormForward.name: self.convert_batchnorm, MGEOpType.Concat.name: self.convert_concat, MGEOpType.ConvolutionForward.name: self.convert_conv2d, MGEOpType.ConvolutionBackwardData.name: self.convert_deconv2d, MGEOpType.Dimshuffle.name: self.convert_dimshuffle, MGEOpType.Elemwise.name: self.convert_elemwise, MGEOpType.GetVarShape.name: self.convert_shape, MGEOpType.Host2DeviceCopy.name: self.convert_nop, MGEOpType.Identity.name: self.convert_identity, MGEOpType.MarkNoBroadcastElemwise.name: self.convert_identity, MGEOpType.MatrixMul.name: self.convert_matmul, MGEOpType.PoolingForward.name: self.convert_pooling, MGEOpType.Reduce.name: self.convert_reduce, MGEOpType.Reshape.name: self.convert_reshape, MGEOpType.SharedDeviceTensor.name: self.convert_nop, MGEOpType.Subtensor.name: self.convert_subtensor, } self._option = option self._mace_net_def = mace_pb2.NetDef() ConverterUtil.set_filter_format(self._mace_net_def, DataFormat.OIHW) ConverterUtil.add_data_format_arg(self._mace_net_def, DataFormat.NCHW) cg, _, outputs = mgb.load_comp_graph_from_file(src_model_file) map_oprs, _, var2oprs, *_ =
mgb.cgtools.graph_traversal(outputs)
megengine._internal.cgtools.graph_traversal
import os import math import numpy as np import six import megengine._internal as mgb from enum import Enum from py_proto import mace_pb2 from transform import base_converter from transform.base_converter import PoolingType from transform.base_converter import ActivationType from transform.base_converter import EltwiseType from transform.base_converter import FrameworkType from transform.base_converter import ReduceType from transform.base_converter import DataFormat from transform.base_converter import MaceOp from transform.base_converter import MaceKeyword from transform.base_converter import ConverterUtil from transform.base_converter import RoundMode from utils.util import mace_check mge_kernel_h_str = "window_h" mge_kernel_w_str = "window_w" mge_stride_h_str = "stride_h" mge_stride_w_str = "stride_w" mge_pad_h_str = "pad_h" mge_pad_w_str = "pad_w" mge_dilate_h_str = "dilate_h" mge_dilate_w_str = "dilate_w" MGESupportedOps = [ "AxisAddRemove", "BatchNormForward", "Concat", "ConvolutionForward", "ConvolutionBackwardData", "Dimshuffle", "Elemwise", "GetVarShape", "Host2DeviceCopy", "Identity", "MarkNoBroadcastElemwise", "MatrixMul", "PoolingForward", "Reduce", "Reshape", "SharedDeviceTensor", "Subtensor", ] MGEOpType = Enum("MGEOpType", [(op, op) for op in MGESupportedOps], type=str) def get_symvar_value(mge_symvar): if mge_symvar.inferred_value is not None: val = mge_symvar.inferred_value else: cg = mge_symvar.owner_graph func = cg.compile_outonly(mge_symvar) val = func() return val def is_consumer_group_conv(mge_symvar, var2oprs, map_oprs): consumer_ids = var2oprs[mge_symvar.id] n_consumers = len(consumer_ids) for consumer_id in consumer_ids: consumer_op = map_oprs[consumer_id[0]] if (mgb.cgtools.get_opr_type(consumer_op) in ("ConvolutionForward", "ConvolutionBackwardData") and consumer_op.params["sparse"] == "GROUP"): mace_check(n_consumers == 1, "This tensor should only feed depthwise conv/deconv") return True return False class MegengineConverter(base_converter.ConverterInterface): """A class for convert megengine dumped model to mace model.""" compute_format_type = { "NCHW": DataFormat.NCHW, "NHWC": DataFormat.NHWC, "DEFAULT": DataFormat.NCHW, } reduce_math_type = { "SUM": ReduceType.SUM, "PROD": ReduceType.PROD, "MIN": ReduceType.MIN, "MAX": ReduceType.MAX, } # SQE_DIFF, CLIP, SIGN maybe needed eltwise_type = { "ADD": EltwiseType.SUM, "SUB": EltwiseType.SUB, "MUL": EltwiseType.PROD, "TRUE_DIV": EltwiseType.DIV, "MIN": EltwiseType.MIN, "MAX": EltwiseType.MAX, "NEGATE": EltwiseType.NEG, "ABS": EltwiseType.ABS, "POW": EltwiseType.POW, "EQ": EltwiseType.EQUAL, "FLOOR_DIV": EltwiseType.FLOOR_DIV, "EXP": EltwiseType.POW, } activation_type = { "RELU": ActivationType.RELU, "TANH": ActivationType.TANH, "SIGMOID": ActivationType.SIGMOID, } def __init__(self, option, src_model_file): self._op_converters = { MGEOpType.AxisAddRemove.name: self.convert_axisaddrm, MGEOpType.BatchNormForward.name: self.convert_batchnorm, MGEOpType.Concat.name: self.convert_concat, MGEOpType.ConvolutionForward.name: self.convert_conv2d, MGEOpType.ConvolutionBackwardData.name: self.convert_deconv2d, MGEOpType.Dimshuffle.name: self.convert_dimshuffle, MGEOpType.Elemwise.name: self.convert_elemwise, MGEOpType.GetVarShape.name: self.convert_shape, MGEOpType.Host2DeviceCopy.name: self.convert_nop, MGEOpType.Identity.name: self.convert_identity, MGEOpType.MarkNoBroadcastElemwise.name: self.convert_identity, MGEOpType.MatrixMul.name: self.convert_matmul, MGEOpType.PoolingForward.name: self.convert_pooling, MGEOpType.Reduce.name: self.convert_reduce, MGEOpType.Reshape.name: self.convert_reshape, MGEOpType.SharedDeviceTensor.name: self.convert_nop, MGEOpType.Subtensor.name: self.convert_subtensor, } self._option = option self._mace_net_def = mace_pb2.NetDef() ConverterUtil.set_filter_format(self._mace_net_def, DataFormat.OIHW) ConverterUtil.add_data_format_arg(self._mace_net_def, DataFormat.NCHW) cg, _, outputs = mgb.load_comp_graph_from_file(src_model_file) map_oprs, _, var2oprs, *_ = mgb.cgtools.graph_traversal(outputs) # prune second input of reshape # because it introduces several ops, may increase the overhead operators =
mgb.cgtools.get_oprs_seq(outputs, prune_reshape=True)
megengine._internal.cgtools.get_oprs_seq
import os import math import numpy as np import six import megengine._internal as mgb from enum import Enum from py_proto import mace_pb2 from transform import base_converter from transform.base_converter import PoolingType from transform.base_converter import ActivationType from transform.base_converter import EltwiseType from transform.base_converter import FrameworkType from transform.base_converter import ReduceType from transform.base_converter import DataFormat from transform.base_converter import MaceOp from transform.base_converter import MaceKeyword from transform.base_converter import ConverterUtil from transform.base_converter import RoundMode from utils.util import mace_check mge_kernel_h_str = "window_h" mge_kernel_w_str = "window_w" mge_stride_h_str = "stride_h" mge_stride_w_str = "stride_w" mge_pad_h_str = "pad_h" mge_pad_w_str = "pad_w" mge_dilate_h_str = "dilate_h" mge_dilate_w_str = "dilate_w" MGESupportedOps = [ "AxisAddRemove", "BatchNormForward", "Concat", "ConvolutionForward", "ConvolutionBackwardData", "Dimshuffle", "Elemwise", "GetVarShape", "Host2DeviceCopy", "Identity", "MarkNoBroadcastElemwise", "MatrixMul", "PoolingForward", "Reduce", "Reshape", "SharedDeviceTensor", "Subtensor", ] MGEOpType = Enum("MGEOpType", [(op, op) for op in MGESupportedOps], type=str) def get_symvar_value(mge_symvar): if mge_symvar.inferred_value is not None: val = mge_symvar.inferred_value else: cg = mge_symvar.owner_graph func = cg.compile_outonly(mge_symvar) val = func() return val def is_consumer_group_conv(mge_symvar, var2oprs, map_oprs): consumer_ids = var2oprs[mge_symvar.id] n_consumers = len(consumer_ids) for consumer_id in consumer_ids: consumer_op = map_oprs[consumer_id[0]] if (mgb.cgtools.get_opr_type(consumer_op) in ("ConvolutionForward", "ConvolutionBackwardData") and consumer_op.params["sparse"] == "GROUP"): mace_check(n_consumers == 1, "This tensor should only feed depthwise conv/deconv") return True return False class MegengineConverter(base_converter.ConverterInterface): """A class for convert megengine dumped model to mace model.""" compute_format_type = { "NCHW": DataFormat.NCHW, "NHWC": DataFormat.NHWC, "DEFAULT": DataFormat.NCHW, } reduce_math_type = { "SUM": ReduceType.SUM, "PROD": ReduceType.PROD, "MIN": ReduceType.MIN, "MAX": ReduceType.MAX, } # SQE_DIFF, CLIP, SIGN maybe needed eltwise_type = { "ADD": EltwiseType.SUM, "SUB": EltwiseType.SUB, "MUL": EltwiseType.PROD, "TRUE_DIV": EltwiseType.DIV, "MIN": EltwiseType.MIN, "MAX": EltwiseType.MAX, "NEGATE": EltwiseType.NEG, "ABS": EltwiseType.ABS, "POW": EltwiseType.POW, "EQ": EltwiseType.EQUAL, "FLOOR_DIV": EltwiseType.FLOOR_DIV, "EXP": EltwiseType.POW, } activation_type = { "RELU": ActivationType.RELU, "TANH": ActivationType.TANH, "SIGMOID": ActivationType.SIGMOID, } def __init__(self, option, src_model_file): self._op_converters = { MGEOpType.AxisAddRemove.name: self.convert_axisaddrm, MGEOpType.BatchNormForward.name: self.convert_batchnorm, MGEOpType.Concat.name: self.convert_concat, MGEOpType.ConvolutionForward.name: self.convert_conv2d, MGEOpType.ConvolutionBackwardData.name: self.convert_deconv2d, MGEOpType.Dimshuffle.name: self.convert_dimshuffle, MGEOpType.Elemwise.name: self.convert_elemwise, MGEOpType.GetVarShape.name: self.convert_shape, MGEOpType.Host2DeviceCopy.name: self.convert_nop, MGEOpType.Identity.name: self.convert_identity, MGEOpType.MarkNoBroadcastElemwise.name: self.convert_identity, MGEOpType.MatrixMul.name: self.convert_matmul, MGEOpType.PoolingForward.name: self.convert_pooling, MGEOpType.Reduce.name: self.convert_reduce, MGEOpType.Reshape.name: self.convert_reshape, MGEOpType.SharedDeviceTensor.name: self.convert_nop, MGEOpType.Subtensor.name: self.convert_subtensor, } self._option = option self._mace_net_def = mace_pb2.NetDef() ConverterUtil.set_filter_format(self._mace_net_def, DataFormat.OIHW) ConverterUtil.add_data_format_arg(self._mace_net_def, DataFormat.NCHW) cg, _, outputs = mgb.load_comp_graph_from_file(src_model_file) map_oprs, _, var2oprs, *_ = mgb.cgtools.graph_traversal(outputs) # prune second input of reshape # because it introduces several ops, may increase the overhead operators = mgb.cgtools.get_oprs_seq(outputs, prune_reshape=True) self._mge_cg = cg self._mge_operators = operators self._mge_map_oprs = map_oprs self._mge_var2oprs = var2oprs self._skip_tensors = set() self._bn_statistis_tensors = {} def run(self): self.convert_ops() self.replace_input_output_tensor_name() return self._mace_net_def # only change the input/output tensor name for whole model def replace_input_output_tensor_name(self): for op in self._mace_net_def.op: for i in six.moves.range(len(op.input)): if "," in op.input[i]: op_name = op.input[i] op_name = op_name.replace(",", "#") if (op_name in self._option.input_nodes or op_name in self._option.output_nodes): op.input[i] = op_name for i in six.moves.range(len(op.output)): if "," in op.output[i]: op_name = op.output[i] op_name = op_name.replace(",", "#") if op_name in self._option.output_nodes: op.output[i] = op_name # this method will be called by convert_conv2d/deconv2d and convert_pooling @staticmethod def add_stride_pad_kernel_arg(params, op_def): stride = [params[mge_stride_h_str], params[mge_stride_w_str]] pad = [params[mge_pad_h_str] * 2, params[mge_pad_w_str] * 2] strides_arg = op_def.arg.add() strides_arg.name = MaceKeyword.mace_strides_str strides_arg.ints.extend(stride) padding_arg = op_def.arg.add() padding_arg.name = MaceKeyword.mace_padding_values_str padding_arg.ints.extend(pad) if op_def.type == MaceOp.Pooling.name: kernel = [params[mge_kernel_h_str], params[mge_kernel_w_str]] kernels_arg = op_def.arg.add() kernels_arg.name = MaceKeyword.mace_kernel_str kernels_arg.ints.extend(kernel) if op_def.type in (MaceOp.Conv2D.name, MaceOp.DepthwiseConv2d.name, MaceOp.Deconv2D.name, MaceOp.DepthwiseDeconv2d.name): dilation = [params[mge_dilate_h_str], params[mge_dilate_w_str]] dilation_arg = op_def.arg.add() dilation_arg.name = MaceKeyword.mace_dilations_str dilation_arg.ints.extend(dilation) def convert_ops(self): for mge_op in self._mge_operators: opr_type = mgb.cgtools.get_opr_type(mge_op) # some reshape operators provide data for batchnorm if opr_type == "Reshape": output = mge_op.outputs[0] next_ops = self._mge_var2oprs[output.id] if len(next_ops) == 1: (next_op_id, _) = next_ops[0] next_op = self._mge_map_oprs[next_op_id] if mgb.cgtools.get_opr_type(next_op) == "BatchNormForward": self._skip_tensors.update( [inp.name for inp in mge_op.inputs]) # using output name to address input symbol var self._bn_statistis_tensors[mge_op.outputs[0].name] = \ mge_op.inputs[0] # skip this reshape op continue self._op_converters[opr_type](mge_op) self.convert_tensors() def add_tensor(self, name, shape, data_type, value): tensor = self._mace_net_def.tensors.add() tensor.name = name tensor.dims.extend(list(shape)) tensor.data_type = data_type if data_type == mace_pb2.DT_INT32: tensor.int32_data.extend(value) else: tensor.float_data.extend(value) # convert all pre-calculated and constant tensors def convert_tensors(self): for mge_op in self._mge_operators: type_opr = mgb.cgtools.get_opr_type(mge_op) # all tensors generated by SharedDeviceTensor op if type_opr == "SharedDeviceTensor": output = mge_op.outputs[0] if output.name not in self._skip_tensors: nshape = output.imm_shape # tensor used for depthwise conv/deconv should be reshaped for_group_conv = is_consumer_group_conv( output, self._mge_var2oprs, self._mge_map_oprs ) if for_group_conv: nshape = ( 1, output.imm_shape[0], output.imm_shape[3], output.imm_shape[4], ) self.add_tensor( output.name, nshape, mace_pb2.DT_FLOAT, get_symvar_value(output).flatten()) else: # handle all constant values for const_tensor in mge_op.inputs: if (const_tensor.inferred_value is not None and const_tensor.name not in self._skip_tensors): self.add_tensor( const_tensor.name, const_tensor.imm_shape, mace_pb2.DT_INT32, const_tensor.inferred_value.flatten()) def convert_nop(self, mge_op): pass def convert_general_op(self, mge_op): op = self._mace_net_def.op.add() op.name = mge_op.name op.type =
mgb.cgtools.get_opr_type(mge_op)
megengine._internal.cgtools.get_opr_type
import os import math import numpy as np import six import megengine._internal as mgb from enum import Enum from py_proto import mace_pb2 from transform import base_converter from transform.base_converter import PoolingType from transform.base_converter import ActivationType from transform.base_converter import EltwiseType from transform.base_converter import FrameworkType from transform.base_converter import ReduceType from transform.base_converter import DataFormat from transform.base_converter import MaceOp from transform.base_converter import MaceKeyword from transform.base_converter import ConverterUtil from transform.base_converter import RoundMode from utils.util import mace_check mge_kernel_h_str = "window_h" mge_kernel_w_str = "window_w" mge_stride_h_str = "stride_h" mge_stride_w_str = "stride_w" mge_pad_h_str = "pad_h" mge_pad_w_str = "pad_w" mge_dilate_h_str = "dilate_h" mge_dilate_w_str = "dilate_w" MGESupportedOps = [ "AxisAddRemove", "BatchNormForward", "Concat", "ConvolutionForward", "ConvolutionBackwardData", "Dimshuffle", "Elemwise", "GetVarShape", "Host2DeviceCopy", "Identity", "MarkNoBroadcastElemwise", "MatrixMul", "PoolingForward", "Reduce", "Reshape", "SharedDeviceTensor", "Subtensor", ] MGEOpType = Enum("MGEOpType", [(op, op) for op in MGESupportedOps], type=str) def get_symvar_value(mge_symvar): if mge_symvar.inferred_value is not None: val = mge_symvar.inferred_value else: cg = mge_symvar.owner_graph func = cg.compile_outonly(mge_symvar) val = func() return val def is_consumer_group_conv(mge_symvar, var2oprs, map_oprs): consumer_ids = var2oprs[mge_symvar.id] n_consumers = len(consumer_ids) for consumer_id in consumer_ids: consumer_op = map_oprs[consumer_id[0]] if (mgb.cgtools.get_opr_type(consumer_op) in ("ConvolutionForward", "ConvolutionBackwardData") and consumer_op.params["sparse"] == "GROUP"): mace_check(n_consumers == 1, "This tensor should only feed depthwise conv/deconv") return True return False class MegengineConverter(base_converter.ConverterInterface): """A class for convert megengine dumped model to mace model.""" compute_format_type = { "NCHW": DataFormat.NCHW, "NHWC": DataFormat.NHWC, "DEFAULT": DataFormat.NCHW, } reduce_math_type = { "SUM": ReduceType.SUM, "PROD": ReduceType.PROD, "MIN": ReduceType.MIN, "MAX": ReduceType.MAX, } # SQE_DIFF, CLIP, SIGN maybe needed eltwise_type = { "ADD": EltwiseType.SUM, "SUB": EltwiseType.SUB, "MUL": EltwiseType.PROD, "TRUE_DIV": EltwiseType.DIV, "MIN": EltwiseType.MIN, "MAX": EltwiseType.MAX, "NEGATE": EltwiseType.NEG, "ABS": EltwiseType.ABS, "POW": EltwiseType.POW, "EQ": EltwiseType.EQUAL, "FLOOR_DIV": EltwiseType.FLOOR_DIV, "EXP": EltwiseType.POW, } activation_type = { "RELU": ActivationType.RELU, "TANH": ActivationType.TANH, "SIGMOID": ActivationType.SIGMOID, } def __init__(self, option, src_model_file): self._op_converters = { MGEOpType.AxisAddRemove.name: self.convert_axisaddrm, MGEOpType.BatchNormForward.name: self.convert_batchnorm, MGEOpType.Concat.name: self.convert_concat, MGEOpType.ConvolutionForward.name: self.convert_conv2d, MGEOpType.ConvolutionBackwardData.name: self.convert_deconv2d, MGEOpType.Dimshuffle.name: self.convert_dimshuffle, MGEOpType.Elemwise.name: self.convert_elemwise, MGEOpType.GetVarShape.name: self.convert_shape, MGEOpType.Host2DeviceCopy.name: self.convert_nop, MGEOpType.Identity.name: self.convert_identity, MGEOpType.MarkNoBroadcastElemwise.name: self.convert_identity, MGEOpType.MatrixMul.name: self.convert_matmul, MGEOpType.PoolingForward.name: self.convert_pooling, MGEOpType.Reduce.name: self.convert_reduce, MGEOpType.Reshape.name: self.convert_reshape, MGEOpType.SharedDeviceTensor.name: self.convert_nop, MGEOpType.Subtensor.name: self.convert_subtensor, } self._option = option self._mace_net_def = mace_pb2.NetDef() ConverterUtil.set_filter_format(self._mace_net_def, DataFormat.OIHW) ConverterUtil.add_data_format_arg(self._mace_net_def, DataFormat.NCHW) cg, _, outputs = mgb.load_comp_graph_from_file(src_model_file) map_oprs, _, var2oprs, *_ = mgb.cgtools.graph_traversal(outputs) # prune second input of reshape # because it introduces several ops, may increase the overhead operators = mgb.cgtools.get_oprs_seq(outputs, prune_reshape=True) self._mge_cg = cg self._mge_operators = operators self._mge_map_oprs = map_oprs self._mge_var2oprs = var2oprs self._skip_tensors = set() self._bn_statistis_tensors = {} def run(self): self.convert_ops() self.replace_input_output_tensor_name() return self._mace_net_def # only change the input/output tensor name for whole model def replace_input_output_tensor_name(self): for op in self._mace_net_def.op: for i in six.moves.range(len(op.input)): if "," in op.input[i]: op_name = op.input[i] op_name = op_name.replace(",", "#") if (op_name in self._option.input_nodes or op_name in self._option.output_nodes): op.input[i] = op_name for i in six.moves.range(len(op.output)): if "," in op.output[i]: op_name = op.output[i] op_name = op_name.replace(",", "#") if op_name in self._option.output_nodes: op.output[i] = op_name # this method will be called by convert_conv2d/deconv2d and convert_pooling @staticmethod def add_stride_pad_kernel_arg(params, op_def): stride = [params[mge_stride_h_str], params[mge_stride_w_str]] pad = [params[mge_pad_h_str] * 2, params[mge_pad_w_str] * 2] strides_arg = op_def.arg.add() strides_arg.name = MaceKeyword.mace_strides_str strides_arg.ints.extend(stride) padding_arg = op_def.arg.add() padding_arg.name = MaceKeyword.mace_padding_values_str padding_arg.ints.extend(pad) if op_def.type == MaceOp.Pooling.name: kernel = [params[mge_kernel_h_str], params[mge_kernel_w_str]] kernels_arg = op_def.arg.add() kernels_arg.name = MaceKeyword.mace_kernel_str kernels_arg.ints.extend(kernel) if op_def.type in (MaceOp.Conv2D.name, MaceOp.DepthwiseConv2d.name, MaceOp.Deconv2D.name, MaceOp.DepthwiseDeconv2d.name): dilation = [params[mge_dilate_h_str], params[mge_dilate_w_str]] dilation_arg = op_def.arg.add() dilation_arg.name = MaceKeyword.mace_dilations_str dilation_arg.ints.extend(dilation) def convert_ops(self): for mge_op in self._mge_operators: opr_type =
mgb.cgtools.get_opr_type(mge_op)
megengine._internal.cgtools.get_opr_type
import os import math import numpy as np import six import megengine._internal as mgb from enum import Enum from py_proto import mace_pb2 from transform import base_converter from transform.base_converter import PoolingType from transform.base_converter import ActivationType from transform.base_converter import EltwiseType from transform.base_converter import FrameworkType from transform.base_converter import ReduceType from transform.base_converter import DataFormat from transform.base_converter import MaceOp from transform.base_converter import MaceKeyword from transform.base_converter import ConverterUtil from transform.base_converter import RoundMode from utils.util import mace_check mge_kernel_h_str = "window_h" mge_kernel_w_str = "window_w" mge_stride_h_str = "stride_h" mge_stride_w_str = "stride_w" mge_pad_h_str = "pad_h" mge_pad_w_str = "pad_w" mge_dilate_h_str = "dilate_h" mge_dilate_w_str = "dilate_w" MGESupportedOps = [ "AxisAddRemove", "BatchNormForward", "Concat", "ConvolutionForward", "ConvolutionBackwardData", "Dimshuffle", "Elemwise", "GetVarShape", "Host2DeviceCopy", "Identity", "MarkNoBroadcastElemwise", "MatrixMul", "PoolingForward", "Reduce", "Reshape", "SharedDeviceTensor", "Subtensor", ] MGEOpType = Enum("MGEOpType", [(op, op) for op in MGESupportedOps], type=str) def get_symvar_value(mge_symvar): if mge_symvar.inferred_value is not None: val = mge_symvar.inferred_value else: cg = mge_symvar.owner_graph func = cg.compile_outonly(mge_symvar) val = func() return val def is_consumer_group_conv(mge_symvar, var2oprs, map_oprs): consumer_ids = var2oprs[mge_symvar.id] n_consumers = len(consumer_ids) for consumer_id in consumer_ids: consumer_op = map_oprs[consumer_id[0]] if (mgb.cgtools.get_opr_type(consumer_op) in ("ConvolutionForward", "ConvolutionBackwardData") and consumer_op.params["sparse"] == "GROUP"): mace_check(n_consumers == 1, "This tensor should only feed depthwise conv/deconv") return True return False class MegengineConverter(base_converter.ConverterInterface): """A class for convert megengine dumped model to mace model.""" compute_format_type = { "NCHW": DataFormat.NCHW, "NHWC": DataFormat.NHWC, "DEFAULT": DataFormat.NCHW, } reduce_math_type = { "SUM": ReduceType.SUM, "PROD": ReduceType.PROD, "MIN": ReduceType.MIN, "MAX": ReduceType.MAX, } # SQE_DIFF, CLIP, SIGN maybe needed eltwise_type = { "ADD": EltwiseType.SUM, "SUB": EltwiseType.SUB, "MUL": EltwiseType.PROD, "TRUE_DIV": EltwiseType.DIV, "MIN": EltwiseType.MIN, "MAX": EltwiseType.MAX, "NEGATE": EltwiseType.NEG, "ABS": EltwiseType.ABS, "POW": EltwiseType.POW, "EQ": EltwiseType.EQUAL, "FLOOR_DIV": EltwiseType.FLOOR_DIV, "EXP": EltwiseType.POW, } activation_type = { "RELU": ActivationType.RELU, "TANH": ActivationType.TANH, "SIGMOID": ActivationType.SIGMOID, } def __init__(self, option, src_model_file): self._op_converters = { MGEOpType.AxisAddRemove.name: self.convert_axisaddrm, MGEOpType.BatchNormForward.name: self.convert_batchnorm, MGEOpType.Concat.name: self.convert_concat, MGEOpType.ConvolutionForward.name: self.convert_conv2d, MGEOpType.ConvolutionBackwardData.name: self.convert_deconv2d, MGEOpType.Dimshuffle.name: self.convert_dimshuffle, MGEOpType.Elemwise.name: self.convert_elemwise, MGEOpType.GetVarShape.name: self.convert_shape, MGEOpType.Host2DeviceCopy.name: self.convert_nop, MGEOpType.Identity.name: self.convert_identity, MGEOpType.MarkNoBroadcastElemwise.name: self.convert_identity, MGEOpType.MatrixMul.name: self.convert_matmul, MGEOpType.PoolingForward.name: self.convert_pooling, MGEOpType.Reduce.name: self.convert_reduce, MGEOpType.Reshape.name: self.convert_reshape, MGEOpType.SharedDeviceTensor.name: self.convert_nop, MGEOpType.Subtensor.name: self.convert_subtensor, } self._option = option self._mace_net_def = mace_pb2.NetDef() ConverterUtil.set_filter_format(self._mace_net_def, DataFormat.OIHW) ConverterUtil.add_data_format_arg(self._mace_net_def, DataFormat.NCHW) cg, _, outputs = mgb.load_comp_graph_from_file(src_model_file) map_oprs, _, var2oprs, *_ = mgb.cgtools.graph_traversal(outputs) # prune second input of reshape # because it introduces several ops, may increase the overhead operators = mgb.cgtools.get_oprs_seq(outputs, prune_reshape=True) self._mge_cg = cg self._mge_operators = operators self._mge_map_oprs = map_oprs self._mge_var2oprs = var2oprs self._skip_tensors = set() self._bn_statistis_tensors = {} def run(self): self.convert_ops() self.replace_input_output_tensor_name() return self._mace_net_def # only change the input/output tensor name for whole model def replace_input_output_tensor_name(self): for op in self._mace_net_def.op: for i in six.moves.range(len(op.input)): if "," in op.input[i]: op_name = op.input[i] op_name = op_name.replace(",", "#") if (op_name in self._option.input_nodes or op_name in self._option.output_nodes): op.input[i] = op_name for i in six.moves.range(len(op.output)): if "," in op.output[i]: op_name = op.output[i] op_name = op_name.replace(",", "#") if op_name in self._option.output_nodes: op.output[i] = op_name # this method will be called by convert_conv2d/deconv2d and convert_pooling @staticmethod def add_stride_pad_kernel_arg(params, op_def): stride = [params[mge_stride_h_str], params[mge_stride_w_str]] pad = [params[mge_pad_h_str] * 2, params[mge_pad_w_str] * 2] strides_arg = op_def.arg.add() strides_arg.name = MaceKeyword.mace_strides_str strides_arg.ints.extend(stride) padding_arg = op_def.arg.add() padding_arg.name = MaceKeyword.mace_padding_values_str padding_arg.ints.extend(pad) if op_def.type == MaceOp.Pooling.name: kernel = [params[mge_kernel_h_str], params[mge_kernel_w_str]] kernels_arg = op_def.arg.add() kernels_arg.name = MaceKeyword.mace_kernel_str kernels_arg.ints.extend(kernel) if op_def.type in (MaceOp.Conv2D.name, MaceOp.DepthwiseConv2d.name, MaceOp.Deconv2D.name, MaceOp.DepthwiseDeconv2d.name): dilation = [params[mge_dilate_h_str], params[mge_dilate_w_str]] dilation_arg = op_def.arg.add() dilation_arg.name = MaceKeyword.mace_dilations_str dilation_arg.ints.extend(dilation) def convert_ops(self): for mge_op in self._mge_operators: opr_type = mgb.cgtools.get_opr_type(mge_op) # some reshape operators provide data for batchnorm if opr_type == "Reshape": output = mge_op.outputs[0] next_ops = self._mge_var2oprs[output.id] if len(next_ops) == 1: (next_op_id, _) = next_ops[0] next_op = self._mge_map_oprs[next_op_id] if mgb.cgtools.get_opr_type(next_op) == "BatchNormForward": self._skip_tensors.update( [inp.name for inp in mge_op.inputs]) # using output name to address input symbol var self._bn_statistis_tensors[mge_op.outputs[0].name] = \ mge_op.inputs[0] # skip this reshape op continue self._op_converters[opr_type](mge_op) self.convert_tensors() def add_tensor(self, name, shape, data_type, value): tensor = self._mace_net_def.tensors.add() tensor.name = name tensor.dims.extend(list(shape)) tensor.data_type = data_type if data_type == mace_pb2.DT_INT32: tensor.int32_data.extend(value) else: tensor.float_data.extend(value) # convert all pre-calculated and constant tensors def convert_tensors(self): for mge_op in self._mge_operators: type_opr =
mgb.cgtools.get_opr_type(mge_op)
megengine._internal.cgtools.get_opr_type
import os import math import numpy as np import six import megengine._internal as mgb from enum import Enum from py_proto import mace_pb2 from transform import base_converter from transform.base_converter import PoolingType from transform.base_converter import ActivationType from transform.base_converter import EltwiseType from transform.base_converter import FrameworkType from transform.base_converter import ReduceType from transform.base_converter import DataFormat from transform.base_converter import MaceOp from transform.base_converter import MaceKeyword from transform.base_converter import ConverterUtil from transform.base_converter import RoundMode from utils.util import mace_check mge_kernel_h_str = "window_h" mge_kernel_w_str = "window_w" mge_stride_h_str = "stride_h" mge_stride_w_str = "stride_w" mge_pad_h_str = "pad_h" mge_pad_w_str = "pad_w" mge_dilate_h_str = "dilate_h" mge_dilate_w_str = "dilate_w" MGESupportedOps = [ "AxisAddRemove", "BatchNormForward", "Concat", "ConvolutionForward", "ConvolutionBackwardData", "Dimshuffle", "Elemwise", "GetVarShape", "Host2DeviceCopy", "Identity", "MarkNoBroadcastElemwise", "MatrixMul", "PoolingForward", "Reduce", "Reshape", "SharedDeviceTensor", "Subtensor", ] MGEOpType = Enum("MGEOpType", [(op, op) for op in MGESupportedOps], type=str) def get_symvar_value(mge_symvar): if mge_symvar.inferred_value is not None: val = mge_symvar.inferred_value else: cg = mge_symvar.owner_graph func = cg.compile_outonly(mge_symvar) val = func() return val def is_consumer_group_conv(mge_symvar, var2oprs, map_oprs): consumer_ids = var2oprs[mge_symvar.id] n_consumers = len(consumer_ids) for consumer_id in consumer_ids: consumer_op = map_oprs[consumer_id[0]] if (
mgb.cgtools.get_opr_type(consumer_op)
megengine._internal.cgtools.get_opr_type
import os import math import numpy as np import six import megengine._internal as mgb from enum import Enum from py_proto import mace_pb2 from transform import base_converter from transform.base_converter import PoolingType from transform.base_converter import ActivationType from transform.base_converter import EltwiseType from transform.base_converter import FrameworkType from transform.base_converter import ReduceType from transform.base_converter import DataFormat from transform.base_converter import MaceOp from transform.base_converter import MaceKeyword from transform.base_converter import ConverterUtil from transform.base_converter import RoundMode from utils.util import mace_check mge_kernel_h_str = "window_h" mge_kernel_w_str = "window_w" mge_stride_h_str = "stride_h" mge_stride_w_str = "stride_w" mge_pad_h_str = "pad_h" mge_pad_w_str = "pad_w" mge_dilate_h_str = "dilate_h" mge_dilate_w_str = "dilate_w" MGESupportedOps = [ "AxisAddRemove", "BatchNormForward", "Concat", "ConvolutionForward", "ConvolutionBackwardData", "Dimshuffle", "Elemwise", "GetVarShape", "Host2DeviceCopy", "Identity", "MarkNoBroadcastElemwise", "MatrixMul", "PoolingForward", "Reduce", "Reshape", "SharedDeviceTensor", "Subtensor", ] MGEOpType = Enum("MGEOpType", [(op, op) for op in MGESupportedOps], type=str) def get_symvar_value(mge_symvar): if mge_symvar.inferred_value is not None: val = mge_symvar.inferred_value else: cg = mge_symvar.owner_graph func = cg.compile_outonly(mge_symvar) val = func() return val def is_consumer_group_conv(mge_symvar, var2oprs, map_oprs): consumer_ids = var2oprs[mge_symvar.id] n_consumers = len(consumer_ids) for consumer_id in consumer_ids: consumer_op = map_oprs[consumer_id[0]] if (mgb.cgtools.get_opr_type(consumer_op) in ("ConvolutionForward", "ConvolutionBackwardData") and consumer_op.params["sparse"] == "GROUP"): mace_check(n_consumers == 1, "This tensor should only feed depthwise conv/deconv") return True return False class MegengineConverter(base_converter.ConverterInterface): """A class for convert megengine dumped model to mace model.""" compute_format_type = { "NCHW": DataFormat.NCHW, "NHWC": DataFormat.NHWC, "DEFAULT": DataFormat.NCHW, } reduce_math_type = { "SUM": ReduceType.SUM, "PROD": ReduceType.PROD, "MIN": ReduceType.MIN, "MAX": ReduceType.MAX, } # SQE_DIFF, CLIP, SIGN maybe needed eltwise_type = { "ADD": EltwiseType.SUM, "SUB": EltwiseType.SUB, "MUL": EltwiseType.PROD, "TRUE_DIV": EltwiseType.DIV, "MIN": EltwiseType.MIN, "MAX": EltwiseType.MAX, "NEGATE": EltwiseType.NEG, "ABS": EltwiseType.ABS, "POW": EltwiseType.POW, "EQ": EltwiseType.EQUAL, "FLOOR_DIV": EltwiseType.FLOOR_DIV, "EXP": EltwiseType.POW, } activation_type = { "RELU": ActivationType.RELU, "TANH": ActivationType.TANH, "SIGMOID": ActivationType.SIGMOID, } def __init__(self, option, src_model_file): self._op_converters = { MGEOpType.AxisAddRemove.name: self.convert_axisaddrm, MGEOpType.BatchNormForward.name: self.convert_batchnorm, MGEOpType.Concat.name: self.convert_concat, MGEOpType.ConvolutionForward.name: self.convert_conv2d, MGEOpType.ConvolutionBackwardData.name: self.convert_deconv2d, MGEOpType.Dimshuffle.name: self.convert_dimshuffle, MGEOpType.Elemwise.name: self.convert_elemwise, MGEOpType.GetVarShape.name: self.convert_shape, MGEOpType.Host2DeviceCopy.name: self.convert_nop, MGEOpType.Identity.name: self.convert_identity, MGEOpType.MarkNoBroadcastElemwise.name: self.convert_identity, MGEOpType.MatrixMul.name: self.convert_matmul, MGEOpType.PoolingForward.name: self.convert_pooling, MGEOpType.Reduce.name: self.convert_reduce, MGEOpType.Reshape.name: self.convert_reshape, MGEOpType.SharedDeviceTensor.name: self.convert_nop, MGEOpType.Subtensor.name: self.convert_subtensor, } self._option = option self._mace_net_def = mace_pb2.NetDef() ConverterUtil.set_filter_format(self._mace_net_def, DataFormat.OIHW) ConverterUtil.add_data_format_arg(self._mace_net_def, DataFormat.NCHW) cg, _, outputs = mgb.load_comp_graph_from_file(src_model_file) map_oprs, _, var2oprs, *_ = mgb.cgtools.graph_traversal(outputs) # prune second input of reshape # because it introduces several ops, may increase the overhead operators = mgb.cgtools.get_oprs_seq(outputs, prune_reshape=True) self._mge_cg = cg self._mge_operators = operators self._mge_map_oprs = map_oprs self._mge_var2oprs = var2oprs self._skip_tensors = set() self._bn_statistis_tensors = {} def run(self): self.convert_ops() self.replace_input_output_tensor_name() return self._mace_net_def # only change the input/output tensor name for whole model def replace_input_output_tensor_name(self): for op in self._mace_net_def.op: for i in six.moves.range(len(op.input)): if "," in op.input[i]: op_name = op.input[i] op_name = op_name.replace(",", "#") if (op_name in self._option.input_nodes or op_name in self._option.output_nodes): op.input[i] = op_name for i in six.moves.range(len(op.output)): if "," in op.output[i]: op_name = op.output[i] op_name = op_name.replace(",", "#") if op_name in self._option.output_nodes: op.output[i] = op_name # this method will be called by convert_conv2d/deconv2d and convert_pooling @staticmethod def add_stride_pad_kernel_arg(params, op_def): stride = [params[mge_stride_h_str], params[mge_stride_w_str]] pad = [params[mge_pad_h_str] * 2, params[mge_pad_w_str] * 2] strides_arg = op_def.arg.add() strides_arg.name = MaceKeyword.mace_strides_str strides_arg.ints.extend(stride) padding_arg = op_def.arg.add() padding_arg.name = MaceKeyword.mace_padding_values_str padding_arg.ints.extend(pad) if op_def.type == MaceOp.Pooling.name: kernel = [params[mge_kernel_h_str], params[mge_kernel_w_str]] kernels_arg = op_def.arg.add() kernels_arg.name = MaceKeyword.mace_kernel_str kernels_arg.ints.extend(kernel) if op_def.type in (MaceOp.Conv2D.name, MaceOp.DepthwiseConv2d.name, MaceOp.Deconv2D.name, MaceOp.DepthwiseDeconv2d.name): dilation = [params[mge_dilate_h_str], params[mge_dilate_w_str]] dilation_arg = op_def.arg.add() dilation_arg.name = MaceKeyword.mace_dilations_str dilation_arg.ints.extend(dilation) def convert_ops(self): for mge_op in self._mge_operators: opr_type = mgb.cgtools.get_opr_type(mge_op) # some reshape operators provide data for batchnorm if opr_type == "Reshape": output = mge_op.outputs[0] next_ops = self._mge_var2oprs[output.id] if len(next_ops) == 1: (next_op_id, _) = next_ops[0] next_op = self._mge_map_oprs[next_op_id] if
mgb.cgtools.get_opr_type(next_op)
megengine._internal.cgtools.get_opr_type
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False), M.BatchNorm2d(8), M.ReLU(), M.MaxPool2d(kernel_size=2, stride=2), BasicBlock(8, 16), BasicBlock(16, 32, stride=2), BasicBlock(32, 64, stride=2), ) self.fc =
M.Linear(64, 9)
megengine.module.Linear
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False), M.BatchNorm2d(8), M.ReLU(), M.MaxPool2d(kernel_size=2, stride=2), BasicBlock(8, 16), BasicBlock(16, 32, stride=2), BasicBlock(32, 64, stride=2), ) self.fc = M.Linear(64, 9) def _get_transformed_image(self, image, mat3x3): """apply perspective transform to the image note: there is NO need to guarantee the bottom right element equals 1 Args: image (Tensor): input images (shape: n * 3 * 112 * 112) mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) Returns: transformed_image (Tensor): perspectively transformed image """ s = self.input_size transformed_image =
F.warp_perspective(image, mat3x3, [s, s])
megengine.functional.warp_perspective
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False), M.BatchNorm2d(8), M.ReLU(), M.MaxPool2d(kernel_size=2, stride=2), BasicBlock(8, 16), BasicBlock(16, 32, stride=2), BasicBlock(32, 64, stride=2), ) self.fc = M.Linear(64, 9) def _get_transformed_image(self, image, mat3x3): """apply perspective transform to the image note: there is NO need to guarantee the bottom right element equals 1 Args: image (Tensor): input images (shape: n * 3 * 112 * 112) mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) Returns: transformed_image (Tensor): perspectively transformed image """ s = self.input_size transformed_image = F.warp_perspective(image, mat3x3, [s, s]) return transformed_image def _get_mat3x3(self, image): """get perspective matrix used in the transformation note: there are only 8 degrees of freedom in a perspective matrix, while the output matrix has 9 variables. Args: image (Tensor): input images (shape: n * 3 * 112 * 112) Returns: mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) """ x = self.stem(image) x =
F.avg_pool2d(x, 7)
megengine.functional.avg_pool2d
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False), M.BatchNorm2d(8), M.ReLU(), M.MaxPool2d(kernel_size=2, stride=2), BasicBlock(8, 16), BasicBlock(16, 32, stride=2), BasicBlock(32, 64, stride=2), ) self.fc = M.Linear(64, 9) def _get_transformed_image(self, image, mat3x3): """apply perspective transform to the image note: there is NO need to guarantee the bottom right element equals 1 Args: image (Tensor): input images (shape: n * 3 * 112 * 112) mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) Returns: transformed_image (Tensor): perspectively transformed image """ s = self.input_size transformed_image = F.warp_perspective(image, mat3x3, [s, s]) return transformed_image def _get_mat3x3(self, image): """get perspective matrix used in the transformation note: there are only 8 degrees of freedom in a perspective matrix, while the output matrix has 9 variables. Args: image (Tensor): input images (shape: n * 3 * 112 * 112) Returns: mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) """ x = self.stem(image) x = F.avg_pool2d(x, 7) x =
F.flatten(x, 1)
megengine.functional.flatten
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False), M.BatchNorm2d(8), M.ReLU(), M.MaxPool2d(kernel_size=2, stride=2), BasicBlock(8, 16), BasicBlock(16, 32, stride=2), BasicBlock(32, 64, stride=2), ) self.fc = M.Linear(64, 9) def _get_transformed_image(self, image, mat3x3): """apply perspective transform to the image note: there is NO need to guarantee the bottom right element equals 1 Args: image (Tensor): input images (shape: n * 3 * 112 * 112) mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) Returns: transformed_image (Tensor): perspectively transformed image """ s = self.input_size transformed_image = F.warp_perspective(image, mat3x3, [s, s]) return transformed_image def _get_mat3x3(self, image): """get perspective matrix used in the transformation note: there are only 8 degrees of freedom in a perspective matrix, while the output matrix has 9 variables. Args: image (Tensor): input images (shape: n * 3 * 112 * 112) Returns: mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) """ x = self.stem(image) x = F.avg_pool2d(x, 7) x = F.flatten(x, 1) x = self.fc(x) s = self.input_size # 0.01 here is a magic number. it aims to maintain identity transform at early stage of training residual = x.reshape(-1, 3, 3) * 0.01 base = mge.tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).astype("float32") base =
F.broadcast_to(base, residual.shape)
megengine.functional.broadcast_to
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False), M.BatchNorm2d(8), M.ReLU(), M.MaxPool2d(kernel_size=2, stride=2), BasicBlock(8, 16), BasicBlock(16, 32, stride=2), BasicBlock(32, 64, stride=2), ) self.fc = M.Linear(64, 9) def _get_transformed_image(self, image, mat3x3): """apply perspective transform to the image note: there is NO need to guarantee the bottom right element equals 1 Args: image (Tensor): input images (shape: n * 3 * 112 * 112) mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) Returns: transformed_image (Tensor): perspectively transformed image """ s = self.input_size transformed_image = F.warp_perspective(image, mat3x3, [s, s]) return transformed_image def _get_mat3x3(self, image): """get perspective matrix used in the transformation note: there are only 8 degrees of freedom in a perspective matrix, while the output matrix has 9 variables. Args: image (Tensor): input images (shape: n * 3 * 112 * 112) Returns: mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) """ x = self.stem(image) x = F.avg_pool2d(x, 7) x = F.flatten(x, 1) x = self.fc(x) s = self.input_size # 0.01 here is a magic number. it aims to maintain identity transform at early stage of training residual = x.reshape(-1, 3, 3) * 0.01 base = mge.tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).astype("float32") base = F.broadcast_to(base, residual.shape) left_scale = mge.tensor([[s, 0, 0], [0, s, 0], [0, 0, 1]]).astype("float32") left_scale =
F.broadcast_to(left_scale, residual.shape)
megengine.functional.broadcast_to
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False), M.BatchNorm2d(8), M.ReLU(), M.MaxPool2d(kernel_size=2, stride=2), BasicBlock(8, 16), BasicBlock(16, 32, stride=2), BasicBlock(32, 64, stride=2), ) self.fc = M.Linear(64, 9) def _get_transformed_image(self, image, mat3x3): """apply perspective transform to the image note: there is NO need to guarantee the bottom right element equals 1 Args: image (Tensor): input images (shape: n * 3 * 112 * 112) mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) Returns: transformed_image (Tensor): perspectively transformed image """ s = self.input_size transformed_image = F.warp_perspective(image, mat3x3, [s, s]) return transformed_image def _get_mat3x3(self, image): """get perspective matrix used in the transformation note: there are only 8 degrees of freedom in a perspective matrix, while the output matrix has 9 variables. Args: image (Tensor): input images (shape: n * 3 * 112 * 112) Returns: mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) """ x = self.stem(image) x = F.avg_pool2d(x, 7) x = F.flatten(x, 1) x = self.fc(x) s = self.input_size # 0.01 here is a magic number. it aims to maintain identity transform at early stage of training residual = x.reshape(-1, 3, 3) * 0.01 base = mge.tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).astype("float32") base = F.broadcast_to(base, residual.shape) left_scale = mge.tensor([[s, 0, 0], [0, s, 0], [0, 0, 1]]).astype("float32") left_scale = F.broadcast_to(left_scale, residual.shape) right_scale = mge.tensor([[1 / s, 0, 0], [0, 1 / s, 0], [0, 0, 1]]).astype("float32") right_scale =
F.broadcast_to(right_scale, residual.shape)
megengine.functional.broadcast_to
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential(
M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False)
megengine.module.Conv2d
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False),
M.BatchNorm2d(8)
megengine.module.BatchNorm2d
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False), M.BatchNorm2d(8),
M.ReLU()
megengine.module.ReLU
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False), M.BatchNorm2d(8), M.ReLU(),
M.MaxPool2d(kernel_size=2, stride=2)
megengine.module.MaxPool2d
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False), M.BatchNorm2d(8), M.ReLU(), M.MaxPool2d(kernel_size=2, stride=2), BasicBlock(8, 16), BasicBlock(16, 32, stride=2), BasicBlock(32, 64, stride=2), ) self.fc = M.Linear(64, 9) def _get_transformed_image(self, image, mat3x3): """apply perspective transform to the image note: there is NO need to guarantee the bottom right element equals 1 Args: image (Tensor): input images (shape: n * 3 * 112 * 112) mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) Returns: transformed_image (Tensor): perspectively transformed image """ s = self.input_size transformed_image = F.warp_perspective(image, mat3x3, [s, s]) return transformed_image def _get_mat3x3(self, image): """get perspective matrix used in the transformation note: there are only 8 degrees of freedom in a perspective matrix, while the output matrix has 9 variables. Args: image (Tensor): input images (shape: n * 3 * 112 * 112) Returns: mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) """ x = self.stem(image) x = F.avg_pool2d(x, 7) x = F.flatten(x, 1) x = self.fc(x) s = self.input_size # 0.01 here is a magic number. it aims to maintain identity transform at early stage of training residual = x.reshape(-1, 3, 3) * 0.01 base = mge.tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).astype("float32") base = F.broadcast_to(base, residual.shape) left_scale = mge.tensor([[s, 0, 0], [0, s, 0], [0, 0, 1]]).astype("float32") left_scale = F.broadcast_to(left_scale, residual.shape) right_scale = mge.tensor([[1 / s, 0, 0], [0, 1 / s, 0], [0, 0, 1]]).astype("float32") right_scale = F.broadcast_to(right_scale, residual.shape) mat3x3 = F.matmul(left_scale,
F.matmul(base + residual, right_scale)
megengine.functional.matmul
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False), M.BatchNorm2d(8), M.ReLU(), M.MaxPool2d(kernel_size=2, stride=2), BasicBlock(8, 16), BasicBlock(16, 32, stride=2), BasicBlock(32, 64, stride=2), ) self.fc = M.Linear(64, 9) def _get_transformed_image(self, image, mat3x3): """apply perspective transform to the image note: there is NO need to guarantee the bottom right element equals 1 Args: image (Tensor): input images (shape: n * 3 * 112 * 112) mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) Returns: transformed_image (Tensor): perspectively transformed image """ s = self.input_size transformed_image = F.warp_perspective(image, mat3x3, [s, s]) return transformed_image def _get_mat3x3(self, image): """get perspective matrix used in the transformation note: there are only 8 degrees of freedom in a perspective matrix, while the output matrix has 9 variables. Args: image (Tensor): input images (shape: n * 3 * 112 * 112) Returns: mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) """ x = self.stem(image) x = F.avg_pool2d(x, 7) x = F.flatten(x, 1) x = self.fc(x) s = self.input_size # 0.01 here is a magic number. it aims to maintain identity transform at early stage of training residual = x.reshape(-1, 3, 3) * 0.01 base =
mge.tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
megengine.tensor
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False), M.BatchNorm2d(8), M.ReLU(), M.MaxPool2d(kernel_size=2, stride=2), BasicBlock(8, 16), BasicBlock(16, 32, stride=2), BasicBlock(32, 64, stride=2), ) self.fc = M.Linear(64, 9) def _get_transformed_image(self, image, mat3x3): """apply perspective transform to the image note: there is NO need to guarantee the bottom right element equals 1 Args: image (Tensor): input images (shape: n * 3 * 112 * 112) mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) Returns: transformed_image (Tensor): perspectively transformed image """ s = self.input_size transformed_image = F.warp_perspective(image, mat3x3, [s, s]) return transformed_image def _get_mat3x3(self, image): """get perspective matrix used in the transformation note: there are only 8 degrees of freedom in a perspective matrix, while the output matrix has 9 variables. Args: image (Tensor): input images (shape: n * 3 * 112 * 112) Returns: mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) """ x = self.stem(image) x = F.avg_pool2d(x, 7) x = F.flatten(x, 1) x = self.fc(x) s = self.input_size # 0.01 here is a magic number. it aims to maintain identity transform at early stage of training residual = x.reshape(-1, 3, 3) * 0.01 base = mge.tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).astype("float32") base = F.broadcast_to(base, residual.shape) left_scale =
mge.tensor([[s, 0, 0], [0, s, 0], [0, 0, 1]])
megengine.tensor
# Copyright (c) Megvii, Inc. and its affiliates. import megengine as mge import megengine.functional as F import megengine.module as M from .resnet import BasicBlock class STN(M.Module): """spatial transformer networks from `"Spatial Transformer Networks" <https://arxiv.org/pdf/1506.02025.pdf>`_ some detailed implements are highly simplified while good performance maintained """ def __init__(self, input_size=112): assert input_size == 112, f"expected input_size == 112, got {input_size}" super().__init__() self.input_size = input_size self.stem = M.Sequential( M.Conv2d(3, 8, kernel_size=3, stride=2, padding=1, bias=False), M.BatchNorm2d(8), M.ReLU(), M.MaxPool2d(kernel_size=2, stride=2), BasicBlock(8, 16), BasicBlock(16, 32, stride=2), BasicBlock(32, 64, stride=2), ) self.fc = M.Linear(64, 9) def _get_transformed_image(self, image, mat3x3): """apply perspective transform to the image note: there is NO need to guarantee the bottom right element equals 1 Args: image (Tensor): input images (shape: n * 3 * 112 * 112) mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) Returns: transformed_image (Tensor): perspectively transformed image """ s = self.input_size transformed_image = F.warp_perspective(image, mat3x3, [s, s]) return transformed_image def _get_mat3x3(self, image): """get perspective matrix used in the transformation note: there are only 8 degrees of freedom in a perspective matrix, while the output matrix has 9 variables. Args: image (Tensor): input images (shape: n * 3 * 112 * 112) Returns: mat3x3 (Tensor): perspective matrix (shape: n * 3 * 3) """ x = self.stem(image) x = F.avg_pool2d(x, 7) x = F.flatten(x, 1) x = self.fc(x) s = self.input_size # 0.01 here is a magic number. it aims to maintain identity transform at early stage of training residual = x.reshape(-1, 3, 3) * 0.01 base = mge.tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).astype("float32") base = F.broadcast_to(base, residual.shape) left_scale = mge.tensor([[s, 0, 0], [0, s, 0], [0, 0, 1]]).astype("float32") left_scale = F.broadcast_to(left_scale, residual.shape) right_scale =
mge.tensor([[1 / s, 0, 0], [0, 1 / s, 0], [0, 0, 1]])
megengine.tensor
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import numpy as np import megengine as mge import megengine.functional as F import megengine.module as M from megengine.core import tensor def test_mge_81(): np.random.seed(0) N, D = 3, 4 x = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) y = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) z = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) a = x * y b = a + z c =
F.sum(b)
megengine.functional.sum
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import numpy as np import megengine as mge import megengine.functional as F import megengine.module as M from megengine.core import tensor def test_mge_81(): np.random.seed(0) N, D = 3, 4 x = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) y = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) z = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) a = x * y b = a + z c = F.sum(b) grad_x =
F.grad(c, x, use_virtual_grad=False)
megengine.functional.grad
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import numpy as np import megengine as mge import megengine.functional as F import megengine.module as M from megengine.core import tensor def test_mge_81(): np.random.seed(0) N, D = 3, 4 x = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) y = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) z = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) a = x * y b = a + z c = F.sum(b) grad_x = F.grad(c, x, use_virtual_grad=False) grad_y =
F.grad(c, y, use_virtual_grad=False)
megengine.functional.grad
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import numpy as np import megengine as mge import megengine.functional as F import megengine.module as M from megengine.core import tensor def test_mge_81(): np.random.seed(0) N, D = 3, 4 x = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) y = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) z = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) a = x * y b = a + z c = F.sum(b) grad_x = F.grad(c, x, use_virtual_grad=False) grad_y = F.grad(c, y, use_virtual_grad=False) grad_z =
F.grad(c, z, use_virtual_grad=False)
megengine.functional.grad
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import numpy as np import megengine as mge import megengine.functional as F import megengine.module as M from megengine.core import tensor def test_mge_81(): np.random.seed(0) N, D = 3, 4 x = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) y = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) z = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) a = x * y b = a + z c = F.sum(b) grad_x = F.grad(c, x, use_virtual_grad=False) grad_y = F.grad(c, y, use_virtual_grad=False) grad_z = F.grad(c, z, use_virtual_grad=False) print(grad_x.numpy()) print(grad_y.numpy()) print(grad_z.numpy()) m =
M.BatchNorm2d(4)
megengine.module.BatchNorm2d
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import numpy as np import megengine as mge import megengine.functional as F import megengine.module as M from megengine.core import tensor def test_mge_81(): np.random.seed(0) N, D = 3, 4 x = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) y = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) z = mge.Parameter(value=np.random.normal(size=(N, D)).astype(np.float32)) a = x * y b = a + z c = F.sum(b) grad_x = F.grad(c, x, use_virtual_grad=False) grad_y = F.grad(c, y, use_virtual_grad=False) grad_z = F.grad(c, z, use_virtual_grad=False) print(grad_x.numpy()) print(grad_y.numpy()) print(grad_z.numpy()) m = M.BatchNorm2d(4) input = tensor(np.zeros((64, 4, 32, 32), dtype=np.float32)) _ = m(input) m =
M.BatchNorm2d(4, affine=False)
megengine.module.BatchNorm2d
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # This repo is licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import math import collections import megengine.module as nn import megengine.functional as F from model.nn_upsample import NeuralUpsampler, FlowMaskEstimator from common.utils import flow_warp, upsample2d_flow_as def conv(inp, out, k=3, s=1, d=1, isReLU=True): if isReLU: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True), nn.LeakyReLU(0.1)) else: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True)) return ret class ContextNetwork(nn.Module): def __init__(self, ch_in): super(ContextNetwork, self).__init__() self.convs = nn.Sequential(conv(ch_in, 128, 3, 1, 1), conv(128, 128, 3, 1, 2), conv(128, 128, 3, 1, 4), conv(128, 96, 3, 1, 8), conv(96, 64, 3, 1, 16), conv(64, 32, 3, 1, 1), conv(32, 2, isReLU=False)) def forward(self, x): return self.convs(x) class FlowEstimator(nn.Module): def __init__(self, ch_in): super(FlowEstimator, self).__init__() self.conv1 = conv(ch_in, 128) self.conv2 = conv(128, 128) self.conv3 = conv(128 + 128, 96) self.conv4 = conv(96 + 128, 64) self.conv5 = conv(96 + 64, 32) # channels of the second last layer self.feat_dim = 32 self.predict_flow = conv(64 + 32, 2, isReLU=False) def forward(self, x): x1 = self.conv1(x) x2 = self.conv2(x1) x3 = self.conv3(F.concat([x1, x2], axis=1)) x4 = self.conv4(F.concat([x2, x3], axis=1)) x5 = self.conv5(F.concat([x3, x4], axis=1)) flow = self.predict_flow(F.concat([x4, x5], axis=1)) return x5, flow class CostVolume(nn.Module): def __init__(self, d=4, *args, **kwargs): super(CostVolume, self).__init__() self.d = d self.out_dim = 2 * self.d + 1 self.pad_size = self.d def forward(self, x1, x2): _, _, H, W = x1.shape x2 =
F.nn.pad(x2, ((0, 0), (0, 0), (self.pad_size, self.pad_size), (self.pad_size, self.pad_size)))
megengine.functional.nn.pad
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # This repo is licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import math import collections import megengine.module as nn import megengine.functional as F from model.nn_upsample import NeuralUpsampler, FlowMaskEstimator from common.utils import flow_warp, upsample2d_flow_as def conv(inp, out, k=3, s=1, d=1, isReLU=True): if isReLU: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True), nn.LeakyReLU(0.1)) else: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True)) return ret class ContextNetwork(nn.Module): def __init__(self, ch_in): super(ContextNetwork, self).__init__() self.convs = nn.Sequential(conv(ch_in, 128, 3, 1, 1), conv(128, 128, 3, 1, 2), conv(128, 128, 3, 1, 4), conv(128, 96, 3, 1, 8), conv(96, 64, 3, 1, 16), conv(64, 32, 3, 1, 1), conv(32, 2, isReLU=False)) def forward(self, x): return self.convs(x) class FlowEstimator(nn.Module): def __init__(self, ch_in): super(FlowEstimator, self).__init__() self.conv1 = conv(ch_in, 128) self.conv2 = conv(128, 128) self.conv3 = conv(128 + 128, 96) self.conv4 = conv(96 + 128, 64) self.conv5 = conv(96 + 64, 32) # channels of the second last layer self.feat_dim = 32 self.predict_flow = conv(64 + 32, 2, isReLU=False) def forward(self, x): x1 = self.conv1(x) x2 = self.conv2(x1) x3 = self.conv3(F.concat([x1, x2], axis=1)) x4 = self.conv4(F.concat([x2, x3], axis=1)) x5 = self.conv5(F.concat([x3, x4], axis=1)) flow = self.predict_flow(F.concat([x4, x5], axis=1)) return x5, flow class CostVolume(nn.Module): def __init__(self, d=4, *args, **kwargs): super(CostVolume, self).__init__() self.d = d self.out_dim = 2 * self.d + 1 self.pad_size = self.d def forward(self, x1, x2): _, _, H, W = x1.shape x2 = F.nn.pad(x2, ((0, 0), (0, 0), (self.pad_size, self.pad_size), (self.pad_size, self.pad_size))) cv = [] for i in range(self.out_dim): for j in range(self.out_dim): cost = x1 * x2[:, :, i:(i + H), j:(j + W)] cost = F.mean(cost, 1, keepdims=True) cv.append(cost) return
F.concat(cv, 1)
megengine.functional.concat
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # This repo is licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import math import collections import megengine.module as nn import megengine.functional as F from model.nn_upsample import NeuralUpsampler, FlowMaskEstimator from common.utils import flow_warp, upsample2d_flow_as def conv(inp, out, k=3, s=1, d=1, isReLU=True): if isReLU: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True), nn.LeakyReLU(0.1)) else: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True)) return ret class ContextNetwork(nn.Module): def __init__(self, ch_in): super(ContextNetwork, self).__init__() self.convs = nn.Sequential(conv(ch_in, 128, 3, 1, 1), conv(128, 128, 3, 1, 2), conv(128, 128, 3, 1, 4), conv(128, 96, 3, 1, 8), conv(96, 64, 3, 1, 16), conv(64, 32, 3, 1, 1), conv(32, 2, isReLU=False)) def forward(self, x): return self.convs(x) class FlowEstimator(nn.Module): def __init__(self, ch_in): super(FlowEstimator, self).__init__() self.conv1 = conv(ch_in, 128) self.conv2 = conv(128, 128) self.conv3 = conv(128 + 128, 96) self.conv4 = conv(96 + 128, 64) self.conv5 = conv(96 + 64, 32) # channels of the second last layer self.feat_dim = 32 self.predict_flow = conv(64 + 32, 2, isReLU=False) def forward(self, x): x1 = self.conv1(x) x2 = self.conv2(x1) x3 = self.conv3(F.concat([x1, x2], axis=1)) x4 = self.conv4(F.concat([x2, x3], axis=1)) x5 = self.conv5(F.concat([x3, x4], axis=1)) flow = self.predict_flow(F.concat([x4, x5], axis=1)) return x5, flow class CostVolume(nn.Module): def __init__(self, d=4, *args, **kwargs): super(CostVolume, self).__init__() self.d = d self.out_dim = 2 * self.d + 1 self.pad_size = self.d def forward(self, x1, x2): _, _, H, W = x1.shape x2 = F.nn.pad(x2, ((0, 0), (0, 0), (self.pad_size, self.pad_size), (self.pad_size, self.pad_size))) cv = [] for i in range(self.out_dim): for j in range(self.out_dim): cost = x1 * x2[:, :, i:(i + H), j:(j + W)] cost = F.mean(cost, 1, keepdims=True) cv.append(cost) return F.concat(cv, 1) class FeaturePyramidExtractor(nn.Module): def __init__(self, pyr_chans): super(FeaturePyramidExtractor, self).__init__() self.pyr_chans = pyr_chans self.convs = [] for _, (ch_in, ch_out) in enumerate(zip(pyr_chans[:-1], pyr_chans[1:])): layer = nn.Sequential(conv(ch_in, ch_out, s=2), conv(ch_out, ch_out)) self.convs.append(layer) def forward(self, x): feature_pyramid = [] for conv in self.convs: x = conv(x) feature_pyramid.append(x) return feature_pyramid[::-1] class GyroFlow(nn.Module): def __init__(self, params): super(GyroFlow, self).__init__() self.leakyRELU =
nn.LeakyReLU(0.1)
megengine.module.LeakyReLU
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # This repo is licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import math import collections import megengine.module as nn import megengine.functional as F from model.nn_upsample import NeuralUpsampler, FlowMaskEstimator from common.utils import flow_warp, upsample2d_flow_as def conv(inp, out, k=3, s=1, d=1, isReLU=True): if isReLU: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True), nn.LeakyReLU(0.1)) else: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True)) return ret class ContextNetwork(nn.Module): def __init__(self, ch_in): super(ContextNetwork, self).__init__() self.convs = nn.Sequential(conv(ch_in, 128, 3, 1, 1), conv(128, 128, 3, 1, 2), conv(128, 128, 3, 1, 4), conv(128, 96, 3, 1, 8), conv(96, 64, 3, 1, 16), conv(64, 32, 3, 1, 1), conv(32, 2, isReLU=False)) def forward(self, x): return self.convs(x) class FlowEstimator(nn.Module): def __init__(self, ch_in): super(FlowEstimator, self).__init__() self.conv1 = conv(ch_in, 128) self.conv2 = conv(128, 128) self.conv3 = conv(128 + 128, 96) self.conv4 = conv(96 + 128, 64) self.conv5 = conv(96 + 64, 32) # channels of the second last layer self.feat_dim = 32 self.predict_flow = conv(64 + 32, 2, isReLU=False) def forward(self, x): x1 = self.conv1(x) x2 = self.conv2(x1) x3 = self.conv3(F.concat([x1, x2], axis=1)) x4 = self.conv4(F.concat([x2, x3], axis=1)) x5 = self.conv5(F.concat([x3, x4], axis=1)) flow = self.predict_flow(F.concat([x4, x5], axis=1)) return x5, flow class CostVolume(nn.Module): def __init__(self, d=4, *args, **kwargs): super(CostVolume, self).__init__() self.d = d self.out_dim = 2 * self.d + 1 self.pad_size = self.d def forward(self, x1, x2): _, _, H, W = x1.shape x2 = F.nn.pad(x2, ((0, 0), (0, 0), (self.pad_size, self.pad_size), (self.pad_size, self.pad_size))) cv = [] for i in range(self.out_dim): for j in range(self.out_dim): cost = x1 * x2[:, :, i:(i + H), j:(j + W)] cost = F.mean(cost, 1, keepdims=True) cv.append(cost) return F.concat(cv, 1) class FeaturePyramidExtractor(nn.Module): def __init__(self, pyr_chans): super(FeaturePyramidExtractor, self).__init__() self.pyr_chans = pyr_chans self.convs = [] for _, (ch_in, ch_out) in enumerate(zip(pyr_chans[:-1], pyr_chans[1:])): layer = nn.Sequential(conv(ch_in, ch_out, s=2), conv(ch_out, ch_out)) self.convs.append(layer) def forward(self, x): feature_pyramid = [] for conv in self.convs: x = conv(x) feature_pyramid.append(x) return feature_pyramid[::-1] class GyroFlow(nn.Module): def __init__(self, params): super(GyroFlow, self).__init__() self.leakyRELU = nn.LeakyReLU(0.1) self.upsample = params.upsample self.with_bk = True self.pyr_chans = [3, 16, 32, 64, 96, 128, 192] self.feature_pyramid_extractor = FeaturePyramidExtractor(self.pyr_chans) # correlation range self.d = 4 self.output_level = 4 # cost volume self.cost_volume = CostVolume(d=self.d) self.cv_dim = (self.d * 2 + 1)**2 self.upsampler = NeuralUpsampler() self.ch_inp = 32 + self.cv_dim + 2 self.flow_estimator = FlowEstimator(self.ch_inp) self.context_net = ContextNetwork(self.flow_estimator.feat_dim + 2) self.conv_1x1 = list([ conv(192, 32, k=1, s=1, d=1), conv(128, 32, k=1, s=1, d=1), conv(96, 32, k=1, s=1, d=1), conv(64, 32, k=1, s=1, d=1), conv(32, 32, k=1, s=1, d=1) ]) self.with_gyro_field = True self.flow_predictor = FlowMaskEstimator(4, (8, 16, 32, 16, 8), 2) self.mask_predictor = FlowMaskEstimator(64, (32, 32, 32, 16, 8), 1) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.msra_normal_(m.weight, a=math.sqrt(5)) if m.bias is not None: fan_in, _ = nn.init.calculate_fan_in_and_fan_out(m.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(m.bias, -bound, bound) def generate_fused_flow(self, x1, x2): input_feature =
F.concat((x1, x2), axis=1)
megengine.functional.concat
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # This repo is licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import math import collections import megengine.module as nn import megengine.functional as F from model.nn_upsample import NeuralUpsampler, FlowMaskEstimator from common.utils import flow_warp, upsample2d_flow_as def conv(inp, out, k=3, s=1, d=1, isReLU=True): if isReLU: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True), nn.LeakyReLU(0.1)) else: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True)) return ret class ContextNetwork(nn.Module): def __init__(self, ch_in): super(ContextNetwork, self).__init__() self.convs = nn.Sequential(conv(ch_in, 128, 3, 1, 1), conv(128, 128, 3, 1, 2), conv(128, 128, 3, 1, 4), conv(128, 96, 3, 1, 8), conv(96, 64, 3, 1, 16), conv(64, 32, 3, 1, 1), conv(32, 2, isReLU=False)) def forward(self, x): return self.convs(x) class FlowEstimator(nn.Module): def __init__(self, ch_in): super(FlowEstimator, self).__init__() self.conv1 = conv(ch_in, 128) self.conv2 = conv(128, 128) self.conv3 = conv(128 + 128, 96) self.conv4 = conv(96 + 128, 64) self.conv5 = conv(96 + 64, 32) # channels of the second last layer self.feat_dim = 32 self.predict_flow = conv(64 + 32, 2, isReLU=False) def forward(self, x): x1 = self.conv1(x) x2 = self.conv2(x1) x3 = self.conv3(F.concat([x1, x2], axis=1)) x4 = self.conv4(F.concat([x2, x3], axis=1)) x5 = self.conv5(F.concat([x3, x4], axis=1)) flow = self.predict_flow(F.concat([x4, x5], axis=1)) return x5, flow class CostVolume(nn.Module): def __init__(self, d=4, *args, **kwargs): super(CostVolume, self).__init__() self.d = d self.out_dim = 2 * self.d + 1 self.pad_size = self.d def forward(self, x1, x2): _, _, H, W = x1.shape x2 = F.nn.pad(x2, ((0, 0), (0, 0), (self.pad_size, self.pad_size), (self.pad_size, self.pad_size))) cv = [] for i in range(self.out_dim): for j in range(self.out_dim): cost = x1 * x2[:, :, i:(i + H), j:(j + W)] cost = F.mean(cost, 1, keepdims=True) cv.append(cost) return F.concat(cv, 1) class FeaturePyramidExtractor(nn.Module): def __init__(self, pyr_chans): super(FeaturePyramidExtractor, self).__init__() self.pyr_chans = pyr_chans self.convs = [] for _, (ch_in, ch_out) in enumerate(zip(pyr_chans[:-1], pyr_chans[1:])): layer = nn.Sequential(conv(ch_in, ch_out, s=2), conv(ch_out, ch_out)) self.convs.append(layer) def forward(self, x): feature_pyramid = [] for conv in self.convs: x = conv(x) feature_pyramid.append(x) return feature_pyramid[::-1] class GyroFlow(nn.Module): def __init__(self, params): super(GyroFlow, self).__init__() self.leakyRELU = nn.LeakyReLU(0.1) self.upsample = params.upsample self.with_bk = True self.pyr_chans = [3, 16, 32, 64, 96, 128, 192] self.feature_pyramid_extractor = FeaturePyramidExtractor(self.pyr_chans) # correlation range self.d = 4 self.output_level = 4 # cost volume self.cost_volume = CostVolume(d=self.d) self.cv_dim = (self.d * 2 + 1)**2 self.upsampler = NeuralUpsampler() self.ch_inp = 32 + self.cv_dim + 2 self.flow_estimator = FlowEstimator(self.ch_inp) self.context_net = ContextNetwork(self.flow_estimator.feat_dim + 2) self.conv_1x1 = list([ conv(192, 32, k=1, s=1, d=1), conv(128, 32, k=1, s=1, d=1), conv(96, 32, k=1, s=1, d=1), conv(64, 32, k=1, s=1, d=1), conv(32, 32, k=1, s=1, d=1) ]) self.with_gyro_field = True self.flow_predictor = FlowMaskEstimator(4, (8, 16, 32, 16, 8), 2) self.mask_predictor = FlowMaskEstimator(64, (32, 32, 32, 16, 8), 1) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.msra_normal_(m.weight, a=math.sqrt(5)) if m.bias is not None: fan_in, _ = nn.init.calculate_fan_in_and_fan_out(m.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(m.bias, -bound, bound) def generate_fused_flow(self, x1, x2): input_feature = F.concat((x1, x2), axis=1) flow = self.flow_predictor(input_feature)[1] assert flow.shape[1] == 2 return flow def generate_map(self, x1, x2): input_feature =
F.concat((x1, x2), axis=1)
megengine.functional.concat
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # This repo is licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import math import collections import megengine.module as nn import megengine.functional as F from model.nn_upsample import NeuralUpsampler, FlowMaskEstimator from common.utils import flow_warp, upsample2d_flow_as def conv(inp, out, k=3, s=1, d=1, isReLU=True): if isReLU: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True), nn.LeakyReLU(0.1)) else: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True)) return ret class ContextNetwork(nn.Module): def __init__(self, ch_in): super(ContextNetwork, self).__init__() self.convs = nn.Sequential(conv(ch_in, 128, 3, 1, 1), conv(128, 128, 3, 1, 2), conv(128, 128, 3, 1, 4), conv(128, 96, 3, 1, 8), conv(96, 64, 3, 1, 16), conv(64, 32, 3, 1, 1), conv(32, 2, isReLU=False)) def forward(self, x): return self.convs(x) class FlowEstimator(nn.Module): def __init__(self, ch_in): super(FlowEstimator, self).__init__() self.conv1 = conv(ch_in, 128) self.conv2 = conv(128, 128) self.conv3 = conv(128 + 128, 96) self.conv4 = conv(96 + 128, 64) self.conv5 = conv(96 + 64, 32) # channels of the second last layer self.feat_dim = 32 self.predict_flow = conv(64 + 32, 2, isReLU=False) def forward(self, x): x1 = self.conv1(x) x2 = self.conv2(x1) x3 = self.conv3(F.concat([x1, x2], axis=1)) x4 = self.conv4(F.concat([x2, x3], axis=1)) x5 = self.conv5(F.concat([x3, x4], axis=1)) flow = self.predict_flow(F.concat([x4, x5], axis=1)) return x5, flow class CostVolume(nn.Module): def __init__(self, d=4, *args, **kwargs): super(CostVolume, self).__init__() self.d = d self.out_dim = 2 * self.d + 1 self.pad_size = self.d def forward(self, x1, x2): _, _, H, W = x1.shape x2 = F.nn.pad(x2, ((0, 0), (0, 0), (self.pad_size, self.pad_size), (self.pad_size, self.pad_size))) cv = [] for i in range(self.out_dim): for j in range(self.out_dim): cost = x1 * x2[:, :, i:(i + H), j:(j + W)] cost = F.mean(cost, 1, keepdims=True) cv.append(cost) return F.concat(cv, 1) class FeaturePyramidExtractor(nn.Module): def __init__(self, pyr_chans): super(FeaturePyramidExtractor, self).__init__() self.pyr_chans = pyr_chans self.convs = [] for _, (ch_in, ch_out) in enumerate(zip(pyr_chans[:-1], pyr_chans[1:])): layer = nn.Sequential(conv(ch_in, ch_out, s=2), conv(ch_out, ch_out)) self.convs.append(layer) def forward(self, x): feature_pyramid = [] for conv in self.convs: x = conv(x) feature_pyramid.append(x) return feature_pyramid[::-1] class GyroFlow(nn.Module): def __init__(self, params): super(GyroFlow, self).__init__() self.leakyRELU = nn.LeakyReLU(0.1) self.upsample = params.upsample self.with_bk = True self.pyr_chans = [3, 16, 32, 64, 96, 128, 192] self.feature_pyramid_extractor = FeaturePyramidExtractor(self.pyr_chans) # correlation range self.d = 4 self.output_level = 4 # cost volume self.cost_volume = CostVolume(d=self.d) self.cv_dim = (self.d * 2 + 1)**2 self.upsampler = NeuralUpsampler() self.ch_inp = 32 + self.cv_dim + 2 self.flow_estimator = FlowEstimator(self.ch_inp) self.context_net = ContextNetwork(self.flow_estimator.feat_dim + 2) self.conv_1x1 = list([ conv(192, 32, k=1, s=1, d=1), conv(128, 32, k=1, s=1, d=1), conv(96, 32, k=1, s=1, d=1), conv(64, 32, k=1, s=1, d=1), conv(32, 32, k=1, s=1, d=1) ]) self.with_gyro_field = True self.flow_predictor = FlowMaskEstimator(4, (8, 16, 32, 16, 8), 2) self.mask_predictor = FlowMaskEstimator(64, (32, 32, 32, 16, 8), 1) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.msra_normal_(m.weight, a=math.sqrt(5)) if m.bias is not None: fan_in, _ = nn.init.calculate_fan_in_and_fan_out(m.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(m.bias, -bound, bound) def generate_fused_flow(self, x1, x2): input_feature = F.concat((x1, x2), axis=1) flow = self.flow_predictor(input_feature)[1] assert flow.shape[1] == 2 return flow def generate_map(self, x1, x2): input_feature = F.concat((x1, x2), axis=1) out = self.mask_predictor(input_feature)[1] mask =
F.sigmoid(out)
megengine.functional.sigmoid
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # This repo is licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import math import collections import megengine.module as nn import megengine.functional as F from model.nn_upsample import NeuralUpsampler, FlowMaskEstimator from common.utils import flow_warp, upsample2d_flow_as def conv(inp, out, k=3, s=1, d=1, isReLU=True): if isReLU: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True), nn.LeakyReLU(0.1)) else: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True)) return ret class ContextNetwork(nn.Module): def __init__(self, ch_in): super(ContextNetwork, self).__init__() self.convs = nn.Sequential(conv(ch_in, 128, 3, 1, 1), conv(128, 128, 3, 1, 2), conv(128, 128, 3, 1, 4), conv(128, 96, 3, 1, 8), conv(96, 64, 3, 1, 16), conv(64, 32, 3, 1, 1), conv(32, 2, isReLU=False)) def forward(self, x): return self.convs(x) class FlowEstimator(nn.Module): def __init__(self, ch_in): super(FlowEstimator, self).__init__() self.conv1 = conv(ch_in, 128) self.conv2 = conv(128, 128) self.conv3 = conv(128 + 128, 96) self.conv4 = conv(96 + 128, 64) self.conv5 = conv(96 + 64, 32) # channels of the second last layer self.feat_dim = 32 self.predict_flow = conv(64 + 32, 2, isReLU=False) def forward(self, x): x1 = self.conv1(x) x2 = self.conv2(x1) x3 = self.conv3(F.concat([x1, x2], axis=1)) x4 = self.conv4(F.concat([x2, x3], axis=1)) x5 = self.conv5(F.concat([x3, x4], axis=1)) flow = self.predict_flow(F.concat([x4, x5], axis=1)) return x5, flow class CostVolume(nn.Module): def __init__(self, d=4, *args, **kwargs): super(CostVolume, self).__init__() self.d = d self.out_dim = 2 * self.d + 1 self.pad_size = self.d def forward(self, x1, x2): _, _, H, W = x1.shape x2 = F.nn.pad(x2, ((0, 0), (0, 0), (self.pad_size, self.pad_size), (self.pad_size, self.pad_size))) cv = [] for i in range(self.out_dim): for j in range(self.out_dim): cost = x1 * x2[:, :, i:(i + H), j:(j + W)] cost = F.mean(cost, 1, keepdims=True) cv.append(cost) return F.concat(cv, 1) class FeaturePyramidExtractor(nn.Module): def __init__(self, pyr_chans): super(FeaturePyramidExtractor, self).__init__() self.pyr_chans = pyr_chans self.convs = [] for _, (ch_in, ch_out) in enumerate(zip(pyr_chans[:-1], pyr_chans[1:])): layer = nn.Sequential(conv(ch_in, ch_out, s=2), conv(ch_out, ch_out)) self.convs.append(layer) def forward(self, x): feature_pyramid = [] for conv in self.convs: x = conv(x) feature_pyramid.append(x) return feature_pyramid[::-1] class GyroFlow(nn.Module): def __init__(self, params): super(GyroFlow, self).__init__() self.leakyRELU = nn.LeakyReLU(0.1) self.upsample = params.upsample self.with_bk = True self.pyr_chans = [3, 16, 32, 64, 96, 128, 192] self.feature_pyramid_extractor = FeaturePyramidExtractor(self.pyr_chans) # correlation range self.d = 4 self.output_level = 4 # cost volume self.cost_volume = CostVolume(d=self.d) self.cv_dim = (self.d * 2 + 1)**2 self.upsampler = NeuralUpsampler() self.ch_inp = 32 + self.cv_dim + 2 self.flow_estimator = FlowEstimator(self.ch_inp) self.context_net = ContextNetwork(self.flow_estimator.feat_dim + 2) self.conv_1x1 = list([ conv(192, 32, k=1, s=1, d=1), conv(128, 32, k=1, s=1, d=1), conv(96, 32, k=1, s=1, d=1), conv(64, 32, k=1, s=1, d=1), conv(32, 32, k=1, s=1, d=1) ]) self.with_gyro_field = True self.flow_predictor = FlowMaskEstimator(4, (8, 16, 32, 16, 8), 2) self.mask_predictor = FlowMaskEstimator(64, (32, 32, 32, 16, 8), 1) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.msra_normal_(m.weight, a=math.sqrt(5)) if m.bias is not None: fan_in, _ = nn.init.calculate_fan_in_and_fan_out(m.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(m.bias, -bound, bound) def generate_fused_flow(self, x1, x2): input_feature = F.concat((x1, x2), axis=1) flow = self.flow_predictor(input_feature)[1] assert flow.shape[1] == 2 return flow def generate_map(self, x1, x2): input_feature = F.concat((x1, x2), axis=1) out = self.mask_predictor(input_feature)[1] mask = F.sigmoid(out) assert mask.shape[1] == 1 return mask def self_guided_fusion_module(self, flow, gyro_field_rsz, x1, x2_warp, layer): fuse_flow = self.generate_fused_flow(flow, gyro_field_rsz) mask = self.generate_map(self.conv_1x1[layer](x1), self.conv_1x1[layer](x2_warp)) flow = fuse_flow * mask + gyro_field_rsz * (1 - mask) return flow def normalize_features(self, feature_list, normalize, center, moments_across_channels=True, moments_across_images=True): # Compute feature statistics. statistics = collections.defaultdict(list) axes = [1, 2, 3] if moments_across_channels else [2, 3] # [b, c, h, w] for feature_image in feature_list: mean = F.mean(feature_image, axis=axes, keepdims=True) # [b,1,1,1] or [b,c,1,1] variance = F.var(feature_image, axis=axes, keepdims=True) # [b,1,1,1] or [b,c,1,1] statistics['mean'].append(mean) statistics['var'].append(variance) if moments_across_images: statistics['mean'] = ([F.mean(F.stack(statistics['mean'], axis=0), axis=(0, ))] * len(feature_list)) statistics['var'] = ([F.var(F.stack(statistics['var'], axis=0), axis=(0, ))] * len(feature_list)) statistics['std'] = [F.sqrt(v + 1e-16) for v in statistics['var']] # Center and normalize features. if center: feature_list = [f - mean for f, mean in zip(feature_list, statistics['mean'])] if normalize: feature_list = [f / std for f, std in zip(feature_list, statistics['std'])] return feature_list def predict_flow(self, x1_pyrs, x2_pyrs, gyro_field=None): flow_pyrs = [] batch_size, _, h_x1, w_x1 = x1_pyrs[0].shape dtype = x1_pyrs[0].dtype flow =
F.zeros((batch_size, 2, h_x1, w_x1), dtype=dtype)
megengine.functional.zeros
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # This repo is licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import math import collections import megengine.module as nn import megengine.functional as F from model.nn_upsample import NeuralUpsampler, FlowMaskEstimator from common.utils import flow_warp, upsample2d_flow_as def conv(inp, out, k=3, s=1, d=1, isReLU=True): if isReLU: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True),
nn.LeakyReLU(0.1)
megengine.module.LeakyReLU
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # This repo is licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import math import collections import megengine.module as nn import megengine.functional as F from model.nn_upsample import NeuralUpsampler, FlowMaskEstimator from common.utils import flow_warp, upsample2d_flow_as def conv(inp, out, k=3, s=1, d=1, isReLU=True): if isReLU: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True), nn.LeakyReLU(0.1)) else: ret = nn.Sequential(nn.Conv2d(inp, out, k, s, padding=((k - 1) * d) // 2, dilation=d, bias=True)) return ret class ContextNetwork(nn.Module): def __init__(self, ch_in): super(ContextNetwork, self).__init__() self.convs = nn.Sequential(conv(ch_in, 128, 3, 1, 1), conv(128, 128, 3, 1, 2), conv(128, 128, 3, 1, 4), conv(128, 96, 3, 1, 8), conv(96, 64, 3, 1, 16), conv(64, 32, 3, 1, 1), conv(32, 2, isReLU=False)) def forward(self, x): return self.convs(x) class FlowEstimator(nn.Module): def __init__(self, ch_in): super(FlowEstimator, self).__init__() self.conv1 = conv(ch_in, 128) self.conv2 = conv(128, 128) self.conv3 = conv(128 + 128, 96) self.conv4 = conv(96 + 128, 64) self.conv5 = conv(96 + 64, 32) # channels of the second last layer self.feat_dim = 32 self.predict_flow = conv(64 + 32, 2, isReLU=False) def forward(self, x): x1 = self.conv1(x) x2 = self.conv2(x1) x3 = self.conv3(
F.concat([x1, x2], axis=1)
megengine.functional.concat