prompt
stringlengths
94
42.6k
completion
stringlengths
6
120
api
stringlengths
14
68
# -*- 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 pytest import megengine as mge from megengine import tensor from megengine.core.autodiff.grad import Function, Grad from megengine.core.tensor.utils import make_shape_tuple from megengine.quantization.internal_fake_quant import * from megengine.quantization.utils import QuantMode, fake_quant_tensor, tqt_forward class TQT_numpy: def __init__(self, lowerbound, upperbound): super().__init__() self.lowerbound = lowerbound self.upperbound = upperbound def forward(self, inp, scale): t = 2 ** scale # t = F.maximum(t, 1e-4) inp_scaled = inp / t inp_clipped = np.maximum( np.minimum(inp_scaled, self.upperbound), self.lowerbound ) inp_rounded = np.round(inp_clipped) inp_flq = inp_rounded * t self.saved_tensors = (inp_scaled, inp_rounded, t) return inp_flq def backward(self, grad_inp_flq): (inp_scaled, inp_rounded, t) = self.saved_tensors mask_clip = (inp_scaled < -0.5 + self.lowerbound) + ( inp_scaled > self.upperbound + 0.5 ) # mask for accumulating the gradients of |data_scaled|>L mask_quant = np.abs( mask_clip - 1 ) # mask for accumulating the gradients with |data_scaled|<=L grad_quant = ( grad_inp_flq * mask_quant * (inp_rounded - inp_scaled) ) # gradient within |data_scaled|<=L grad_clip = ( grad_inp_flq * mask_clip * inp_rounded ) # gradient with | data_scaled|>L grad_s = grad_clip.sum() + grad_quant.sum() # dL/ds = dL/dt * t * ln(2) grad_s = grad_s * t * np.log(2) grad_inp = grad_inp_flq * mask_quant return grad_inp, grad_s def test_tqt(): g = [] def cb(grad): g.append(grad) x = np.random.normal(size=(1, 2, 3, 4)) s = np.random.rand(1) + 1 g_y = np.ones(shape=(1, 2, 3, 4), dtype="float32") n = TQT_numpy(-127, 127) y_np = n.forward(x, s) g_x_np, g_s_np = n.backward(g_y) x = mge.tensor(x, dtype="float32") s = mge.tensor(s, dtype="float32") g_y = mge.tensor(g_y, dtype="float32") grad = Grad().wrt(x, s, callback=cb) y = tqt_forward(-127, 127, x, s) grad(y, g_y) g_x, g_s = g np.testing.assert_allclose(y.numpy(), y_np, atol=1e-6) np.testing.assert_allclose(g_x.numpy(), g_x_np, atol=1e-6) np.testing.assert_allclose(g_s.numpy(), g_s_np, atol=1e-6) def _save_to(self, name="grad"): def callback(grad): setattr(self, name, grad) return callback class Round(Function): def forward(self, x): return F.round(x) def backward(self, output_grads): return output_grads def fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax): oup = Round()(inp / scale) + zero_point oup = F.minimum(F.maximum(oup, qmin), qmax) oup = (oup - zero_point) * scale return oup def test_fakequant(): qmin = -126 qmax = 129 def run(zero_point, scale): q_dict = {} q_dict["mode"] = QuantMode.ASYMMERTIC q_dict["scale"] = scale q_dict["zero_point"] = zero_point inp_data = np.random.uniform(low=-512.0, high=512.0, size=(1, 32, 32, 32)) inp = tensor(inp_data, dtype=np.float32) # test forward oup = fake_quant_tensor(inp, qmin, qmax, q_dict).numpy() oup_gt = fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax).numpy() assert np.allclose(oup, oup_gt) assert oup.shape == oup_gt.shape # test backward x = tensor(inp_data, dtype=np.float32) grad = Grad().wrt(x, callback=_save_to(x)) y =
fake_quant_tensor(x, qmin, qmax, q_dict)
megengine.quantization.utils.fake_quant_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 pytest import megengine as mge from megengine import tensor from megengine.core.autodiff.grad import Function, Grad from megengine.core.tensor.utils import make_shape_tuple from megengine.quantization.internal_fake_quant import * from megengine.quantization.utils import QuantMode, fake_quant_tensor, tqt_forward class TQT_numpy: def __init__(self, lowerbound, upperbound): super().__init__() self.lowerbound = lowerbound self.upperbound = upperbound def forward(self, inp, scale): t = 2 ** scale # t = F.maximum(t, 1e-4) inp_scaled = inp / t inp_clipped = np.maximum( np.minimum(inp_scaled, self.upperbound), self.lowerbound ) inp_rounded = np.round(inp_clipped) inp_flq = inp_rounded * t self.saved_tensors = (inp_scaled, inp_rounded, t) return inp_flq def backward(self, grad_inp_flq): (inp_scaled, inp_rounded, t) = self.saved_tensors mask_clip = (inp_scaled < -0.5 + self.lowerbound) + ( inp_scaled > self.upperbound + 0.5 ) # mask for accumulating the gradients of |data_scaled|>L mask_quant = np.abs( mask_clip - 1 ) # mask for accumulating the gradients with |data_scaled|<=L grad_quant = ( grad_inp_flq * mask_quant * (inp_rounded - inp_scaled) ) # gradient within |data_scaled|<=L grad_clip = ( grad_inp_flq * mask_clip * inp_rounded ) # gradient with | data_scaled|>L grad_s = grad_clip.sum() + grad_quant.sum() # dL/ds = dL/dt * t * ln(2) grad_s = grad_s * t * np.log(2) grad_inp = grad_inp_flq * mask_quant return grad_inp, grad_s def test_tqt(): g = [] def cb(grad): g.append(grad) x = np.random.normal(size=(1, 2, 3, 4)) s = np.random.rand(1) + 1 g_y = np.ones(shape=(1, 2, 3, 4), dtype="float32") n = TQT_numpy(-127, 127) y_np = n.forward(x, s) g_x_np, g_s_np = n.backward(g_y) x = mge.tensor(x, dtype="float32") s = mge.tensor(s, dtype="float32") g_y = mge.tensor(g_y, dtype="float32") grad = Grad().wrt(x, s, callback=cb) y = tqt_forward(-127, 127, x, s) grad(y, g_y) g_x, g_s = g np.testing.assert_allclose(y.numpy(), y_np, atol=1e-6) np.testing.assert_allclose(g_x.numpy(), g_x_np, atol=1e-6) np.testing.assert_allclose(g_s.numpy(), g_s_np, atol=1e-6) def _save_to(self, name="grad"): def callback(grad): setattr(self, name, grad) return callback class Round(Function): def forward(self, x): return F.round(x) def backward(self, output_grads): return output_grads def fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax): oup = Round()(inp / scale) + zero_point oup = F.minimum(F.maximum(oup, qmin), qmax) oup = (oup - zero_point) * scale return oup def test_fakequant(): qmin = -126 qmax = 129 def run(zero_point, scale): q_dict = {} q_dict["mode"] = QuantMode.ASYMMERTIC q_dict["scale"] = scale q_dict["zero_point"] = zero_point inp_data = np.random.uniform(low=-512.0, high=512.0, size=(1, 32, 32, 32)) inp = tensor(inp_data, dtype=np.float32) # test forward oup = fake_quant_tensor(inp, qmin, qmax, q_dict).numpy() oup_gt = fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax).numpy() assert np.allclose(oup, oup_gt) assert oup.shape == oup_gt.shape # test backward x = tensor(inp_data, dtype=np.float32) grad = Grad().wrt(x, callback=_save_to(x)) y = fake_quant_tensor(x, qmin, qmax, q_dict) grad(y, tensor(F.ones_like(x))) x1 =
tensor(inp_data, dtype=np.float32)
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 pytest import megengine as mge from megengine import tensor from megengine.core.autodiff.grad import Function, Grad from megengine.core.tensor.utils import make_shape_tuple from megengine.quantization.internal_fake_quant import * from megengine.quantization.utils import QuantMode, fake_quant_tensor, tqt_forward class TQT_numpy: def __init__(self, lowerbound, upperbound): super().__init__() self.lowerbound = lowerbound self.upperbound = upperbound def forward(self, inp, scale): t = 2 ** scale # t = F.maximum(t, 1e-4) inp_scaled = inp / t inp_clipped = np.maximum( np.minimum(inp_scaled, self.upperbound), self.lowerbound ) inp_rounded = np.round(inp_clipped) inp_flq = inp_rounded * t self.saved_tensors = (inp_scaled, inp_rounded, t) return inp_flq def backward(self, grad_inp_flq): (inp_scaled, inp_rounded, t) = self.saved_tensors mask_clip = (inp_scaled < -0.5 + self.lowerbound) + ( inp_scaled > self.upperbound + 0.5 ) # mask for accumulating the gradients of |data_scaled|>L mask_quant = np.abs( mask_clip - 1 ) # mask for accumulating the gradients with |data_scaled|<=L grad_quant = ( grad_inp_flq * mask_quant * (inp_rounded - inp_scaled) ) # gradient within |data_scaled|<=L grad_clip = ( grad_inp_flq * mask_clip * inp_rounded ) # gradient with | data_scaled|>L grad_s = grad_clip.sum() + grad_quant.sum() # dL/ds = dL/dt * t * ln(2) grad_s = grad_s * t * np.log(2) grad_inp = grad_inp_flq * mask_quant return grad_inp, grad_s def test_tqt(): g = [] def cb(grad): g.append(grad) x = np.random.normal(size=(1, 2, 3, 4)) s = np.random.rand(1) + 1 g_y = np.ones(shape=(1, 2, 3, 4), dtype="float32") n = TQT_numpy(-127, 127) y_np = n.forward(x, s) g_x_np, g_s_np = n.backward(g_y) x = mge.tensor(x, dtype="float32") s = mge.tensor(s, dtype="float32") g_y = mge.tensor(g_y, dtype="float32") grad =
Grad()
megengine.core.autodiff.grad.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 pytest import megengine as mge from megengine import tensor from megengine.core.autodiff.grad import Function, Grad from megengine.core.tensor.utils import make_shape_tuple from megengine.quantization.internal_fake_quant import * from megengine.quantization.utils import QuantMode, fake_quant_tensor, tqt_forward class TQT_numpy: def __init__(self, lowerbound, upperbound): super().__init__() self.lowerbound = lowerbound self.upperbound = upperbound def forward(self, inp, scale): t = 2 ** scale # t = F.maximum(t, 1e-4) inp_scaled = inp / t inp_clipped = np.maximum( np.minimum(inp_scaled, self.upperbound), self.lowerbound ) inp_rounded = np.round(inp_clipped) inp_flq = inp_rounded * t self.saved_tensors = (inp_scaled, inp_rounded, t) return inp_flq def backward(self, grad_inp_flq): (inp_scaled, inp_rounded, t) = self.saved_tensors mask_clip = (inp_scaled < -0.5 + self.lowerbound) + ( inp_scaled > self.upperbound + 0.5 ) # mask for accumulating the gradients of |data_scaled|>L mask_quant = np.abs( mask_clip - 1 ) # mask for accumulating the gradients with |data_scaled|<=L grad_quant = ( grad_inp_flq * mask_quant * (inp_rounded - inp_scaled) ) # gradient within |data_scaled|<=L grad_clip = ( grad_inp_flq * mask_clip * inp_rounded ) # gradient with | data_scaled|>L grad_s = grad_clip.sum() + grad_quant.sum() # dL/ds = dL/dt * t * ln(2) grad_s = grad_s * t * np.log(2) grad_inp = grad_inp_flq * mask_quant return grad_inp, grad_s def test_tqt(): g = [] def cb(grad): g.append(grad) x = np.random.normal(size=(1, 2, 3, 4)) s = np.random.rand(1) + 1 g_y = np.ones(shape=(1, 2, 3, 4), dtype="float32") n = TQT_numpy(-127, 127) y_np = n.forward(x, s) g_x_np, g_s_np = n.backward(g_y) x = mge.tensor(x, dtype="float32") s = mge.tensor(s, dtype="float32") g_y = mge.tensor(g_y, dtype="float32") grad = Grad().wrt(x, s, callback=cb) y = tqt_forward(-127, 127, x, s) grad(y, g_y) g_x, g_s = g np.testing.assert_allclose(y.numpy(), y_np, atol=1e-6) np.testing.assert_allclose(g_x.numpy(), g_x_np, atol=1e-6) np.testing.assert_allclose(g_s.numpy(), g_s_np, atol=1e-6) def _save_to(self, name="grad"): def callback(grad): setattr(self, name, grad) return callback class Round(Function): def forward(self, x): return F.round(x) def backward(self, output_grads): return output_grads def fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax): oup = Round()(inp / scale) + zero_point oup = F.minimum(F.maximum(oup, qmin), qmax) oup = (oup - zero_point) * scale return oup def test_fakequant(): qmin = -126 qmax = 129 def run(zero_point, scale): q_dict = {} q_dict["mode"] = QuantMode.ASYMMERTIC q_dict["scale"] = scale q_dict["zero_point"] = zero_point inp_data = np.random.uniform(low=-512.0, high=512.0, size=(1, 32, 32, 32)) inp = tensor(inp_data, dtype=np.float32) # test forward oup = fake_quant_tensor(inp, qmin, qmax, q_dict).numpy() oup_gt = fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax).numpy() assert np.allclose(oup, oup_gt) assert oup.shape == oup_gt.shape # test backward x = tensor(inp_data, dtype=np.float32) grad = Grad().wrt(x, callback=_save_to(x)) y = fake_quant_tensor(x, qmin, qmax, q_dict) grad(y, tensor(F.ones_like(x))) x1 = tensor(inp_data, dtype=np.float32) grad = Grad().wrt(x1, callback=_save_to(x1)) y1 = fake_quant_tensor_gt(x1, scale, zero_point, qmin, qmax) grad(y1, tensor(F.ones_like(x1))) assert np.allclose(x.grad.numpy(), x1.grad.numpy()) assert
make_shape_tuple(x.grad.shape)
megengine.core.tensor.utils.make_shape_tuple
# -*- 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 pytest import megengine as mge from megengine import tensor from megengine.core.autodiff.grad import Function, Grad from megengine.core.tensor.utils import make_shape_tuple from megengine.quantization.internal_fake_quant import * from megengine.quantization.utils import QuantMode, fake_quant_tensor, tqt_forward class TQT_numpy: def __init__(self, lowerbound, upperbound): super().__init__() self.lowerbound = lowerbound self.upperbound = upperbound def forward(self, inp, scale): t = 2 ** scale # t = F.maximum(t, 1e-4) inp_scaled = inp / t inp_clipped = np.maximum( np.minimum(inp_scaled, self.upperbound), self.lowerbound ) inp_rounded = np.round(inp_clipped) inp_flq = inp_rounded * t self.saved_tensors = (inp_scaled, inp_rounded, t) return inp_flq def backward(self, grad_inp_flq): (inp_scaled, inp_rounded, t) = self.saved_tensors mask_clip = (inp_scaled < -0.5 + self.lowerbound) + ( inp_scaled > self.upperbound + 0.5 ) # mask for accumulating the gradients of |data_scaled|>L mask_quant = np.abs( mask_clip - 1 ) # mask for accumulating the gradients with |data_scaled|<=L grad_quant = ( grad_inp_flq * mask_quant * (inp_rounded - inp_scaled) ) # gradient within |data_scaled|<=L grad_clip = ( grad_inp_flq * mask_clip * inp_rounded ) # gradient with | data_scaled|>L grad_s = grad_clip.sum() + grad_quant.sum() # dL/ds = dL/dt * t * ln(2) grad_s = grad_s * t * np.log(2) grad_inp = grad_inp_flq * mask_quant return grad_inp, grad_s def test_tqt(): g = [] def cb(grad): g.append(grad) x = np.random.normal(size=(1, 2, 3, 4)) s = np.random.rand(1) + 1 g_y = np.ones(shape=(1, 2, 3, 4), dtype="float32") n = TQT_numpy(-127, 127) y_np = n.forward(x, s) g_x_np, g_s_np = n.backward(g_y) x = mge.tensor(x, dtype="float32") s = mge.tensor(s, dtype="float32") g_y = mge.tensor(g_y, dtype="float32") grad = Grad().wrt(x, s, callback=cb) y = tqt_forward(-127, 127, x, s) grad(y, g_y) g_x, g_s = g np.testing.assert_allclose(y.numpy(), y_np, atol=1e-6) np.testing.assert_allclose(g_x.numpy(), g_x_np, atol=1e-6) np.testing.assert_allclose(g_s.numpy(), g_s_np, atol=1e-6) def _save_to(self, name="grad"): def callback(grad): setattr(self, name, grad) return callback class Round(Function): def forward(self, x): return F.round(x) def backward(self, output_grads): return output_grads def fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax): oup = Round()(inp / scale) + zero_point oup = F.minimum(F.maximum(oup, qmin), qmax) oup = (oup - zero_point) * scale return oup def test_fakequant(): qmin = -126 qmax = 129 def run(zero_point, scale): q_dict = {} q_dict["mode"] = QuantMode.ASYMMERTIC q_dict["scale"] = scale q_dict["zero_point"] = zero_point inp_data = np.random.uniform(low=-512.0, high=512.0, size=(1, 32, 32, 32)) inp = tensor(inp_data, dtype=np.float32) # test forward oup = fake_quant_tensor(inp, qmin, qmax, q_dict).numpy() oup_gt = fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax).numpy() assert np.allclose(oup, oup_gt) assert oup.shape == oup_gt.shape # test backward x = tensor(inp_data, dtype=np.float32) grad = Grad().wrt(x, callback=_save_to(x)) y = fake_quant_tensor(x, qmin, qmax, q_dict) grad(y, tensor(F.ones_like(x))) x1 = tensor(inp_data, dtype=np.float32) grad = Grad().wrt(x1, callback=_save_to(x1)) y1 = fake_quant_tensor_gt(x1, scale, zero_point, qmin, qmax) grad(y1, tensor(F.ones_like(x1))) assert np.allclose(x.grad.numpy(), x1.grad.numpy()) assert make_shape_tuple(x.grad.shape) ==
make_shape_tuple(x1.grad.shape)
megengine.core.tensor.utils.make_shape_tuple
# -*- 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 pytest import megengine as mge from megengine import tensor from megengine.core.autodiff.grad import Function, Grad from megengine.core.tensor.utils import make_shape_tuple from megengine.quantization.internal_fake_quant import * from megengine.quantization.utils import QuantMode, fake_quant_tensor, tqt_forward class TQT_numpy: def __init__(self, lowerbound, upperbound): super().__init__() self.lowerbound = lowerbound self.upperbound = upperbound def forward(self, inp, scale): t = 2 ** scale # t = F.maximum(t, 1e-4) inp_scaled = inp / t inp_clipped = np.maximum( np.minimum(inp_scaled, self.upperbound), self.lowerbound ) inp_rounded = np.round(inp_clipped) inp_flq = inp_rounded * t self.saved_tensors = (inp_scaled, inp_rounded, t) return inp_flq def backward(self, grad_inp_flq): (inp_scaled, inp_rounded, t) = self.saved_tensors mask_clip = (inp_scaled < -0.5 + self.lowerbound) + ( inp_scaled > self.upperbound + 0.5 ) # mask for accumulating the gradients of |data_scaled|>L mask_quant = np.abs( mask_clip - 1 ) # mask for accumulating the gradients with |data_scaled|<=L grad_quant = ( grad_inp_flq * mask_quant * (inp_rounded - inp_scaled) ) # gradient within |data_scaled|<=L grad_clip = ( grad_inp_flq * mask_clip * inp_rounded ) # gradient with | data_scaled|>L grad_s = grad_clip.sum() + grad_quant.sum() # dL/ds = dL/dt * t * ln(2) grad_s = grad_s * t * np.log(2) grad_inp = grad_inp_flq * mask_quant return grad_inp, grad_s def test_tqt(): g = [] def cb(grad): g.append(grad) x = np.random.normal(size=(1, 2, 3, 4)) s = np.random.rand(1) + 1 g_y = np.ones(shape=(1, 2, 3, 4), dtype="float32") n = TQT_numpy(-127, 127) y_np = n.forward(x, s) g_x_np, g_s_np = n.backward(g_y) x = mge.tensor(x, dtype="float32") s = mge.tensor(s, dtype="float32") g_y = mge.tensor(g_y, dtype="float32") grad = Grad().wrt(x, s, callback=cb) y = tqt_forward(-127, 127, x, s) grad(y, g_y) g_x, g_s = g np.testing.assert_allclose(y.numpy(), y_np, atol=1e-6) np.testing.assert_allclose(g_x.numpy(), g_x_np, atol=1e-6) np.testing.assert_allclose(g_s.numpy(), g_s_np, atol=1e-6) def _save_to(self, name="grad"): def callback(grad): setattr(self, name, grad) return callback class Round(Function): def forward(self, x): return F.round(x) def backward(self, output_grads): return output_grads def fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax): oup = Round()(inp / scale) + zero_point oup = F.minimum(F.maximum(oup, qmin), qmax) oup = (oup - zero_point) * scale return oup def test_fakequant(): qmin = -126 qmax = 129 def run(zero_point, scale): q_dict = {} q_dict["mode"] = QuantMode.ASYMMERTIC q_dict["scale"] = scale q_dict["zero_point"] = zero_point inp_data = np.random.uniform(low=-512.0, high=512.0, size=(1, 32, 32, 32)) inp = tensor(inp_data, dtype=np.float32) # test forward oup =
fake_quant_tensor(inp, qmin, qmax, q_dict)
megengine.quantization.utils.fake_quant_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 pytest import megengine as mge from megengine import tensor from megengine.core.autodiff.grad import Function, Grad from megengine.core.tensor.utils import make_shape_tuple from megengine.quantization.internal_fake_quant import * from megengine.quantization.utils import QuantMode, fake_quant_tensor, tqt_forward class TQT_numpy: def __init__(self, lowerbound, upperbound): super().__init__() self.lowerbound = lowerbound self.upperbound = upperbound def forward(self, inp, scale): t = 2 ** scale # t = F.maximum(t, 1e-4) inp_scaled = inp / t inp_clipped = np.maximum( np.minimum(inp_scaled, self.upperbound), self.lowerbound ) inp_rounded = np.round(inp_clipped) inp_flq = inp_rounded * t self.saved_tensors = (inp_scaled, inp_rounded, t) return inp_flq def backward(self, grad_inp_flq): (inp_scaled, inp_rounded, t) = self.saved_tensors mask_clip = (inp_scaled < -0.5 + self.lowerbound) + ( inp_scaled > self.upperbound + 0.5 ) # mask for accumulating the gradients of |data_scaled|>L mask_quant = np.abs( mask_clip - 1 ) # mask for accumulating the gradients with |data_scaled|<=L grad_quant = ( grad_inp_flq * mask_quant * (inp_rounded - inp_scaled) ) # gradient within |data_scaled|<=L grad_clip = ( grad_inp_flq * mask_clip * inp_rounded ) # gradient with | data_scaled|>L grad_s = grad_clip.sum() + grad_quant.sum() # dL/ds = dL/dt * t * ln(2) grad_s = grad_s * t * np.log(2) grad_inp = grad_inp_flq * mask_quant return grad_inp, grad_s def test_tqt(): g = [] def cb(grad): g.append(grad) x = np.random.normal(size=(1, 2, 3, 4)) s = np.random.rand(1) + 1 g_y = np.ones(shape=(1, 2, 3, 4), dtype="float32") n = TQT_numpy(-127, 127) y_np = n.forward(x, s) g_x_np, g_s_np = n.backward(g_y) x = mge.tensor(x, dtype="float32") s = mge.tensor(s, dtype="float32") g_y = mge.tensor(g_y, dtype="float32") grad = Grad().wrt(x, s, callback=cb) y = tqt_forward(-127, 127, x, s) grad(y, g_y) g_x, g_s = g np.testing.assert_allclose(y.numpy(), y_np, atol=1e-6) np.testing.assert_allclose(g_x.numpy(), g_x_np, atol=1e-6) np.testing.assert_allclose(g_s.numpy(), g_s_np, atol=1e-6) def _save_to(self, name="grad"): def callback(grad): setattr(self, name, grad) return callback class Round(Function): def forward(self, x): return F.round(x) def backward(self, output_grads): return output_grads def fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax): oup = Round()(inp / scale) + zero_point oup = F.minimum(F.maximum(oup, qmin), qmax) oup = (oup - zero_point) * scale return oup def test_fakequant(): qmin = -126 qmax = 129 def run(zero_point, scale): q_dict = {} q_dict["mode"] = QuantMode.ASYMMERTIC q_dict["scale"] = scale q_dict["zero_point"] = zero_point inp_data = np.random.uniform(low=-512.0, high=512.0, size=(1, 32, 32, 32)) inp = tensor(inp_data, dtype=np.float32) # test forward oup = fake_quant_tensor(inp, qmin, qmax, q_dict).numpy() oup_gt = fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax).numpy() assert np.allclose(oup, oup_gt) assert oup.shape == oup_gt.shape # test backward x = tensor(inp_data, dtype=np.float32) grad =
Grad()
megengine.core.autodiff.grad.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 pytest import megengine as mge from megengine import tensor from megengine.core.autodiff.grad import Function, Grad from megengine.core.tensor.utils import make_shape_tuple from megengine.quantization.internal_fake_quant import * from megengine.quantization.utils import QuantMode, fake_quant_tensor, tqt_forward class TQT_numpy: def __init__(self, lowerbound, upperbound): super().__init__() self.lowerbound = lowerbound self.upperbound = upperbound def forward(self, inp, scale): t = 2 ** scale # t = F.maximum(t, 1e-4) inp_scaled = inp / t inp_clipped = np.maximum( np.minimum(inp_scaled, self.upperbound), self.lowerbound ) inp_rounded = np.round(inp_clipped) inp_flq = inp_rounded * t self.saved_tensors = (inp_scaled, inp_rounded, t) return inp_flq def backward(self, grad_inp_flq): (inp_scaled, inp_rounded, t) = self.saved_tensors mask_clip = (inp_scaled < -0.5 + self.lowerbound) + ( inp_scaled > self.upperbound + 0.5 ) # mask for accumulating the gradients of |data_scaled|>L mask_quant = np.abs( mask_clip - 1 ) # mask for accumulating the gradients with |data_scaled|<=L grad_quant = ( grad_inp_flq * mask_quant * (inp_rounded - inp_scaled) ) # gradient within |data_scaled|<=L grad_clip = ( grad_inp_flq * mask_clip * inp_rounded ) # gradient with | data_scaled|>L grad_s = grad_clip.sum() + grad_quant.sum() # dL/ds = dL/dt * t * ln(2) grad_s = grad_s * t * np.log(2) grad_inp = grad_inp_flq * mask_quant return grad_inp, grad_s def test_tqt(): g = [] def cb(grad): g.append(grad) x = np.random.normal(size=(1, 2, 3, 4)) s = np.random.rand(1) + 1 g_y = np.ones(shape=(1, 2, 3, 4), dtype="float32") n = TQT_numpy(-127, 127) y_np = n.forward(x, s) g_x_np, g_s_np = n.backward(g_y) x = mge.tensor(x, dtype="float32") s = mge.tensor(s, dtype="float32") g_y = mge.tensor(g_y, dtype="float32") grad = Grad().wrt(x, s, callback=cb) y = tqt_forward(-127, 127, x, s) grad(y, g_y) g_x, g_s = g np.testing.assert_allclose(y.numpy(), y_np, atol=1e-6) np.testing.assert_allclose(g_x.numpy(), g_x_np, atol=1e-6) np.testing.assert_allclose(g_s.numpy(), g_s_np, atol=1e-6) def _save_to(self, name="grad"): def callback(grad): setattr(self, name, grad) return callback class Round(Function): def forward(self, x): return F.round(x) def backward(self, output_grads): return output_grads def fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax): oup = Round()(inp / scale) + zero_point oup = F.minimum(F.maximum(oup, qmin), qmax) oup = (oup - zero_point) * scale return oup def test_fakequant(): qmin = -126 qmax = 129 def run(zero_point, scale): q_dict = {} q_dict["mode"] = QuantMode.ASYMMERTIC q_dict["scale"] = scale q_dict["zero_point"] = zero_point inp_data = np.random.uniform(low=-512.0, high=512.0, size=(1, 32, 32, 32)) inp = tensor(inp_data, dtype=np.float32) # test forward oup = fake_quant_tensor(inp, qmin, qmax, q_dict).numpy() oup_gt = fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax).numpy() assert np.allclose(oup, oup_gt) assert oup.shape == oup_gt.shape # test backward x = tensor(inp_data, dtype=np.float32) grad = Grad().wrt(x, callback=_save_to(x)) y = fake_quant_tensor(x, qmin, qmax, q_dict) grad(y, tensor(F.ones_like(x))) x1 = tensor(inp_data, dtype=np.float32) grad =
Grad()
megengine.core.autodiff.grad.Grad
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x =
F.reshape(x, (n, c, -1, k1 * k2))
megengine.functional.reshape
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x =
F.transpose(x, (0, 1, 3, 2))
megengine.functional.transpose
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x =
F.reshape(x, (n, c * k1 * k2, -1))
megengine.functional.reshape
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask =
F.reshape(mask, (N, 1, 9, rate, rate, H, W))
megengine.functional.reshape
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask =
F.softmax(mask, axis=2)
megengine.functional.softmax
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow =
F.reshape(up_flow, (N, 2, 9, 1, 1, H, W))
megengine.functional.reshape
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow =
F.sum(mask * up_flow, axis=2)
megengine.functional.sum
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow =
F.transpose(up_flow, (0, 1, 4, 2, 5, 3))
megengine.functional.transpose
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return
F.reshape(up_flow, (N, 2, rate * H, rate * W))
megengine.functional.reshape
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x =
F.zeros([N, 1, H, W], dtype="float32")
megengine.functional.zeros
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y =
F.zeros([N, 1, H, W], dtype="float32")
megengine.functional.zeros
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with
amp.autocast(enabled=self.mixed_precision)
megengine.amp.autocast
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with
amp.autocast(enabled=self.mixed_precision)
megengine.amp.autocast
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 =
F.avg_pool2d(fmap1, 2, stride=2)
megengine.functional.avg_pool2d
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 =
F.avg_pool2d(fmap2, 2, stride=2)
megengine.functional.avg_pool2d
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp =
F.split(fmap1, [hdim], axis=1)
megengine.functional.split
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net =
F.tanh(net)
megengine.functional.tanh
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp =
F.relu(inp)
megengine.functional.relu
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp = F.relu(inp) net_dw8 =
F.avg_pool2d(net, 2, stride=2)
megengine.functional.avg_pool2d
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp = F.relu(inp) net_dw8 = F.avg_pool2d(net, 2, stride=2) inp_dw8 =
F.avg_pool2d(inp, 2, stride=2)
megengine.functional.avg_pool2d
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp = F.relu(inp) net_dw8 = F.avg_pool2d(net, 2, stride=2) inp_dw8 = F.avg_pool2d(inp, 2, stride=2) # 1/4 -> 1/16 # feature fmap1_dw16 =
F.avg_pool2d(fmap1, 4, stride=4)
megengine.functional.avg_pool2d
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp = F.relu(inp) net_dw8 = F.avg_pool2d(net, 2, stride=2) inp_dw8 = F.avg_pool2d(inp, 2, stride=2) # 1/4 -> 1/16 # feature fmap1_dw16 = F.avg_pool2d(fmap1, 4, stride=4) fmap2_dw16 =
F.avg_pool2d(fmap2, 4, stride=4)
megengine.functional.avg_pool2d
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp = F.relu(inp) net_dw8 = F.avg_pool2d(net, 2, stride=2) inp_dw8 = F.avg_pool2d(inp, 2, stride=2) # 1/4 -> 1/16 # feature fmap1_dw16 = F.avg_pool2d(fmap1, 4, stride=4) fmap2_dw16 = F.avg_pool2d(fmap2, 4, stride=4) offset_dw16 = self.conv_offset_16(fmap1_dw16) offset_dw16 = self.range_16 * (F.sigmoid(offset_dw16) - 0.5) * 2.0 # context net_dw16 =
F.avg_pool2d(net, 4, stride=4)
megengine.functional.avg_pool2d
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp = F.relu(inp) net_dw8 = F.avg_pool2d(net, 2, stride=2) inp_dw8 = F.avg_pool2d(inp, 2, stride=2) # 1/4 -> 1/16 # feature fmap1_dw16 = F.avg_pool2d(fmap1, 4, stride=4) fmap2_dw16 = F.avg_pool2d(fmap2, 4, stride=4) offset_dw16 = self.conv_offset_16(fmap1_dw16) offset_dw16 = self.range_16 * (F.sigmoid(offset_dw16) - 0.5) * 2.0 # context net_dw16 = F.avg_pool2d(net, 4, stride=4) inp_dw16 =
F.avg_pool2d(inp, 4, stride=4)
megengine.functional.avg_pool2d
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow =
F.concat([_x, _y], axis=1)
megengine.functional.concat
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp = F.relu(inp) net_dw8 = F.avg_pool2d(net, 2, stride=2) inp_dw8 = F.avg_pool2d(inp, 2, stride=2) # 1/4 -> 1/16 # feature fmap1_dw16 = F.avg_pool2d(fmap1, 4, stride=4) fmap2_dw16 = F.avg_pool2d(fmap2, 4, stride=4) offset_dw16 = self.conv_offset_16(fmap1_dw16) offset_dw16 = self.range_16 * (F.sigmoid(offset_dw16) - 0.5) * 2.0 # context net_dw16 = F.avg_pool2d(net, 4, stride=4) inp_dw16 = F.avg_pool2d(inp, 4, stride=4) # positional encoding and self-attention pos_encoding_fn_small = PositionEncodingSine( d_model=256, max_shape=(image1.shape[2] // 16, image1.shape[3] // 16) ) # 'n c h w -> n (h w) c' x_tmp = pos_encoding_fn_small(fmap1_dw16) fmap1_dw16 = F.reshape(
F.transpose(x_tmp, (0, 2, 3, 1))
megengine.functional.transpose
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp = F.relu(inp) net_dw8 = F.avg_pool2d(net, 2, stride=2) inp_dw8 = F.avg_pool2d(inp, 2, stride=2) # 1/4 -> 1/16 # feature fmap1_dw16 = F.avg_pool2d(fmap1, 4, stride=4) fmap2_dw16 = F.avg_pool2d(fmap2, 4, stride=4) offset_dw16 = self.conv_offset_16(fmap1_dw16) offset_dw16 = self.range_16 * (F.sigmoid(offset_dw16) - 0.5) * 2.0 # context net_dw16 = F.avg_pool2d(net, 4, stride=4) inp_dw16 = F.avg_pool2d(inp, 4, stride=4) # positional encoding and self-attention pos_encoding_fn_small = PositionEncodingSine( d_model=256, max_shape=(image1.shape[2] // 16, image1.shape[3] // 16) ) # 'n c h w -> n (h w) c' x_tmp = pos_encoding_fn_small(fmap1_dw16) fmap1_dw16 = F.reshape( F.transpose(x_tmp, (0, 2, 3, 1)), (x_tmp.shape[0], x_tmp.shape[2] * x_tmp.shape[3], x_tmp.shape[1]), ) # 'n c h w -> n (h w) c' x_tmp = pos_encoding_fn_small(fmap2_dw16) fmap2_dw16 = F.reshape(
F.transpose(x_tmp, (0, 2, 3, 1))
megengine.functional.transpose
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp = F.relu(inp) net_dw8 = F.avg_pool2d(net, 2, stride=2) inp_dw8 = F.avg_pool2d(inp, 2, stride=2) # 1/4 -> 1/16 # feature fmap1_dw16 = F.avg_pool2d(fmap1, 4, stride=4) fmap2_dw16 = F.avg_pool2d(fmap2, 4, stride=4) offset_dw16 = self.conv_offset_16(fmap1_dw16) offset_dw16 = self.range_16 * (F.sigmoid(offset_dw16) - 0.5) * 2.0 # context net_dw16 = F.avg_pool2d(net, 4, stride=4) inp_dw16 = F.avg_pool2d(inp, 4, stride=4) # positional encoding and self-attention pos_encoding_fn_small = PositionEncodingSine( d_model=256, max_shape=(image1.shape[2] // 16, image1.shape[3] // 16) ) # 'n c h w -> n (h w) c' x_tmp = pos_encoding_fn_small(fmap1_dw16) fmap1_dw16 = F.reshape( F.transpose(x_tmp, (0, 2, 3, 1)), (x_tmp.shape[0], x_tmp.shape[2] * x_tmp.shape[3], x_tmp.shape[1]), ) # 'n c h w -> n (h w) c' x_tmp = pos_encoding_fn_small(fmap2_dw16) fmap2_dw16 = F.reshape( F.transpose(x_tmp, (0, 2, 3, 1)), (x_tmp.shape[0], x_tmp.shape[2] * x_tmp.shape[3], x_tmp.shape[1]), ) fmap1_dw16, fmap2_dw16 = self.self_att_fn(fmap1_dw16, fmap2_dw16) fmap1_dw16, fmap2_dw16 = [ F.transpose( F.reshape(x, (x.shape[0], image1.shape[2] // 16, -1, x.shape[2])), (0, 3, 1, 2), ) for x in [fmap1_dw16, fmap2_dw16] ] corr_fn = AGCL(fmap1, fmap2) corr_fn_dw8 = AGCL(fmap1_dw8, fmap2_dw8) corr_fn_att_dw16 = AGCL(fmap1_dw16, fmap2_dw16, att=self.cross_att_fn) # Cascaded refinement (1/16 + 1/8 + 1/4) predictions = [] flow = None flow_up = None if flow_init is not None: scale = fmap1.shape[2] / flow_init.shape[2] flow = -scale * F.nn.interpolate( flow_init, size=(fmap1.shape[2], fmap1.shape[3]), mode="bilinear", align_corners=True, ) else: # zero initialization flow_dw16 = self.zero_init(fmap1_dw16) # Recurrent Update Module # RUM: 1/16 for itr in range(iters // 2): if itr % 2 == 0: small_patch = False else: small_patch = True flow_dw16 = flow_dw16.detach() out_corrs = corr_fn_att_dw16( flow_dw16, offset_dw16, small_patch=small_patch ) with amp.autocast(enabled=self.mixed_precision): net_dw16, up_mask, delta_flow = self.update_block( net_dw16, inp_dw16, out_corrs, flow_dw16 ) flow_dw16 = flow_dw16 + delta_flow flow = self.convex_upsample(flow_dw16, up_mask, rate=4) flow_up = -4 * F.nn.interpolate( flow, size=(4 * flow.shape[2], 4 * flow.shape[3]), mode="bilinear", align_corners=True, ) predictions.append(flow_up) scale = fmap1_dw8.shape[2] / flow.shape[2] flow_dw8 = -scale * F.nn.interpolate( flow, size=(fmap1_dw8.shape[2], fmap1_dw8.shape[3]), mode="bilinear", align_corners=True, ) # RUM: 1/8 for itr in range(iters // 2): if itr % 2 == 0: small_patch = False else: small_patch = True flow_dw8 = flow_dw8.detach() out_corrs = corr_fn_dw8(flow_dw8, offset_dw8, small_patch=small_patch) with amp.autocast(enabled=self.mixed_precision): net_dw8, up_mask, delta_flow = self.update_block( net_dw8, inp_dw8, out_corrs, flow_dw8 ) flow_dw8 = flow_dw8 + delta_flow flow = self.convex_upsample(flow_dw8, up_mask, rate=4) flow_up = -2 * F.nn.interpolate( flow, size=(2 * flow.shape[2], 2 * flow.shape[3]), mode="bilinear", align_corners=True, ) predictions.append(flow_up) scale = fmap1.shape[2] / flow.shape[2] flow = -scale * F.nn.interpolate( flow, size=(fmap1.shape[2], fmap1.shape[3]), mode="bilinear", align_corners=True, ) # RUM: 1/4 for itr in range(iters): if itr % 2 == 0: small_patch = False else: small_patch = True flow = flow.detach() out_corrs = corr_fn(flow, None, small_patch=small_patch, iter_mode=True) with
amp.autocast(enabled=self.mixed_precision)
megengine.amp.autocast
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp = F.relu(inp) net_dw8 = F.avg_pool2d(net, 2, stride=2) inp_dw8 = F.avg_pool2d(inp, 2, stride=2) # 1/4 -> 1/16 # feature fmap1_dw16 = F.avg_pool2d(fmap1, 4, stride=4) fmap2_dw16 = F.avg_pool2d(fmap2, 4, stride=4) offset_dw16 = self.conv_offset_16(fmap1_dw16) offset_dw16 = self.range_16 * (F.sigmoid(offset_dw16) - 0.5) * 2.0 # context net_dw16 = F.avg_pool2d(net, 4, stride=4) inp_dw16 = F.avg_pool2d(inp, 4, stride=4) # positional encoding and self-attention pos_encoding_fn_small = PositionEncodingSine( d_model=256, max_shape=(image1.shape[2] // 16, image1.shape[3] // 16) ) # 'n c h w -> n (h w) c' x_tmp = pos_encoding_fn_small(fmap1_dw16) fmap1_dw16 = F.reshape( F.transpose(x_tmp, (0, 2, 3, 1)), (x_tmp.shape[0], x_tmp.shape[2] * x_tmp.shape[3], x_tmp.shape[1]), ) # 'n c h w -> n (h w) c' x_tmp = pos_encoding_fn_small(fmap2_dw16) fmap2_dw16 = F.reshape( F.transpose(x_tmp, (0, 2, 3, 1)), (x_tmp.shape[0], x_tmp.shape[2] * x_tmp.shape[3], x_tmp.shape[1]), ) fmap1_dw16, fmap2_dw16 = self.self_att_fn(fmap1_dw16, fmap2_dw16) fmap1_dw16, fmap2_dw16 = [ F.transpose(
F.reshape(x, (x.shape[0], image1.shape[2] // 16, -1, x.shape[2]))
megengine.functional.reshape
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp = F.relu(inp) net_dw8 = F.avg_pool2d(net, 2, stride=2) inp_dw8 = F.avg_pool2d(inp, 2, stride=2) # 1/4 -> 1/16 # feature fmap1_dw16 = F.avg_pool2d(fmap1, 4, stride=4) fmap2_dw16 = F.avg_pool2d(fmap2, 4, stride=4) offset_dw16 = self.conv_offset_16(fmap1_dw16) offset_dw16 = self.range_16 * (F.sigmoid(offset_dw16) - 0.5) * 2.0 # context net_dw16 = F.avg_pool2d(net, 4, stride=4) inp_dw16 = F.avg_pool2d(inp, 4, stride=4) # positional encoding and self-attention pos_encoding_fn_small = PositionEncodingSine( d_model=256, max_shape=(image1.shape[2] // 16, image1.shape[3] // 16) ) # 'n c h w -> n (h w) c' x_tmp = pos_encoding_fn_small(fmap1_dw16) fmap1_dw16 = F.reshape( F.transpose(x_tmp, (0, 2, 3, 1)), (x_tmp.shape[0], x_tmp.shape[2] * x_tmp.shape[3], x_tmp.shape[1]), ) # 'n c h w -> n (h w) c' x_tmp = pos_encoding_fn_small(fmap2_dw16) fmap2_dw16 = F.reshape( F.transpose(x_tmp, (0, 2, 3, 1)), (x_tmp.shape[0], x_tmp.shape[2] * x_tmp.shape[3], x_tmp.shape[1]), ) fmap1_dw16, fmap2_dw16 = self.self_att_fn(fmap1_dw16, fmap2_dw16) fmap1_dw16, fmap2_dw16 = [ F.transpose( F.reshape(x, (x.shape[0], image1.shape[2] // 16, -1, x.shape[2])), (0, 3, 1, 2), ) for x in [fmap1_dw16, fmap2_dw16] ] corr_fn = AGCL(fmap1, fmap2) corr_fn_dw8 = AGCL(fmap1_dw8, fmap2_dw8) corr_fn_att_dw16 = AGCL(fmap1_dw16, fmap2_dw16, att=self.cross_att_fn) # Cascaded refinement (1/16 + 1/8 + 1/4) predictions = [] flow = None flow_up = None if flow_init is not None: scale = fmap1.shape[2] / flow_init.shape[2] flow = -scale * F.nn.interpolate( flow_init, size=(fmap1.shape[2], fmap1.shape[3]), mode="bilinear", align_corners=True, ) else: # zero initialization flow_dw16 = self.zero_init(fmap1_dw16) # Recurrent Update Module # RUM: 1/16 for itr in range(iters // 2): if itr % 2 == 0: small_patch = False else: small_patch = True flow_dw16 = flow_dw16.detach() out_corrs = corr_fn_att_dw16( flow_dw16, offset_dw16, small_patch=small_patch ) with
amp.autocast(enabled=self.mixed_precision)
megengine.amp.autocast
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp = F.relu(inp) net_dw8 = F.avg_pool2d(net, 2, stride=2) inp_dw8 = F.avg_pool2d(inp, 2, stride=2) # 1/4 -> 1/16 # feature fmap1_dw16 = F.avg_pool2d(fmap1, 4, stride=4) fmap2_dw16 = F.avg_pool2d(fmap2, 4, stride=4) offset_dw16 = self.conv_offset_16(fmap1_dw16) offset_dw16 = self.range_16 * (F.sigmoid(offset_dw16) - 0.5) * 2.0 # context net_dw16 = F.avg_pool2d(net, 4, stride=4) inp_dw16 = F.avg_pool2d(inp, 4, stride=4) # positional encoding and self-attention pos_encoding_fn_small = PositionEncodingSine( d_model=256, max_shape=(image1.shape[2] // 16, image1.shape[3] // 16) ) # 'n c h w -> n (h w) c' x_tmp = pos_encoding_fn_small(fmap1_dw16) fmap1_dw16 = F.reshape( F.transpose(x_tmp, (0, 2, 3, 1)), (x_tmp.shape[0], x_tmp.shape[2] * x_tmp.shape[3], x_tmp.shape[1]), ) # 'n c h w -> n (h w) c' x_tmp = pos_encoding_fn_small(fmap2_dw16) fmap2_dw16 = F.reshape( F.transpose(x_tmp, (0, 2, 3, 1)), (x_tmp.shape[0], x_tmp.shape[2] * x_tmp.shape[3], x_tmp.shape[1]), ) fmap1_dw16, fmap2_dw16 = self.self_att_fn(fmap1_dw16, fmap2_dw16) fmap1_dw16, fmap2_dw16 = [ F.transpose( F.reshape(x, (x.shape[0], image1.shape[2] // 16, -1, x.shape[2])), (0, 3, 1, 2), ) for x in [fmap1_dw16, fmap2_dw16] ] corr_fn = AGCL(fmap1, fmap2) corr_fn_dw8 = AGCL(fmap1_dw8, fmap2_dw8) corr_fn_att_dw16 = AGCL(fmap1_dw16, fmap2_dw16, att=self.cross_att_fn) # Cascaded refinement (1/16 + 1/8 + 1/4) predictions = [] flow = None flow_up = None if flow_init is not None: scale = fmap1.shape[2] / flow_init.shape[2] flow = -scale * F.nn.interpolate( flow_init, size=(fmap1.shape[2], fmap1.shape[3]), mode="bilinear", align_corners=True, ) else: # zero initialization flow_dw16 = self.zero_init(fmap1_dw16) # Recurrent Update Module # RUM: 1/16 for itr in range(iters // 2): if itr % 2 == 0: small_patch = False else: small_patch = True flow_dw16 = flow_dw16.detach() out_corrs = corr_fn_att_dw16( flow_dw16, offset_dw16, small_patch=small_patch ) with amp.autocast(enabled=self.mixed_precision): net_dw16, up_mask, delta_flow = self.update_block( net_dw16, inp_dw16, out_corrs, flow_dw16 ) flow_dw16 = flow_dw16 + delta_flow flow = self.convex_upsample(flow_dw16, up_mask, rate=4) flow_up = -4 * F.nn.interpolate( flow, size=(4 * flow.shape[2], 4 * flow.shape[3]), mode="bilinear", align_corners=True, ) predictions.append(flow_up) scale = fmap1_dw8.shape[2] / flow.shape[2] flow_dw8 = -scale * F.nn.interpolate( flow, size=(fmap1_dw8.shape[2], fmap1_dw8.shape[3]), mode="bilinear", align_corners=True, ) # RUM: 1/8 for itr in range(iters // 2): if itr % 2 == 0: small_patch = False else: small_patch = True flow_dw8 = flow_dw8.detach() out_corrs = corr_fn_dw8(flow_dw8, offset_dw8, small_patch=small_patch) with
amp.autocast(enabled=self.mixed_precision)
megengine.amp.autocast
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (
F.sigmoid(offset_dw8)
megengine.functional.sigmoid
import megengine.module as M import megengine.functional as F from megengine import amp from .update import BasicUpdateBlock from .extractor import BasicEncoder from .corr import AGCL from .attention import PositionEncodingSine, LocalFeatureTransformer class CREStereo(M.Module): def __init__(self, max_disp=192, mixed_precision=False, test_mode=False): super(CREStereo, self).__init__() self.max_flow = max_disp self.mixed_precision = mixed_precision self.test_mode = test_mode self.hidden_dim = 128 self.context_dim = 128 self.dropout = 0 # feature network and update block self.fnet = BasicEncoder( output_dim=256, norm_fn="instance", dropout=self.dropout ) self.update_block = BasicUpdateBlock( hidden_dim=self.hidden_dim, cor_planes=4 * 9, mask_size=4 ) # loftr self.self_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["self"] * 1, attention="linear" ) self.cross_att_fn = LocalFeatureTransformer( d_model=256, nhead=8, layer_names=["cross"] * 1, attention="linear" ) # adaptive search self.search_num = 9 self.conv_offset_16 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.conv_offset_8 = M.Conv2d( 256, self.search_num * 2, kernel_size=3, stride=1, padding=1 ) self.range_16 = 1 self.range_8 = 1 def freeze_bn(self): for m in self.modules(): if isinstance(m, M.BatchNorm2d): m.eval() def unfold(self, x, kernel_size, dilation=1, padding=0, stride=1): n, c, h, w = x.shape if isinstance(kernel_size, tuple) or isinstance(kernel_size, list): assert len(kernel_size) == 2 k1, k2 = kernel_size else: assert isinstance(kernel_size, int) k1 = k2 = kernel_size x = F.sliding_window( x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride, ) x = F.reshape(x, (n, c, -1, k1 * k2)) x = F.transpose(x, (0, 1, 3, 2)) x = F.reshape(x, (n, c * k1 * k2, -1)) return x def convex_upsample(self, flow, mask, rate=4): """[H/rate, W/rate, 2] -> [H, W, 2]""" N, _, H, W = flow.shape mask = F.reshape(mask, (N, 1, 9, rate, rate, H, W)) mask = F.softmax(mask, axis=2) up_flow = self.unfold(rate * flow, [3, 3], padding=1) up_flow = F.reshape(up_flow, (N, 2, 9, 1, 1, H, W)) up_flow = F.sum(mask * up_flow, axis=2) up_flow = F.transpose(up_flow, (0, 1, 4, 2, 5, 3)) return F.reshape(up_flow, (N, 2, rate * H, rate * W)) def zero_init(self, fmap): N, C, H, W = fmap.shape _x = F.zeros([N, 1, H, W], dtype="float32") _y = F.zeros([N, 1, H, W], dtype="float32") zero_flow = F.concat([_x, _y], axis=1).to(fmap.device) return zero_flow def forward(self, image1, image2, iters=10, flow_init=None): image1 = 2 * (image1 / 255.0) - 1.0 image2 = 2 * (image2 / 255.0) - 1.0 hdim = self.hidden_dim cdim = self.context_dim # feature network with amp.autocast(enabled=self.mixed_precision): fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.astype("float32") fmap2 = fmap2.astype("float32") with amp.autocast(enabled=self.mixed_precision): # 1/4 -> 1/8 # feature fmap1_dw8 = F.avg_pool2d(fmap1, 2, stride=2) fmap2_dw8 = F.avg_pool2d(fmap2, 2, stride=2) # offset offset_dw8 = self.conv_offset_8(fmap1_dw8) offset_dw8 = self.range_8 * (F.sigmoid(offset_dw8) - 0.5) * 2.0 # context net, inp = F.split(fmap1, [hdim], axis=1) net = F.tanh(net) inp = F.relu(inp) net_dw8 = F.avg_pool2d(net, 2, stride=2) inp_dw8 = F.avg_pool2d(inp, 2, stride=2) # 1/4 -> 1/16 # feature fmap1_dw16 = F.avg_pool2d(fmap1, 4, stride=4) fmap2_dw16 = F.avg_pool2d(fmap2, 4, stride=4) offset_dw16 = self.conv_offset_16(fmap1_dw16) offset_dw16 = self.range_16 * (
F.sigmoid(offset_dw16)
megengine.functional.sigmoid
# 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. # pylint: disable=import-error,no-name-in-module,no-member from typing import List, Union import megengine as mge from megengine.traced_module import TracedModule from ..backend.ir_to_caffe.caffe_converter import BackEnd, CaffeConverter from ..converter_ir.ir_quantizer import IRQuantizer from ..converter_ir.ir_transform import IRTransform, TransformerRule from ..frontend.tm_to_ir import TM_FrontEnd from ..frontend.tm_to_ir.tm_utils import _update_inputs_qparams def tracedmodule_to_caffe( traced_module, prototxt="out.prototxt", caffemodel="out.caffemodel", outspec=None, use_empty_blobs=False, input_data_type: str = None, input_scales: Union[float, List[float]] = None, input_zero_points: Union[int, List[int]] = None, require_quantize=False, param_fake_quant=False, split_conv_relu=False, quantize_file_path="quant_params.json", convert_backend: BackEnd = BackEnd.CAFFE, ): """ Convert TracedModule model to Caffe, and save caffe model to `prototxt` and `caffemodel`. :param traced_module: the file path of TracedModule model. :type traced_module: str :param prototxt: the filename used for saved model definition. :type prototxt: str :param caffemodel: the filename used for saved model weights. :type caffemodel: str :param outspec: specify the end points of the model, expect the full names of nodes. :type outspec: list """ if isinstance(traced_module, str): traced_module =
mge.load(traced_module)
megengine.load
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 =
M.BatchNorm2d(self.in_channels)
megengine.module.BatchNorm2d
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 =
M.BatchNorm2d(self.hidden_channels)
megengine.module.BatchNorm2d
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation =
M.ReLU()
megengine.module.ReLU
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _upsample_conv(self, x, conv): r""" Helper function for performing convolution after upsampling. """ return conv( F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)) def _residual(self, x): r""" Helper function for feedforwarding through main layers. """ h = x h = self.b1(h) h = self.activation(h) h = self._upsample_conv(h, self.c1) if self.upsample else self.c1(h) h = self.b2(h) h = self.activation(h) h = self.c2(h) return h def _shortcut(self, x): r""" Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self._upsample_conv( x, self.c_sc) if self.upsample else self.c_sc(x) return x else: return x def forward(self, x): r""" Residual block feedforward function. """ return self._residual(x) + self._shortcut(x) class DBlock(M.Module): """ Residual block for discriminator. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. downsample (bool): If True, downsamples the input feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, downsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else in_channels self.downsample = downsample self.learnable_sc = (in_channels != out_channels) or downsample # Build the layers self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, 1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, 1) self.activation =
M.ReLU()
megengine.module.ReLU
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _upsample_conv(self, x, conv): r""" Helper function for performing convolution after upsampling. """ return conv( F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)) def _residual(self, x): r""" Helper function for feedforwarding through main layers. """ h = x h = self.b1(h) h = self.activation(h) h = self._upsample_conv(h, self.c1) if self.upsample else self.c1(h) h = self.b2(h) h = self.activation(h) h = self.c2(h) return h def _shortcut(self, x): r""" Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self._upsample_conv( x, self.c_sc) if self.upsample else self.c_sc(x) return x else: return x def forward(self, x): r""" Residual block feedforward function. """ return self._residual(x) + self._shortcut(x) class DBlock(M.Module): """ Residual block for discriminator. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. downsample (bool): If True, downsamples the input feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, downsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else in_channels self.downsample = downsample self.learnable_sc = (in_channels != out_channels) or downsample # Build the layers self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, 1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, 1) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, 0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _residual(self, x): """ Helper function for feedforwarding through main layers. """ h = x h = self.activation(h) h = self.c1(h) h = self.activation(h) h = self.c2(h) if self.downsample: h = F.avg_pool2d(h, 2) return h def _shortcut(self, x): """ Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self.c_sc(x) return F.avg_pool2d(x, 2) if self.downsample else x else: return x def forward(self, x): """ Residual block feedforward function. """ # NOTE: to completely reproduce pytorch, we use F.relu(x) to replace x in shortcut # since pytorch use inplace relu in residual branch. return self._residual(x) + self._shortcut(F.relu(x)) class DBlockOptimized(M.Module): """ Optimized residual block for discriminator. This is used as the first residual block, where there is a definite downsampling involved. Follows the official SNGAN reference implementation in chainer. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, spectral_norm=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.spectral_norm = spectral_norm # Build the layers self.c1 =
M.Conv2d(self.in_channels, self.out_channels, 3, 1, 1)
megengine.module.Conv2d
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _upsample_conv(self, x, conv): r""" Helper function for performing convolution after upsampling. """ return conv( F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)) def _residual(self, x): r""" Helper function for feedforwarding through main layers. """ h = x h = self.b1(h) h = self.activation(h) h = self._upsample_conv(h, self.c1) if self.upsample else self.c1(h) h = self.b2(h) h = self.activation(h) h = self.c2(h) return h def _shortcut(self, x): r""" Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self._upsample_conv( x, self.c_sc) if self.upsample else self.c_sc(x) return x else: return x def forward(self, x): r""" Residual block feedforward function. """ return self._residual(x) + self._shortcut(x) class DBlock(M.Module): """ Residual block for discriminator. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. downsample (bool): If True, downsamples the input feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, downsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else in_channels self.downsample = downsample self.learnable_sc = (in_channels != out_channels) or downsample # Build the layers self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, 1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, 1) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, 0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _residual(self, x): """ Helper function for feedforwarding through main layers. """ h = x h = self.activation(h) h = self.c1(h) h = self.activation(h) h = self.c2(h) if self.downsample: h = F.avg_pool2d(h, 2) return h def _shortcut(self, x): """ Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self.c_sc(x) return F.avg_pool2d(x, 2) if self.downsample else x else: return x def forward(self, x): """ Residual block feedforward function. """ # NOTE: to completely reproduce pytorch, we use F.relu(x) to replace x in shortcut # since pytorch use inplace relu in residual branch. return self._residual(x) + self._shortcut(F.relu(x)) class DBlockOptimized(M.Module): """ Optimized residual block for discriminator. This is used as the first residual block, where there is a definite downsampling involved. Follows the official SNGAN reference implementation in chainer. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, spectral_norm=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.spectral_norm = spectral_norm # Build the layers self.c1 = M.Conv2d(self.in_channels, self.out_channels, 3, 1, 1) self.c2 =
M.Conv2d(self.out_channels, self.out_channels, 3, 1, 1)
megengine.module.Conv2d
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _upsample_conv(self, x, conv): r""" Helper function for performing convolution after upsampling. """ return conv( F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)) def _residual(self, x): r""" Helper function for feedforwarding through main layers. """ h = x h = self.b1(h) h = self.activation(h) h = self._upsample_conv(h, self.c1) if self.upsample else self.c1(h) h = self.b2(h) h = self.activation(h) h = self.c2(h) return h def _shortcut(self, x): r""" Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self._upsample_conv( x, self.c_sc) if self.upsample else self.c_sc(x) return x else: return x def forward(self, x): r""" Residual block feedforward function. """ return self._residual(x) + self._shortcut(x) class DBlock(M.Module): """ Residual block for discriminator. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. downsample (bool): If True, downsamples the input feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, downsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else in_channels self.downsample = downsample self.learnable_sc = (in_channels != out_channels) or downsample # Build the layers self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, 1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, 1) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, 0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _residual(self, x): """ Helper function for feedforwarding through main layers. """ h = x h = self.activation(h) h = self.c1(h) h = self.activation(h) h = self.c2(h) if self.downsample: h = F.avg_pool2d(h, 2) return h def _shortcut(self, x): """ Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self.c_sc(x) return F.avg_pool2d(x, 2) if self.downsample else x else: return x def forward(self, x): """ Residual block feedforward function. """ # NOTE: to completely reproduce pytorch, we use F.relu(x) to replace x in shortcut # since pytorch use inplace relu in residual branch. return self._residual(x) + self._shortcut(F.relu(x)) class DBlockOptimized(M.Module): """ Optimized residual block for discriminator. This is used as the first residual block, where there is a definite downsampling involved. Follows the official SNGAN reference implementation in chainer. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, spectral_norm=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.spectral_norm = spectral_norm # Build the layers self.c1 = M.Conv2d(self.in_channels, self.out_channels, 3, 1, 1) self.c2 = M.Conv2d(self.out_channels, self.out_channels, 3, 1, 1) self.c_sc =
M.Conv2d(self.in_channels, self.out_channels, 1, 1, 0)
megengine.module.Conv2d
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _upsample_conv(self, x, conv): r""" Helper function for performing convolution after upsampling. """ return conv( F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)) def _residual(self, x): r""" Helper function for feedforwarding through main layers. """ h = x h = self.b1(h) h = self.activation(h) h = self._upsample_conv(h, self.c1) if self.upsample else self.c1(h) h = self.b2(h) h = self.activation(h) h = self.c2(h) return h def _shortcut(self, x): r""" Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self._upsample_conv( x, self.c_sc) if self.upsample else self.c_sc(x) return x else: return x def forward(self, x): r""" Residual block feedforward function. """ return self._residual(x) + self._shortcut(x) class DBlock(M.Module): """ Residual block for discriminator. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. downsample (bool): If True, downsamples the input feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, downsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else in_channels self.downsample = downsample self.learnable_sc = (in_channels != out_channels) or downsample # Build the layers self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, 1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, 1) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, 0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _residual(self, x): """ Helper function for feedforwarding through main layers. """ h = x h = self.activation(h) h = self.c1(h) h = self.activation(h) h = self.c2(h) if self.downsample: h = F.avg_pool2d(h, 2) return h def _shortcut(self, x): """ Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self.c_sc(x) return F.avg_pool2d(x, 2) if self.downsample else x else: return x def forward(self, x): """ Residual block feedforward function. """ # NOTE: to completely reproduce pytorch, we use F.relu(x) to replace x in shortcut # since pytorch use inplace relu in residual branch. return self._residual(x) + self._shortcut(F.relu(x)) class DBlockOptimized(M.Module): """ Optimized residual block for discriminator. This is used as the first residual block, where there is a definite downsampling involved. Follows the official SNGAN reference implementation in chainer. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, spectral_norm=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.spectral_norm = spectral_norm # Build the layers self.c1 = M.Conv2d(self.in_channels, self.out_channels, 3, 1, 1) self.c2 = M.Conv2d(self.out_channels, self.out_channels, 3, 1, 1) self.c_sc = M.Conv2d(self.in_channels, self.out_channels, 1, 1, 0) self.activation =
M.ReLU()
megengine.module.ReLU
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _upsample_conv(self, x, conv): r""" Helper function for performing convolution after upsampling. """ return conv( F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)) def _residual(self, x): r""" Helper function for feedforwarding through main layers. """ h = x h = self.b1(h) h = self.activation(h) h = self._upsample_conv(h, self.c1) if self.upsample else self.c1(h) h = self.b2(h) h = self.activation(h) h = self.c2(h) return h def _shortcut(self, x): r""" Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self._upsample_conv( x, self.c_sc) if self.upsample else self.c_sc(x) return x else: return x def forward(self, x): r""" Residual block feedforward function. """ return self._residual(x) + self._shortcut(x) class DBlock(M.Module): """ Residual block for discriminator. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. downsample (bool): If True, downsamples the input feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, downsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else in_channels self.downsample = downsample self.learnable_sc = (in_channels != out_channels) or downsample # Build the layers self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, 1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, 1) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, 0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _residual(self, x): """ Helper function for feedforwarding through main layers. """ h = x h = self.activation(h) h = self.c1(h) h = self.activation(h) h = self.c2(h) if self.downsample: h = F.avg_pool2d(h, 2) return h def _shortcut(self, x): """ Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self.c_sc(x) return F.avg_pool2d(x, 2) if self.downsample else x else: return x def forward(self, x): """ Residual block feedforward function. """ # NOTE: to completely reproduce pytorch, we use F.relu(x) to replace x in shortcut # since pytorch use inplace relu in residual branch. return self._residual(x) + self._shortcut(F.relu(x)) class DBlockOptimized(M.Module): """ Optimized residual block for discriminator. This is used as the first residual block, where there is a definite downsampling involved. Follows the official SNGAN reference implementation in chainer. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, spectral_norm=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.spectral_norm = spectral_norm # Build the layers self.c1 = M.Conv2d(self.in_channels, self.out_channels, 3, 1, 1) self.c2 = M.Conv2d(self.out_channels, self.out_channels, 3, 1, 1) self.c_sc = M.Conv2d(self.in_channels, self.out_channels, 1, 1, 0) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0))
M.init.xavier_uniform_(self.c_sc.weight, 1.0)
megengine.module.init.xavier_uniform_
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _upsample_conv(self, x, conv): r""" Helper function for performing convolution after upsampling. """ return conv( F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)) def _residual(self, x): r""" Helper function for feedforwarding through main layers. """ h = x h = self.b1(h) h = self.activation(h) h = self._upsample_conv(h, self.c1) if self.upsample else self.c1(h) h = self.b2(h) h = self.activation(h) h = self.c2(h) return h def _shortcut(self, x): r""" Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self._upsample_conv( x, self.c_sc) if self.upsample else self.c_sc(x) return x else: return x def forward(self, x): r""" Residual block feedforward function. """ return self._residual(x) + self._shortcut(x) class DBlock(M.Module): """ Residual block for discriminator. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. downsample (bool): If True, downsamples the input feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, downsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else in_channels self.downsample = downsample self.learnable_sc = (in_channels != out_channels) or downsample # Build the layers self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, 1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, 1) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, 0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _residual(self, x): """ Helper function for feedforwarding through main layers. """ h = x h = self.activation(h) h = self.c1(h) h = self.activation(h) h = self.c2(h) if self.downsample: h = F.avg_pool2d(h, 2) return h def _shortcut(self, x): """ Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self.c_sc(x) return F.avg_pool2d(x, 2) if self.downsample else x else: return x def forward(self, x): """ Residual block feedforward function. """ # NOTE: to completely reproduce pytorch, we use F.relu(x) to replace x in shortcut # since pytorch use inplace relu in residual branch. return self._residual(x) + self._shortcut(F.relu(x)) class DBlockOptimized(M.Module): """ Optimized residual block for discriminator. This is used as the first residual block, where there is a definite downsampling involved. Follows the official SNGAN reference implementation in chainer. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, spectral_norm=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.spectral_norm = spectral_norm # Build the layers self.c1 = M.Conv2d(self.in_channels, self.out_channels, 3, 1, 1) self.c2 = M.Conv2d(self.out_channels, self.out_channels, 3, 1, 1) self.c_sc = M.Conv2d(self.in_channels, self.out_channels, 1, 1, 0) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _residual(self, x): """ Helper function for feedforwarding through main layers. """ h = x h = self.c1(h) h = self.activation(h) h = self.c2(h) h =
F.avg_pool2d(h, 2)
megengine.functional.avg_pool2d
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0)
M.init.xavier_uniform_(self.c_sc.weight, 1.0)
megengine.module.init.xavier_uniform_
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _upsample_conv(self, x, conv): r""" Helper function for performing convolution after upsampling. """ return conv( F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)) def _residual(self, x): r""" Helper function for feedforwarding through main layers. """ h = x h = self.b1(h) h = self.activation(h) h = self._upsample_conv(h, self.c1) if self.upsample else self.c1(h) h = self.b2(h) h = self.activation(h) h = self.c2(h) return h def _shortcut(self, x): r""" Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self._upsample_conv( x, self.c_sc) if self.upsample else self.c_sc(x) return x else: return x def forward(self, x): r""" Residual block feedforward function. """ return self._residual(x) + self._shortcut(x) class DBlock(M.Module): """ Residual block for discriminator. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. downsample (bool): If True, downsamples the input feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, downsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else in_channels self.downsample = downsample self.learnable_sc = (in_channels != out_channels) or downsample # Build the layers self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, 1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, 1) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc =
M.Conv2d(in_channels, out_channels, 1, 1, 0)
megengine.module.Conv2d
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _upsample_conv(self, x, conv): r""" Helper function for performing convolution after upsampling. """ return conv( F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)) def _residual(self, x): r""" Helper function for feedforwarding through main layers. """ h = x h = self.b1(h) h = self.activation(h) h = self._upsample_conv(h, self.c1) if self.upsample else self.c1(h) h = self.b2(h) h = self.activation(h) h = self.c2(h) return h def _shortcut(self, x): r""" Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self._upsample_conv( x, self.c_sc) if self.upsample else self.c_sc(x) return x else: return x def forward(self, x): r""" Residual block feedforward function. """ return self._residual(x) + self._shortcut(x) class DBlock(M.Module): """ Residual block for discriminator. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. downsample (bool): If True, downsamples the input feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, downsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else in_channels self.downsample = downsample self.learnable_sc = (in_channels != out_channels) or downsample # Build the layers self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, 1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, 1) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, 0)
M.init.xavier_uniform_(self.c_sc.weight, 1.0)
megengine.module.init.xavier_uniform_
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _upsample_conv(self, x, conv): r""" Helper function for performing convolution after upsampling. """ return conv( F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)) def _residual(self, x): r""" Helper function for feedforwarding through main layers. """ h = x h = self.b1(h) h = self.activation(h) h = self._upsample_conv(h, self.c1) if self.upsample else self.c1(h) h = self.b2(h) h = self.activation(h) h = self.c2(h) return h def _shortcut(self, x): r""" Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self._upsample_conv( x, self.c_sc) if self.upsample else self.c_sc(x) return x else: return x def forward(self, x): r""" Residual block feedforward function. """ return self._residual(x) + self._shortcut(x) class DBlock(M.Module): """ Residual block for discriminator. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. downsample (bool): If True, downsamples the input feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, downsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else in_channels self.downsample = downsample self.learnable_sc = (in_channels != out_channels) or downsample # Build the layers self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, 1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, 1) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, 0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _residual(self, x): """ Helper function for feedforwarding through main layers. """ h = x h = self.activation(h) h = self.c1(h) h = self.activation(h) h = self.c2(h) if self.downsample: h =
F.avg_pool2d(h, 2)
megengine.functional.avg_pool2d
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _upsample_conv(self, x, conv): r""" Helper function for performing convolution after upsampling. """ return conv( F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)) def _residual(self, x): r""" Helper function for feedforwarding through main layers. """ h = x h = self.b1(h) h = self.activation(h) h = self._upsample_conv(h, self.c1) if self.upsample else self.c1(h) h = self.b2(h) h = self.activation(h) h = self.c2(h) return h def _shortcut(self, x): r""" Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self._upsample_conv( x, self.c_sc) if self.upsample else self.c_sc(x) return x else: return x def forward(self, x): r""" Residual block feedforward function. """ return self._residual(x) + self._shortcut(x) class DBlock(M.Module): """ Residual block for discriminator. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. downsample (bool): If True, downsamples the input feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, downsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else in_channels self.downsample = downsample self.learnable_sc = (in_channels != out_channels) or downsample # Build the layers self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, 1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, 1) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, 0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _residual(self, x): """ Helper function for feedforwarding through main layers. """ h = x h = self.activation(h) h = self.c1(h) h = self.activation(h) h = self.c2(h) if self.downsample: h = F.avg_pool2d(h, 2) return h def _shortcut(self, x): """ Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self.c_sc(x) return F.avg_pool2d(x, 2) if self.downsample else x else: return x def forward(self, x): """ Residual block feedforward function. """ # NOTE: to completely reproduce pytorch, we use F.relu(x) to replace x in shortcut # since pytorch use inplace relu in residual branch. return self._residual(x) + self._shortcut(F.relu(x)) class DBlockOptimized(M.Module): """ Optimized residual block for discriminator. This is used as the first residual block, where there is a definite downsampling involved. Follows the official SNGAN reference implementation in chainer. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, spectral_norm=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.spectral_norm = spectral_norm # Build the layers self.c1 = M.Conv2d(self.in_channels, self.out_channels, 3, 1, 1) self.c2 = M.Conv2d(self.out_channels, self.out_channels, 3, 1, 1) self.c_sc = M.Conv2d(self.in_channels, self.out_channels, 1, 1, 0) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _residual(self, x): """ Helper function for feedforwarding through main layers. """ h = x h = self.c1(h) h = self.activation(h) h = self.c2(h) h = F.avg_pool2d(h, 2) return h def _shortcut(self, x): """ Helper function for feedforwarding through shortcut layers. """ return self.c_sc(
F.avg_pool2d(x, 2)
megengine.functional.avg_pool2d
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _upsample_conv(self, x, conv): r""" Helper function for performing convolution after upsampling. """ return conv( F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)) def _residual(self, x): r""" Helper function for feedforwarding through main layers. """ h = x h = self.b1(h) h = self.activation(h) h = self._upsample_conv(h, self.c1) if self.upsample else self.c1(h) h = self.b2(h) h = self.activation(h) h = self.c2(h) return h def _shortcut(self, x): r""" Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self._upsample_conv( x, self.c_sc) if self.upsample else self.c_sc(x) return x else: return x def forward(self, x): r""" Residual block feedforward function. """ return self._residual(x) + self._shortcut(x) class DBlock(M.Module): """ Residual block for discriminator. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. downsample (bool): If True, downsamples the input feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, downsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else in_channels self.downsample = downsample self.learnable_sc = (in_channels != out_channels) or downsample # Build the layers self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, 1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, 1) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, 0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _residual(self, x): """ Helper function for feedforwarding through main layers. """ h = x h = self.activation(h) h = self.c1(h) h = self.activation(h) h = self.c2(h) if self.downsample: h = F.avg_pool2d(h, 2) return h def _shortcut(self, x): """ Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self.c_sc(x) return
F.avg_pool2d(x, 2)
megengine.functional.avg_pool2d
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import math import megengine.functional as F import megengine.module as M class GBlock(M.Module): r""" Residual block for generator. Uses bilinear (rather than nearest) interpolation, and align_corners set to False. This is as per how torchvision does upsampling, as seen in: https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/_utils.py Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. upsample (bool): If True, upsamples the input feature map. num_classes (int): If more than 0, uses conditional batch norm instead. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, upsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else out_channels self.learnable_sc = in_channels != out_channels or upsample self.upsample = upsample self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, padding=1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, padding=1) self.b1 = M.BatchNorm2d(self.in_channels) self.b2 = M.BatchNorm2d(self.hidden_channels) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, padding=0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _upsample_conv(self, x, conv): r""" Helper function for performing convolution after upsampling. """ return conv( F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)) def _residual(self, x): r""" Helper function for feedforwarding through main layers. """ h = x h = self.b1(h) h = self.activation(h) h = self._upsample_conv(h, self.c1) if self.upsample else self.c1(h) h = self.b2(h) h = self.activation(h) h = self.c2(h) return h def _shortcut(self, x): r""" Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self._upsample_conv( x, self.c_sc) if self.upsample else self.c_sc(x) return x else: return x def forward(self, x): r""" Residual block feedforward function. """ return self._residual(x) + self._shortcut(x) class DBlock(M.Module): """ Residual block for discriminator. Attributes: in_channels (int): The channel size of input feature map. out_channels (int): The channel size of output feature map. hidden_channels (int): The channel size of intermediate feature maps. downsample (bool): If True, downsamples the input feature map. spectral_norm (bool): If True, uses spectral norm for convolutional layers. """ def __init__(self, in_channels, out_channels, hidden_channels=None, downsample=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels if hidden_channels is not None else in_channels self.downsample = downsample self.learnable_sc = (in_channels != out_channels) or downsample # Build the layers self.c1 = M.Conv2d(self.in_channels, self.hidden_channels, 3, 1, 1) self.c2 = M.Conv2d(self.hidden_channels, self.out_channels, 3, 1, 1) self.activation = M.ReLU() M.init.xavier_uniform_(self.c1.weight, math.sqrt(2.0)) M.init.xavier_uniform_(self.c2.weight, math.sqrt(2.0)) # Shortcut layer if self.learnable_sc: self.c_sc = M.Conv2d(in_channels, out_channels, 1, 1, 0) M.init.xavier_uniform_(self.c_sc.weight, 1.0) def _residual(self, x): """ Helper function for feedforwarding through main layers. """ h = x h = self.activation(h) h = self.c1(h) h = self.activation(h) h = self.c2(h) if self.downsample: h = F.avg_pool2d(h, 2) return h def _shortcut(self, x): """ Helper function for feedforwarding through shortcut layers. """ if self.learnable_sc: x = self.c_sc(x) return F.avg_pool2d(x, 2) if self.downsample else x else: return x def forward(self, x): """ Residual block feedforward function. """ # NOTE: to completely reproduce pytorch, we use F.relu(x) to replace x in shortcut # since pytorch use inplace relu in residual branch. return self._residual(x) + self._shortcut(
F.relu(x)
megengine.functional.relu
#!/usr/bin/env python # -*-coding=utf-8-*- from megengine.logger import get_logger logger =
get_logger(__name__)
megengine.logger.get_logger
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if
dist.is_distributed()
megengine.distributed.is_distributed
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) / dist.get_world_size() acc5 = dist.all_reduce_sum(acc5) / dist.get_world_size() return loss, acc1, acc5 def valid_func(image, label): model.eval() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) if
dist.is_distributed()
megengine.distributed.is_distributed
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss =
dist.all_reduce_sum(loss)
megengine.distributed.all_reduce_sum
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) /
dist.get_world_size()
megengine.distributed.get_world_size
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 =
dist.all_reduce_sum(acc1)
megengine.distributed.all_reduce_sum
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) /
dist.get_world_size()
megengine.distributed.get_world_size
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) / dist.get_world_size() acc5 =
dist.all_reduce_sum(acc5)
megengine.distributed.all_reduce_sum
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) / dist.get_world_size() acc5 = dist.all_reduce_sum(acc5) /
dist.get_world_size()
megengine.distributed.get_world_size
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) / dist.get_world_size() acc5 = dist.all_reduce_sum(acc5) / dist.get_world_size() return loss, acc1, acc5 def valid_func(image, label): model.eval() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) if dist.is_distributed(): # all_reduce_mean loss =
dist.all_reduce_sum(loss)
megengine.distributed.all_reduce_sum
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) / dist.get_world_size() acc5 = dist.all_reduce_sum(acc5) / dist.get_world_size() return loss, acc1, acc5 def valid_func(image, label): model.eval() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) /
dist.get_world_size()
megengine.distributed.get_world_size
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) / dist.get_world_size() acc5 = dist.all_reduce_sum(acc5) / dist.get_world_size() return loss, acc1, acc5 def valid_func(image, label): model.eval() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 =
dist.all_reduce_sum(acc1)
megengine.distributed.all_reduce_sum
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) / dist.get_world_size() acc5 = dist.all_reduce_sum(acc5) / dist.get_world_size() return loss, acc1, acc5 def valid_func(image, label): model.eval() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) /
dist.get_world_size()
megengine.distributed.get_world_size
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) / dist.get_world_size() acc5 = dist.all_reduce_sum(acc5) / dist.get_world_size() return loss, acc1, acc5 def valid_func(image, label): model.eval() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) / dist.get_world_size() acc5 =
dist.all_reduce_sum(acc5)
megengine.distributed.all_reduce_sum
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) / dist.get_world_size() acc5 = dist.all_reduce_sum(acc5) / dist.get_world_size() return loss, acc1, acc5 def valid_func(image, label): model.eval() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) / dist.get_world_size() acc5 = dist.all_reduce_sum(acc5) /
dist.get_world_size()
megengine.distributed.get_world_size
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ------------------------------------------------------------------------------ # 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. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import argparse import multiprocessing as mp import os import time import sys import logging import megengine.distributed as dist import torch import torch.optim as optim import torch.nn.functional as F import datasets import torchvision.transforms as transforms import shufflenet_v2_pytorch as M from tensorboardX import SummaryWriter from devkit.core import (init_dist, broadcast_params, average_gradients, load_state_ckpt, load_state, save_checkpoint, LRScheduler, CrossEntropyLoss) def main(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", default="shufflenet_v2_x0_5", type=str) parser.add_argument("-d", "--data", default=None, type=str) parser.add_argument("-s", "--save", default="./models", type=str) parser.add_argument("-m", "--model", default=None, type=str) parser.add_argument('-o', '--output', type=str, required=True, help='set path for checkpoints \w tensorboard') parser.add_argument("-b", "--batch-size", default=128, type=int) parser.add_argument("--learning-rate", default=0.0625, type=float) parser.add_argument("--momentum", default=0.9, type=float) parser.add_argument("--weight-decay", default=4e-5, type=float) parser.add_argument("--steps", default=300000, type=int) parser.add_argument("-n", "--ngpus", default=None, type=int) parser.add_argument("-w", "--workers", default=4, type=int) parser.add_argument("--report-freq", default=50, type=int) parser.add_argument( '--port', default=29500, type=int, help='port of server') args = parser.parse_args() rank, world_size = init_dist( backend='nccl', port=args.port) if not os.path.exists(args.output): os.makedirs(args.output) if world_size > 1: # scale learning rate by number of gpus args.learning_rate *= world_size # start distributed training, dispatch sub-processes mp.set_start_method("spawn") processes = [] for rank in range(world_size): p = mp.Process(target=worker, args=(rank, world_size, args)) p.start() processes.append(p) for p in processes: p.join() else: worker(0, 1, args) def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if p.requires_grad: if pname.find("weight") >= 0 and len(p.shape) > 1: # print("include ", pname, p.shape) group_weight_decay.append(p) else: # print("not include ", pname, p.shape) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len(group_weight_decay) + len( group_no_weight_decay ) groups = [ dict(params=group_weight_decay), dict(params=group_no_weight_decay, weight_decay=0.0), ] return groups def worker(rank, world_size, args): # pylint: disable=too-many-statements if rank == 0: save_dir = os.path.join(args.save, args.arch, "b{}".format(args.batch_size * world_size)) if not os.path.exists(save_dir): os.makedirs(save_dir) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(save_dir, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if world_size > 1: # Initialize distributed process group logging.info("init distributed process group {} / {}".format(rank, world_size)) dist.init_process_group( master_ip="localhost", master_port=23456, world_size=world_size, rank=rank, dev=rank, ) save_dir = os.path.join(args.save, args.arch) if rank == 0: prefixs=['train', 'valid'] writers = {prefix: SummaryWriter(os.path.join(args.output, prefix)) for prefix in prefixs} model = getattr(M, args.arch)() step_start = 0 # if args.model: # logging.info("load weights from %s", args.model) # model.load_state_dict(mge.load(args.model)) # step_start = int(args.model.split("-")[1].split(".")[0]) optimizer = optim.SGD( get_parameters(model), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay, ) # Define train and valid graph def train_func(image, label): model.train() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) optimizer.backward(loss) # compute gradients if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) / dist.get_world_size() acc5 = dist.all_reduce_sum(acc5) / dist.get_world_size() return loss, acc1, acc5 def valid_func(image, label): model.eval() logits = model(image) loss = F.cross_entropy_with_softmax(logits, label, label_smooth=0.1) acc1, acc5 = F.accuracy(logits, label, (1, 5)) if dist.is_distributed(): # all_reduce_mean loss = dist.all_reduce_sum(loss) / dist.get_world_size() acc1 = dist.all_reduce_sum(acc1) / dist.get_world_size() acc5 = dist.all_reduce_sum(acc5) / dist.get_world_size() return loss, acc1, acc5 # Build train and valid datasets logging.info("preparing dataset..") transform = transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) train_dataset = datasets.ImageNet(split='train', transform=transform) train_sampler = torch.utils.data.RandomSampler(train_dataset) train_queue = torch.utils.data.DataLoader( train_dataset, batch_size=args.batch_size, sampler=train_sampler, shuffle=False, drop_last=True, pin_memory=True, num_workers=args.workers ) train_queue = iter(train_queue) transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) valid_dataset = datasets.ImageNet(split='val', transform=transform) valid_sampler = torch.utils.data.SequentialSampler(valid_dataset) valid_queue = torch.utils.data.DataLoader( valid_dataset, batch_size=100, sampler=valid_sampler, shuffle=False, drop_last=False, num_workers=args.workers ) # Start training objs = AverageMeter("Loss") top1 = AverageMeter("Acc@1") top5 = AverageMeter("Acc@5") total_time = AverageMeter("Time") t = time.time() best_valid_acc = 0 for step in range(step_start, args.steps + 1): # Linear learning rate decay decay = 1.0 decay = 1 - float(step) / args.steps if step < args.steps else 0 for param_group in optimizer.param_groups: param_group["lr"] = args.learning_rate * decay image, label = next(train_queue) time_data=time.time()-t # image = image.astype("float32") # label = label.astype("int32") n = image.shape[0] optimizer.zero_grad() loss, acc1, acc5 = train_func(image, label) optimizer.step() top1.update(100 * acc1.numpy()[0], n) top5.update(100 * acc5.numpy()[0], n) objs.update(loss.numpy()[0], n) total_time.update(time.time() - t) time_iter=time.time()-t t = time.time() if step % args.report_freq == 0 and rank == 0: logging.info( "TRAIN Iter %06d: lr = %f,\tloss = %f,\twc_loss = 1,\tTop-1 err = %f,\tTop-5 err = %f,\tdata_time = %f,\ttrain_time = %f,\tremain_hours=%f", step, args.learning_rate * decay, float(objs.__str__().split()[1]), 1-float(top1.__str__().split()[1])/100, 1-float(top5.__str__().split()[1])/100, time_data, time_iter - time_data, time_iter * (args.steps - step) / 3600, ) writers['train'].add_scalar('loss', float(objs.__str__().split()[1]), global_step=step) writers['train'].add_scalar('top1_err', 1-float(top1.__str__().split()[1])/100, global_step=step) writers['train'].add_scalar('top5_err', 1-float(top5.__str__().split()[1])/100, global_step=step) objs.reset() top1.reset() top5.reset() total_time.reset() if step % 10000 == 0 and step != 0: loss, valid_acc, valid_acc5 = infer(valid_func, valid_queue, args) logging.info("TEST Iter %06d: loss = %f,\tTop-1 err = %f,\tTop-5 err = %f", step, loss, 1-valid_acc/100, 1-valid_acc5/100) is_best = valid_acc > best_valid_acc best_valid_acc = max(valid_acc, best_valid_acc) if rank == 0: writers['valid'].add_scalar('loss', loss, global_step=step) writers['valid'].add_scalar('top1_err', 1-valid_acc/100, global_step=step) writers['valid'].add_scalar('top5_err', 1-valid_acc5/100, global_step=step) logging.info("SAVING %06d", step) save_checkpoint(save_dir, { 'step': step + 1, 'model': args.arch, 'state_dict': model.state_dict(), 'best_prec1': best_valid_acc, 'optimizer': optimizer.state_dict(), }, is_best) def infer(model, data_queue, args): objs = AverageMeter("Loss") top1 = AverageMeter("Acc@1") top5 = AverageMeter("Acc@5") total_time = AverageMeter("Time") t = time.time() for step, (image, label) in enumerate(data_queue): n = image.shape[0] image = image.astype("float32") # convert np.uint8 to float32 label = label.astype("int32") loss, acc1, acc5 = model(image, label) objs.update(loss.numpy()[0], n) top1.update(100 * acc1.numpy()[0], n) top5.update(100 * acc5.numpy()[0], n) total_time.update(time.time() - t) t = time.time() if step % args.report_freq == 0 and
dist.get_rank()
megengine.distributed.get_rank
# 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. # pylint: disable=import-error,no-name-in-module,no-member from typing import List, Union import megengine as mge from megengine.traced_module import TracedModule from ..backend.ir_to_onnx.onnx_converter import OnnxConverter from ..converter_ir.ir_quantizer import IRQuantizer from ..converter_ir.ir_transform import IRTransform, TransformerRule from ..frontend.tm_to_ir import TM_FrontEnd from ..frontend.tm_to_ir.tm_utils import _update_inputs_qparams def tracedmodule_to_onnx( traced_module, output="out.onnx", *, graph_name="graph", opset=8, outspec=None, input_data_type: str = None, input_scales: Union[float, List[float]] = None, input_zero_points: Union[int, List[int]] = None, require_quantize=False, param_fake_quant=False, quantize_file_path="quant_params.json", ): """ Convert megengine model to ONNX, and save the ONNX model to file `output`. :param mge_fpath: the file path of megengine model. :type fpath: str :param output: the filename used for the saved model. :type output: str :param graph_name: the name of the ONNX graph. :type graph_name: str :param opset: opset version of ONNX model. :type opset: int """ if isinstance(traced_module, str): traced_module =
mge.load(traced_module)
megengine.load
import numpy as np from megengine import tensor def _default_compare_fn(x, y): np.testing.assert_allclose(x.numpy(), y, rtol=1e-6) def opr_test(cases, func, compare_fn=_default_compare_fn, ref_fn=None, **kwargs): """ :param cases: the list which have dict element, the list length should be 2 for dynamic shape test. and the dict should have input, and should have output if ref_fn is None. should use list for multiple inputs and outputs for each case. :param func: the function to run opr. :param compare_fn: the function to compare the result and expected, use ``np.testing.assert_allclose`` if None. :param ref_fn: the function to generate expected data, should assign output if None. Examples: .. code-block:: dtype = np.float32 cases = [{"input": [10, 20]}, {"input": [20, 30]}] opr_test(cases, F.eye, ref_fn=lambda n, m: np.eye(n, m).astype(dtype), dtype=dtype) """ def check_results(results, expected): if not isinstance(results, (tuple, list)): results = (results,) for r, e in zip(results, expected): compare_fn(r, e) def get_param(cases, idx): case = cases[idx] inp = case.get("input", None) outp = case.get("output", None) if inp is None: raise ValueError("the test case should have input") if not isinstance(inp, (tuple, list)): inp = (inp,) if ref_fn is not None and callable(ref_fn): outp = ref_fn(*inp) if outp is None: raise ValueError("the test case should have output or reference function") if not isinstance(outp, (tuple, list)): outp = (outp,) return inp, outp if len(cases) == 0: raise ValueError("should give one case at least") if not callable(func): raise ValueError("the input func should be callable") inp, outp = get_param(cases, 0) inp_tensor = [
tensor(inpi)
megengine.tensor
from itertools import product import numpy as np from megengine import tensor from megengine.module import ( Conv2d, ConvBn2d, ConvRelu2d, DequantStub, Module, QuantStub, ) from megengine.quantization.quantize import disable_fake_quant, quantize_qat def test_qat_convbn2d(): in_channels = 32 out_channels = 64 kernel_size = 3 for groups, bias in product([1, 4], [True, False]): module = ConvBn2d( in_channels, out_channels, kernel_size, groups=groups, bias=bias ) module.train() qat_module =
quantize_qat(module, inplace=False)
megengine.quantization.quantize.quantize_qat
from itertools import product import numpy as np from megengine import tensor from megengine.module import ( Conv2d, ConvBn2d, ConvRelu2d, DequantStub, Module, QuantStub, ) from megengine.quantization.quantize import disable_fake_quant, quantize_qat def test_qat_convbn2d(): in_channels = 32 out_channels = 64 kernel_size = 3 for groups, bias in product([1, 4], [True, False]): module = ConvBn2d( in_channels, out_channels, kernel_size, groups=groups, bias=bias ) module.train() qat_module = quantize_qat(module, inplace=False)
disable_fake_quant(qat_module)
megengine.quantization.quantize.disable_fake_quant
from itertools import product import numpy as np from megengine import tensor from megengine.module import ( Conv2d, ConvBn2d, ConvRelu2d, DequantStub, Module, QuantStub, ) from megengine.quantization.quantize import disable_fake_quant, quantize_qat def test_qat_convbn2d(): in_channels = 32 out_channels = 64 kernel_size = 3 for groups, bias in product([1, 4], [True, False]): module = ConvBn2d( in_channels, out_channels, kernel_size, groups=groups, bias=bias ) module.train() qat_module = quantize_qat(module, inplace=False) disable_fake_quant(qat_module) inputs = tensor(np.random.randn(4, in_channels, 32, 32).astype(np.float32)) normal_outputs = module(inputs) # import pdb # pdb.set_trace() qat_outputs = qat_module(inputs) np.testing.assert_allclose( normal_outputs.numpy(), qat_outputs.numpy(), atol=5e-6 ) np.testing.assert_allclose( module.bn.running_mean.numpy(), qat_module.bn.running_mean.numpy(), atol=5e-8, ) np.testing.assert_allclose( module.bn.running_var.numpy(), qat_module.bn.running_var.numpy(), atol=5e-7, ) module.eval() normal_outputs = module(inputs) qat_module.eval() qat_outputs = qat_module(inputs) np.testing.assert_allclose( normal_outputs.numpy(), qat_outputs.numpy(), atol=5e-6 ) def test_qat_conv(): in_channels = 32 out_channels = 64 kernel_size = 3 class TestNet(Module): def __init__(self, groups, bias): super().__init__() self.quant = QuantStub() self.dequant = DequantStub() self.conv = Conv2d( in_channels, out_channels, kernel_size, groups=groups, bias=bias ) self.conv_relu = ConvRelu2d( out_channels, in_channels, kernel_size, groups=groups, bias=bias ) def forward(self, inp): out = self.quant(inp) out = self.conv(out) out = self.conv_relu(out) out = self.dequant(out) return out inputs = tensor(np.random.randn(4, in_channels, 32, 32).astype(np.float32)) for groups, bias in product([1, 4], [True, False]): net = TestNet(groups, bias) net.train() qat_net =
quantize_qat(net, inplace=False)
megengine.quantization.quantize.quantize_qat
from itertools import product import numpy as np from megengine import tensor from megengine.module import ( Conv2d, ConvBn2d, ConvRelu2d, DequantStub, Module, QuantStub, ) from megengine.quantization.quantize import disable_fake_quant, quantize_qat def test_qat_convbn2d(): in_channels = 32 out_channels = 64 kernel_size = 3 for groups, bias in product([1, 4], [True, False]): module = ConvBn2d( in_channels, out_channels, kernel_size, groups=groups, bias=bias ) module.train() qat_module = quantize_qat(module, inplace=False) disable_fake_quant(qat_module) inputs = tensor(np.random.randn(4, in_channels, 32, 32).astype(np.float32)) normal_outputs = module(inputs) # import pdb # pdb.set_trace() qat_outputs = qat_module(inputs) np.testing.assert_allclose( normal_outputs.numpy(), qat_outputs.numpy(), atol=5e-6 ) np.testing.assert_allclose( module.bn.running_mean.numpy(), qat_module.bn.running_mean.numpy(), atol=5e-8, ) np.testing.assert_allclose( module.bn.running_var.numpy(), qat_module.bn.running_var.numpy(), atol=5e-7, ) module.eval() normal_outputs = module(inputs) qat_module.eval() qat_outputs = qat_module(inputs) np.testing.assert_allclose( normal_outputs.numpy(), qat_outputs.numpy(), atol=5e-6 ) def test_qat_conv(): in_channels = 32 out_channels = 64 kernel_size = 3 class TestNet(Module): def __init__(self, groups, bias): super().__init__() self.quant = QuantStub() self.dequant = DequantStub() self.conv = Conv2d( in_channels, out_channels, kernel_size, groups=groups, bias=bias ) self.conv_relu = ConvRelu2d( out_channels, in_channels, kernel_size, groups=groups, bias=bias ) def forward(self, inp): out = self.quant(inp) out = self.conv(out) out = self.conv_relu(out) out = self.dequant(out) return out inputs = tensor(np.random.randn(4, in_channels, 32, 32).astype(np.float32)) for groups, bias in product([1, 4], [True, False]): net = TestNet(groups, bias) net.train() qat_net = quantize_qat(net, inplace=False)
disable_fake_quant(qat_net)
megengine.quantization.quantize.disable_fake_quant
from itertools import product import numpy as np from megengine import tensor from megengine.module import ( Conv2d, ConvBn2d, ConvRelu2d, DequantStub, Module, QuantStub, ) from megengine.quantization.quantize import disable_fake_quant, quantize_qat def test_qat_convbn2d(): in_channels = 32 out_channels = 64 kernel_size = 3 for groups, bias in product([1, 4], [True, False]): module = ConvBn2d( in_channels, out_channels, kernel_size, groups=groups, bias=bias ) module.train() qat_module = quantize_qat(module, inplace=False) disable_fake_quant(qat_module) inputs = tensor(np.random.randn(4, in_channels, 32, 32).astype(np.float32)) normal_outputs = module(inputs) # import pdb # pdb.set_trace() qat_outputs = qat_module(inputs) np.testing.assert_allclose( normal_outputs.numpy(), qat_outputs.numpy(), atol=5e-6 ) np.testing.assert_allclose( module.bn.running_mean.numpy(), qat_module.bn.running_mean.numpy(), atol=5e-8, ) np.testing.assert_allclose( module.bn.running_var.numpy(), qat_module.bn.running_var.numpy(), atol=5e-7, ) module.eval() normal_outputs = module(inputs) qat_module.eval() qat_outputs = qat_module(inputs) np.testing.assert_allclose( normal_outputs.numpy(), qat_outputs.numpy(), atol=5e-6 ) def test_qat_conv(): in_channels = 32 out_channels = 64 kernel_size = 3 class TestNet(Module): def __init__(self, groups, bias): super().__init__() self.quant =
QuantStub()
megengine.module.QuantStub
from itertools import product import numpy as np from megengine import tensor from megengine.module import ( Conv2d, ConvBn2d, ConvRelu2d, DequantStub, Module, QuantStub, ) from megengine.quantization.quantize import disable_fake_quant, quantize_qat def test_qat_convbn2d(): in_channels = 32 out_channels = 64 kernel_size = 3 for groups, bias in product([1, 4], [True, False]): module = ConvBn2d( in_channels, out_channels, kernel_size, groups=groups, bias=bias ) module.train() qat_module = quantize_qat(module, inplace=False) disable_fake_quant(qat_module) inputs = tensor(np.random.randn(4, in_channels, 32, 32).astype(np.float32)) normal_outputs = module(inputs) # import pdb # pdb.set_trace() qat_outputs = qat_module(inputs) np.testing.assert_allclose( normal_outputs.numpy(), qat_outputs.numpy(), atol=5e-6 ) np.testing.assert_allclose( module.bn.running_mean.numpy(), qat_module.bn.running_mean.numpy(), atol=5e-8, ) np.testing.assert_allclose( module.bn.running_var.numpy(), qat_module.bn.running_var.numpy(), atol=5e-7, ) module.eval() normal_outputs = module(inputs) qat_module.eval() qat_outputs = qat_module(inputs) np.testing.assert_allclose( normal_outputs.numpy(), qat_outputs.numpy(), atol=5e-6 ) def test_qat_conv(): in_channels = 32 out_channels = 64 kernel_size = 3 class TestNet(Module): def __init__(self, groups, bias): super().__init__() self.quant = QuantStub() self.dequant =
DequantStub()
megengine.module.DequantStub
#!/usr/bin/env python3 # Copyright (c) 2020 <NAME> # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (c) 2014-2021 Megvii Inc. All rights reserved. """LARS optimizer References: https://github.com/rwightman/pytorch-image-models/blob/master/timm/optim/lars.py """ import os from typing import Iterable, Union import megengine.functional as F from megengine import Parameter, tensor from megengine.functional.inplace import _inplace_add_ from megengine.optimizer import Optimizer class LARS(Optimizer): r"""Implements LARS algorithm. LARS is proposed in `"Large Batch Optimization for Deep Learning: Training BERT in 76 minutes" <https://arxiv.org/abs/1904.00962>`_. Args: params: iterable of parameters to optimize or dicts defining parameter groups. lr: learning rate. momentum: momentum factor. Default: ``0.0`` nesterov: enables Nesterov momentum. Default: ``False`` weight_decay: weight decay (L2 penalty). Default: ``0.0`` always_adapt: apply adaptive lr to ``0.0`` weight decay parameter. Default: ``False`` """ def __init__( self, params: Union[Iterable[Parameter], dict], lr: float, momentum: float = 0.0, nesterov: bool = False, weight_decay: float = 0.0, always_adapt: bool = False, ): if lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) if nesterov and momentum <= 0: raise ValueError("Nesterov momentum requires a momentum") defaults = dict(lr=lr, momentum=momentum, weight_decay=weight_decay) super().__init__(params, defaults) self.nesterov = nesterov self.always_adapt = always_adapt self._disable_type_convert = True def _create_state(self, param_group): if param_group["momentum"] != 0.0: for param in param_group["params"]: self._add_state(param, "momentum_buffer") def _updates(self, param_group): lr = param_group["lr"] weight_decay = param_group["weight_decay"] momentum = param_group["momentum"] # since `conver_inputs` is disabled for param updates, # scalar should be explicitly tansforred to tensor _lr =
tensor(lr)
megengine.tensor
#!/usr/bin/env python3 # Copyright (c) 2020 <NAME> # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (c) 2014-2021 Megvii Inc. All rights reserved. """LARS optimizer References: https://github.com/rwightman/pytorch-image-models/blob/master/timm/optim/lars.py """ import os from typing import Iterable, Union import megengine.functional as F from megengine import Parameter, tensor from megengine.functional.inplace import _inplace_add_ from megengine.optimizer import Optimizer class LARS(Optimizer): r"""Implements LARS algorithm. LARS is proposed in `"Large Batch Optimization for Deep Learning: Training BERT in 76 minutes" <https://arxiv.org/abs/1904.00962>`_. Args: params: iterable of parameters to optimize or dicts defining parameter groups. lr: learning rate. momentum: momentum factor. Default: ``0.0`` nesterov: enables Nesterov momentum. Default: ``False`` weight_decay: weight decay (L2 penalty). Default: ``0.0`` always_adapt: apply adaptive lr to ``0.0`` weight decay parameter. Default: ``False`` """ def __init__( self, params: Union[Iterable[Parameter], dict], lr: float, momentum: float = 0.0, nesterov: bool = False, weight_decay: float = 0.0, always_adapt: bool = False, ): if lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) if nesterov and momentum <= 0: raise ValueError("Nesterov momentum requires a momentum") defaults = dict(lr=lr, momentum=momentum, weight_decay=weight_decay) super().__init__(params, defaults) self.nesterov = nesterov self.always_adapt = always_adapt self._disable_type_convert = True def _create_state(self, param_group): if param_group["momentum"] != 0.0: for param in param_group["params"]: self._add_state(param, "momentum_buffer") def _updates(self, param_group): lr = param_group["lr"] weight_decay = param_group["weight_decay"] momentum = param_group["momentum"] # since `conver_inputs` is disabled for param updates, # scalar should be explicitly tansforred to tensor _lr = tensor(lr) _weight_decay =
tensor(weight_decay)
megengine.tensor
#!/usr/bin/env python3 # Copyright (c) 2020 <NAME> # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (c) 2014-2021 Megvii Inc. All rights reserved. """LARS optimizer References: https://github.com/rwightman/pytorch-image-models/blob/master/timm/optim/lars.py """ import os from typing import Iterable, Union import megengine.functional as F from megengine import Parameter, tensor from megengine.functional.inplace import _inplace_add_ from megengine.optimizer import Optimizer class LARS(Optimizer): r"""Implements LARS algorithm. LARS is proposed in `"Large Batch Optimization for Deep Learning: Training BERT in 76 minutes" <https://arxiv.org/abs/1904.00962>`_. Args: params: iterable of parameters to optimize or dicts defining parameter groups. lr: learning rate. momentum: momentum factor. Default: ``0.0`` nesterov: enables Nesterov momentum. Default: ``False`` weight_decay: weight decay (L2 penalty). Default: ``0.0`` always_adapt: apply adaptive lr to ``0.0`` weight decay parameter. Default: ``False`` """ def __init__( self, params: Union[Iterable[Parameter], dict], lr: float, momentum: float = 0.0, nesterov: bool = False, weight_decay: float = 0.0, always_adapt: bool = False, ): if lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) if nesterov and momentum <= 0: raise ValueError("Nesterov momentum requires a momentum") defaults = dict(lr=lr, momentum=momentum, weight_decay=weight_decay) super().__init__(params, defaults) self.nesterov = nesterov self.always_adapt = always_adapt self._disable_type_convert = True def _create_state(self, param_group): if param_group["momentum"] != 0.0: for param in param_group["params"]: self._add_state(param, "momentum_buffer") def _updates(self, param_group): lr = param_group["lr"] weight_decay = param_group["weight_decay"] momentum = param_group["momentum"] # since `conver_inputs` is disabled for param updates, # scalar should be explicitly tansforred to tensor _lr = tensor(lr) _weight_decay = tensor(weight_decay) _momentum =
tensor(momentum)
megengine.tensor
#!/usr/bin/env python3 # Copyright (c) 2020 <NAME> # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (c) 2014-2021 Megvii Inc. All rights reserved. """LARS optimizer References: https://github.com/rwightman/pytorch-image-models/blob/master/timm/optim/lars.py """ import os from typing import Iterable, Union import megengine.functional as F from megengine import Parameter, tensor from megengine.functional.inplace import _inplace_add_ from megengine.optimizer import Optimizer class LARS(Optimizer): r"""Implements LARS algorithm. LARS is proposed in `"Large Batch Optimization for Deep Learning: Training BERT in 76 minutes" <https://arxiv.org/abs/1904.00962>`_. Args: params: iterable of parameters to optimize or dicts defining parameter groups. lr: learning rate. momentum: momentum factor. Default: ``0.0`` nesterov: enables Nesterov momentum. Default: ``False`` weight_decay: weight decay (L2 penalty). Default: ``0.0`` always_adapt: apply adaptive lr to ``0.0`` weight decay parameter. Default: ``False`` """ def __init__( self, params: Union[Iterable[Parameter], dict], lr: float, momentum: float = 0.0, nesterov: bool = False, weight_decay: float = 0.0, always_adapt: bool = False, ): if lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) if nesterov and momentum <= 0: raise ValueError("Nesterov momentum requires a momentum") defaults = dict(lr=lr, momentum=momentum, weight_decay=weight_decay) super().__init__(params, defaults) self.nesterov = nesterov self.always_adapt = always_adapt self._disable_type_convert = True def _create_state(self, param_group): if param_group["momentum"] != 0.0: for param in param_group["params"]: self._add_state(param, "momentum_buffer") def _updates(self, param_group): lr = param_group["lr"] weight_decay = param_group["weight_decay"] momentum = param_group["momentum"] # since `conver_inputs` is disabled for param updates, # scalar should be explicitly tansforred to tensor _lr = tensor(lr) _weight_decay = tensor(weight_decay) _momentum = tensor(momentum) c1, c05, c0 = map(tensor, (1.0, 0.5, 0.0)) def norm(vec): return F.sum(vec * vec) ** c05 inplace_mode = int(os.getenv("MEGENGINE_INPLACE_UPDATE", "0")) if inplace_mode: _neg_lr =
tensor(-lr)
megengine.tensor
#!/usr/bin/env python3 # Copyright (c) 2020 <NAME> # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (c) 2014-2021 Megvii Inc. All rights reserved. """LARS optimizer References: https://github.com/rwightman/pytorch-image-models/blob/master/timm/optim/lars.py """ import os from typing import Iterable, Union import megengine.functional as F from megengine import Parameter, tensor from megengine.functional.inplace import _inplace_add_ from megengine.optimizer import Optimizer class LARS(Optimizer): r"""Implements LARS algorithm. LARS is proposed in `"Large Batch Optimization for Deep Learning: Training BERT in 76 minutes" <https://arxiv.org/abs/1904.00962>`_. Args: params: iterable of parameters to optimize or dicts defining parameter groups. lr: learning rate. momentum: momentum factor. Default: ``0.0`` nesterov: enables Nesterov momentum. Default: ``False`` weight_decay: weight decay (L2 penalty). Default: ``0.0`` always_adapt: apply adaptive lr to ``0.0`` weight decay parameter. Default: ``False`` """ def __init__( self, params: Union[Iterable[Parameter], dict], lr: float, momentum: float = 0.0, nesterov: bool = False, weight_decay: float = 0.0, always_adapt: bool = False, ): if lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) if nesterov and momentum <= 0: raise ValueError("Nesterov momentum requires a momentum") defaults = dict(lr=lr, momentum=momentum, weight_decay=weight_decay) super().__init__(params, defaults) self.nesterov = nesterov self.always_adapt = always_adapt self._disable_type_convert = True def _create_state(self, param_group): if param_group["momentum"] != 0.0: for param in param_group["params"]: self._add_state(param, "momentum_buffer") def _updates(self, param_group): lr = param_group["lr"] weight_decay = param_group["weight_decay"] momentum = param_group["momentum"] # since `conver_inputs` is disabled for param updates, # scalar should be explicitly tansforred to tensor _lr = tensor(lr) _weight_decay = tensor(weight_decay) _momentum = tensor(momentum) c1, c05, c0 = map(tensor, (1.0, 0.5, 0.0)) def norm(vec): return
F.sum(vec * vec)
megengine.functional.sum
#!/usr/bin/env python3 # Copyright (c) 2020 <NAME> # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (c) 2014-2021 Megvii Inc. All rights reserved. """LARS optimizer References: https://github.com/rwightman/pytorch-image-models/blob/master/timm/optim/lars.py """ import os from typing import Iterable, Union import megengine.functional as F from megengine import Parameter, tensor from megengine.functional.inplace import _inplace_add_ from megengine.optimizer import Optimizer class LARS(Optimizer): r"""Implements LARS algorithm. LARS is proposed in `"Large Batch Optimization for Deep Learning: Training BERT in 76 minutes" <https://arxiv.org/abs/1904.00962>`_. Args: params: iterable of parameters to optimize or dicts defining parameter groups. lr: learning rate. momentum: momentum factor. Default: ``0.0`` nesterov: enables Nesterov momentum. Default: ``False`` weight_decay: weight decay (L2 penalty). Default: ``0.0`` always_adapt: apply adaptive lr to ``0.0`` weight decay parameter. Default: ``False`` """ def __init__( self, params: Union[Iterable[Parameter], dict], lr: float, momentum: float = 0.0, nesterov: bool = False, weight_decay: float = 0.0, always_adapt: bool = False, ): if lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) if nesterov and momentum <= 0: raise ValueError("Nesterov momentum requires a momentum") defaults = dict(lr=lr, momentum=momentum, weight_decay=weight_decay) super().__init__(params, defaults) self.nesterov = nesterov self.always_adapt = always_adapt self._disable_type_convert = True def _create_state(self, param_group): if param_group["momentum"] != 0.0: for param in param_group["params"]: self._add_state(param, "momentum_buffer") def _updates(self, param_group): lr = param_group["lr"] weight_decay = param_group["weight_decay"] momentum = param_group["momentum"] # since `conver_inputs` is disabled for param updates, # scalar should be explicitly tansforred to tensor _lr = tensor(lr) _weight_decay = tensor(weight_decay) _momentum = tensor(momentum) c1, c05, c0 = map(tensor, (1.0, 0.5, 0.0)) def norm(vec): return F.sum(vec * vec) ** c05 inplace_mode = int(os.getenv("MEGENGINE_INPLACE_UPDATE", "0")) if inplace_mode: _neg_lr = tensor(-lr) for param in param_group["params"]: if param.grad is None: continue grad = param.grad if weight_decay != 0.0: grad = grad + param * _weight_decay p_norm = norm(param.flatten()) if inplace_mode: if momentum != 0.0: v = self._state[param]["momentum_buffer"] _inplace_add_(v, grad, alpha=_momentum, beta=c1) if self.nesterov: grad = grad + v * _momentum else: grad = v d_norm = norm(grad.flatten()) trust_ratio = ( p_norm / d_norm if (self.always_adapt or weight_decay > 0) and p_norm > c0 and d_norm > c0 else c1 )
_inplace_add_(param, grad, alpha=c1, beta=_neg_lr * trust_ratio)
megengine.functional.inplace._inplace_add_
#!/usr/bin/env python3 # Copyright (c) 2020 <NAME> # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (c) 2014-2021 Megvii Inc. All rights reserved. """LARS optimizer References: https://github.com/rwightman/pytorch-image-models/blob/master/timm/optim/lars.py """ import os from typing import Iterable, Union import megengine.functional as F from megengine import Parameter, tensor from megengine.functional.inplace import _inplace_add_ from megengine.optimizer import Optimizer class LARS(Optimizer): r"""Implements LARS algorithm. LARS is proposed in `"Large Batch Optimization for Deep Learning: Training BERT in 76 minutes" <https://arxiv.org/abs/1904.00962>`_. Args: params: iterable of parameters to optimize or dicts defining parameter groups. lr: learning rate. momentum: momentum factor. Default: ``0.0`` nesterov: enables Nesterov momentum. Default: ``False`` weight_decay: weight decay (L2 penalty). Default: ``0.0`` always_adapt: apply adaptive lr to ``0.0`` weight decay parameter. Default: ``False`` """ def __init__( self, params: Union[Iterable[Parameter], dict], lr: float, momentum: float = 0.0, nesterov: bool = False, weight_decay: float = 0.0, always_adapt: bool = False, ): if lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) if nesterov and momentum <= 0: raise ValueError("Nesterov momentum requires a momentum") defaults = dict(lr=lr, momentum=momentum, weight_decay=weight_decay) super().__init__(params, defaults) self.nesterov = nesterov self.always_adapt = always_adapt self._disable_type_convert = True def _create_state(self, param_group): if param_group["momentum"] != 0.0: for param in param_group["params"]: self._add_state(param, "momentum_buffer") def _updates(self, param_group): lr = param_group["lr"] weight_decay = param_group["weight_decay"] momentum = param_group["momentum"] # since `conver_inputs` is disabled for param updates, # scalar should be explicitly tansforred to tensor _lr = tensor(lr) _weight_decay = tensor(weight_decay) _momentum = tensor(momentum) c1, c05, c0 = map(tensor, (1.0, 0.5, 0.0)) def norm(vec): return F.sum(vec * vec) ** c05 inplace_mode = int(os.getenv("MEGENGINE_INPLACE_UPDATE", "0")) if inplace_mode: _neg_lr = tensor(-lr) for param in param_group["params"]: if param.grad is None: continue grad = param.grad if weight_decay != 0.0: grad = grad + param * _weight_decay p_norm = norm(param.flatten()) if inplace_mode: if momentum != 0.0: v = self._state[param]["momentum_buffer"]
_inplace_add_(v, grad, alpha=_momentum, beta=c1)
megengine.functional.inplace._inplace_add_
import os import megengine as mge import megengine.functional as F import argparse import numpy as np import cv2 from nets import Model def load_model(model_path): print("Loading model:", os.path.abspath(model_path)) pretrained_dict =
mge.load(model_path)
megengine.load
import os import megengine as mge import megengine.functional as F import argparse import numpy as np import cv2 from nets import Model def load_model(model_path): print("Loading model:", os.path.abspath(model_path)) pretrained_dict = mge.load(model_path) model = Model(max_disp=256, mixed_precision=False, test_mode=True) model.load_state_dict(pretrained_dict["state_dict"], strict=True) model.eval() return model def inference(left, right, model, n_iter=20): print("Model Forwarding...") imgL = left.transpose(2, 0, 1) imgR = right.transpose(2, 0, 1) imgL = np.ascontiguousarray(imgL[None, :, :, :]) imgR = np.ascontiguousarray(imgR[None, :, :, :]) imgL =
mge.tensor(imgL)
megengine.tensor
import os import megengine as mge import megengine.functional as F import argparse import numpy as np import cv2 from nets import Model def load_model(model_path): print("Loading model:", os.path.abspath(model_path)) pretrained_dict = mge.load(model_path) model = Model(max_disp=256, mixed_precision=False, test_mode=True) model.load_state_dict(pretrained_dict["state_dict"], strict=True) model.eval() return model def inference(left, right, model, n_iter=20): print("Model Forwarding...") imgL = left.transpose(2, 0, 1) imgR = right.transpose(2, 0, 1) imgL = np.ascontiguousarray(imgL[None, :, :, :]) imgR = np.ascontiguousarray(imgR[None, :, :, :]) imgL = mge.tensor(imgL).astype("float32") imgR =
mge.tensor(imgR)
megengine.tensor
import os import megengine as mge import megengine.functional as F import argparse import numpy as np import cv2 from nets import Model def load_model(model_path): print("Loading model:", os.path.abspath(model_path)) pretrained_dict = mge.load(model_path) model = Model(max_disp=256, mixed_precision=False, test_mode=True) model.load_state_dict(pretrained_dict["state_dict"], strict=True) model.eval() return model def inference(left, right, model, n_iter=20): print("Model Forwarding...") imgL = left.transpose(2, 0, 1) imgR = right.transpose(2, 0, 1) imgL = np.ascontiguousarray(imgL[None, :, :, :]) imgR = np.ascontiguousarray(imgR[None, :, :, :]) imgL = mge.tensor(imgL).astype("float32") imgR = mge.tensor(imgR).astype("float32") imgL_dw2 = F.nn.interpolate( imgL, size=(imgL.shape[2] // 2, imgL.shape[3] // 2), mode="bilinear", align_corners=True, ) imgR_dw2 = F.nn.interpolate( imgR, size=(imgL.shape[2] // 2, imgL.shape[3] // 2), mode="bilinear", align_corners=True, ) pred_flow_dw2 = model(imgL_dw2, imgR_dw2, iters=n_iter, flow_init=None) pred_flow = model(imgL, imgR, iters=n_iter, flow_init=pred_flow_dw2) pred_disp =
F.squeeze(pred_flow[:, 0, :, :])
megengine.functional.squeeze
import os import cv2 import argparse import warnings import megengine as mge import megengine.functional as F warnings.filterwarnings("ignore") parser = argparse.ArgumentParser(description='Interpolation for a pair of images') parser.add_argument('--img', dest='img', nargs=2, required=True) parser.add_argument('--exp', default=4, type=int) parser.add_argument('--ratio', default=0, type=float, help='inference ratio between two images with 0 - 1 range') parser.add_argument('--rthreshold', default=0.02, type=float, help='returns image when actual ratio falls in given range threshold') parser.add_argument('--rmaxcycles', default=8, type=int, help='limit max number of bisectional cycles') parser.add_argument('--model', dest='modelDir', type=str, default='train_log', help='directory with trained model files') args = parser.parse_args() from model.RIFE import Model model = Model() model.load_model(args.modelDir, -1) print("Loaded model") model.eval() if args.img[0].endswith('.exr') and args.img[1].endswith('.exr'): img0 = cv2.imread(args.img[0], cv2.IMREAD_COLOR | cv2.IMREAD_ANYDEPTH) img1 = cv2.imread(args.img[1], cv2.IMREAD_COLOR | cv2.IMREAD_ANYDEPTH) img0 = F.expand_dims(mge.Tensor(img0.transpose(2, 0, 1)), 0) img1 = F.expand_dims(mge.Tensor(img1.transpose(2, 0, 1)), 0) else: img0 = cv2.imread(args.img[0], cv2.IMREAD_UNCHANGED) img1 = cv2.imread(args.img[1], cv2.IMREAD_UNCHANGED) img0 = F.expand_dims(mge.Tensor(img0.transpose(2, 0, 1)) / 255. , 0) img1 = F.expand_dims(mge.Tensor(img1.transpose(2, 0, 1)) / 255. , 0) n, c, h, w = img0.shape ph = ((h - 1) // 32 + 1) * 32 pw = ((w - 1) // 32 + 1) * 32 padding = ((0, 0), (0, 0), (0, ph - h), (0, pw - w)) img0 =
F.nn.pad(img0, padding)
megengine.functional.nn.pad
import os import cv2 import argparse import warnings import megengine as mge import megengine.functional as F warnings.filterwarnings("ignore") parser = argparse.ArgumentParser(description='Interpolation for a pair of images') parser.add_argument('--img', dest='img', nargs=2, required=True) parser.add_argument('--exp', default=4, type=int) parser.add_argument('--ratio', default=0, type=float, help='inference ratio between two images with 0 - 1 range') parser.add_argument('--rthreshold', default=0.02, type=float, help='returns image when actual ratio falls in given range threshold') parser.add_argument('--rmaxcycles', default=8, type=int, help='limit max number of bisectional cycles') parser.add_argument('--model', dest='modelDir', type=str, default='train_log', help='directory with trained model files') args = parser.parse_args() from model.RIFE import Model model = Model() model.load_model(args.modelDir, -1) print("Loaded model") model.eval() if args.img[0].endswith('.exr') and args.img[1].endswith('.exr'): img0 = cv2.imread(args.img[0], cv2.IMREAD_COLOR | cv2.IMREAD_ANYDEPTH) img1 = cv2.imread(args.img[1], cv2.IMREAD_COLOR | cv2.IMREAD_ANYDEPTH) img0 = F.expand_dims(mge.Tensor(img0.transpose(2, 0, 1)), 0) img1 = F.expand_dims(mge.Tensor(img1.transpose(2, 0, 1)), 0) else: img0 = cv2.imread(args.img[0], cv2.IMREAD_UNCHANGED) img1 = cv2.imread(args.img[1], cv2.IMREAD_UNCHANGED) img0 = F.expand_dims(mge.Tensor(img0.transpose(2, 0, 1)) / 255. , 0) img1 = F.expand_dims(mge.Tensor(img1.transpose(2, 0, 1)) / 255. , 0) n, c, h, w = img0.shape ph = ((h - 1) // 32 + 1) * 32 pw = ((w - 1) // 32 + 1) * 32 padding = ((0, 0), (0, 0), (0, ph - h), (0, pw - w)) img0 = F.nn.pad(img0, padding) img1 =
F.nn.pad(img1, padding)
megengine.functional.nn.pad
# -*- 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 megengine as mge import megengine.functional as F import megengine.hub as hub import megengine.module as M import math import official.vision.classification.resnet.model as resnet import numpy as np class ResnetBody(M.Module): def __init__( self, block, init_channel, layers, channels, zero_init_residual=False, norm=M.BatchNorm2d, ): super(ResnetBody, self).__init__() self.in_channels = init_channel self.layer1 = self._make_layer( block, channels[0], layers[0], stride=1, norm=norm ) self.layer2 = self._make_layer( block, channels[1], layers[1], stride=2, norm=norm ) self.layer3 = self._make_layer( block, channels[2], layers[2], stride=2, norm=norm, ) self.layer4 = self._make_layer( block, channels[3], layers[3], stride=2, norm=norm, ) for m in self.modules(): if isinstance(m, M.Conv2d): M.init.msra_normal_(m.weight, mode="fan_out", nonlinearity="relu") if m.bias is not None: fan_in, _ = M.init.calculate_fan_in_and_fan_out(m.weight) bound = 1 / math.sqrt(fan_in) M.init.uniform_(m.bias, -bound, bound) elif isinstance(m, M.BatchNorm2d): M.init.ones_(m.weight) M.init.zeros_(m.bias) elif isinstance(m, M.Linear): M.init.msra_uniform_(m.weight, a=math.sqrt(5)) if m.bias is not None: fan_in, _ = M.init.calculate_fan_in_and_fan_out(m.weight) bound = 1 / math.sqrt(fan_in) M.init.uniform_(m.bias, -bound, bound) def _make_layer(self, block, channels, blocks, stride=1, norm=M.BatchNorm2d): layers = [] layers.append(block(self.in_channels, channels, stride, norm=norm)) self.in_channels = channels * block.expansion for _ in range(1, blocks): layers.append(block(self.in_channels, channels, norm=norm)) return M.Sequential(*layers) def forward(self, x): outputs = [] x = self.layer1(x) outputs.append(x) x = self.layer2(x) outputs.append(x) x = self.layer3(x) outputs.append(x) x = self.layer4(x) outputs.append(x) return outputs class SingleStage(M.Module): def __init__( self, block, init_channel, layers, channels, mid_channel, norm=M.BatchNorm2d ): super(SingleStage, self).__init__() self.down = ResnetBody(block, init_channel, layers, channels, norm) channel = block.expansion * channels[-1] self.up1 = M.Sequential( M.Conv2d(channel, mid_channel, 1, 1, 0), norm(mid_channel) ) self.deconv1 = M.Sequential( M.ConvTranspose2d(mid_channel, mid_channel, 4, 2, 1), norm(mid_channel) ) channel = block.expansion * channels[-2] self.up2 = M.Sequential( M.Conv2d(channel, mid_channel, 1, 1, 0), norm(mid_channel) ) self.deconv2 = M.Sequential( M.ConvTranspose2d(mid_channel, mid_channel, 4, 2, 1), norm(mid_channel) ) channel = block.expansion * channels[-3] self.up3 = M.Sequential( M.Conv2d(channel, mid_channel, 1, 1, 0), norm(mid_channel) ) self.deconv3 = M.Sequential( M.ConvTranspose2d(mid_channel, mid_channel, 4, 2, 1), norm(mid_channel) ) channel = block.expansion * channels[-4] self.up4 = M.Sequential( M.Conv2d(channel, mid_channel, 1, 1, 0), norm(mid_channel) ) def forward(self, x): branches = self.down(x) branches = list(reversed(branches)) outputs = [] f_up = F.relu(self.up1(branches[0])) outputs.append(f_up) f = self.up2(branches[1]) f_up = F.relu(self.deconv1(f_up) + f) outputs.append(f_up) f = self.up3(branches[2]) f_up = F.relu(self.deconv2(f_up) + f) outputs.append(f_up) f = self.up4(branches[3]) f_up = F.relu(self.deconv3(f_up) + f) outputs.append(f_up) return outputs class MSPN(M.Module): def __init__(self, block, layers, channels, mid_channel, keypoint_num, nr_stg): super(MSPN, self).__init__() block = getattr(resnet, block) norm = M.BatchNorm2d self.nr_stg = nr_stg self.keypoint_num = keypoint_num self.head = M.Sequential( M.Conv2d(3, 64, 3, 2, 1), norm(64), M.ReLU(), M.Conv2d(64, 64, 3, 1, 1), norm(64), M.ReLU(), M.Conv2d(64, 64, 3, 2, 1), norm(64), M.ReLU(), ) self.stages = {} for i in range(nr_stg): init_channel = 64 self.stages["Stage_{}_body".format(i)] = SingleStage( block, init_channel, layers, channels, mid_channel, norm ) tail = {} for j in range(4): tail["tail_{}".format(j)] = M.Conv2d(mid_channel, keypoint_num, 3, 1, 1) self.stages["Stage_{}_tail".format(i)] = tail if i < nr_stg - 1: self.stages["Stage_{}_next".format(i)] = M.Sequential( M.Conv2d(mid_channel, 64, 1, 1, 0), norm(64), M.ReLU() ) self.inputs = { "image": mge.tensor(dtype="float32"), "heatmap": mge.tensor(dtype="float32"), "heat_valid": mge.tensor(dtype="float32"), } def calc_loss(self): outs = self.forward(self.inputs["image"]) loss = 0 for stage_out in outs: for ind, scale_out in enumerate(stage_out[:-1]): label = ( self.inputs["heatmap"][:, ind] * (self.inputs["heat_valid"] > 1.1)[:, :, None, None] ) tmp = F.square_loss(scale_out, label) loss += tmp / 4 / len(outs) # OHKM loss for the largest heatmap tmp = ((stage_out[-1] - self.inputs["heatmap"][:, -1]) ** 2).mean(3).mean( 2 ) * (self.inputs["heat_valid"] > 0.1) ohkm_loss = 0 for i in range(tmp.shape[0]): selected_loss, _ = F.top_k( tmp[i], self.keypoint_num // 2, descending=True ) ohkm_loss += selected_loss.mean() ohkm_loss /= tmp.shape[0] loss += ohkm_loss return loss def predict(self): outputs = self.forward(self.inputs["image"]) pred = outputs[-1][-1] return pred def forward(self, x): f = self.head(x) outputs = [] for i in range(self.nr_stg): multi_scale_features = self.stages["Stage_{}_body".format(i)](f) multi_scale_heatmaps = [] for j in range(4): out = self.stages["Stage_{}_tail".format(i)]["tail_{}".format(j)]( multi_scale_features[j] ) out = F.interpolate(out, scale_factor=2 ** (3 - j)) multi_scale_heatmaps.append(out) if i < self.nr_stg - 1: f = self.stages["Stage_{}_next".format(i)](multi_scale_features[-1]) outputs.append(multi_scale_heatmaps) return outputs @
hub.pretrained( "https://data.megengine.org.cn/models/weights/mspn_4stage_256x192_0_255_75_2.pkl" )
megengine.hub.pretrained
# -*- 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 megengine as mge import megengine.functional as F import megengine.hub as hub import megengine.module as M import math import official.vision.classification.resnet.model as resnet import numpy as np class ResnetBody(M.Module): def __init__( self, block, init_channel, layers, channels, zero_init_residual=False, norm=M.BatchNorm2d, ): super(ResnetBody, self).__init__() self.in_channels = init_channel self.layer1 = self._make_layer( block, channels[0], layers[0], stride=1, norm=norm ) self.layer2 = self._make_layer( block, channels[1], layers[1], stride=2, norm=norm ) self.layer3 = self._make_layer( block, channels[2], layers[2], stride=2, norm=norm, ) self.layer4 = self._make_layer( block, channels[3], layers[3], stride=2, norm=norm, ) for m in self.modules(): if isinstance(m, M.Conv2d): M.init.msra_normal_(m.weight, mode="fan_out", nonlinearity="relu") if m.bias is not None: fan_in, _ = M.init.calculate_fan_in_and_fan_out(m.weight) bound = 1 / math.sqrt(fan_in) M.init.uniform_(m.bias, -bound, bound) elif isinstance(m, M.BatchNorm2d): M.init.ones_(m.weight) M.init.zeros_(m.bias) elif isinstance(m, M.Linear): M.init.msra_uniform_(m.weight, a=math.sqrt(5)) if m.bias is not None: fan_in, _ = M.init.calculate_fan_in_and_fan_out(m.weight) bound = 1 / math.sqrt(fan_in) M.init.uniform_(m.bias, -bound, bound) def _make_layer(self, block, channels, blocks, stride=1, norm=M.BatchNorm2d): layers = [] layers.append(block(self.in_channels, channels, stride, norm=norm)) self.in_channels = channels * block.expansion for _ in range(1, blocks): layers.append(block(self.in_channels, channels, norm=norm)) return
M.Sequential(*layers)
megengine.module.Sequential
# -*- 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 megengine as mge import megengine.functional as F import megengine.hub as hub import megengine.module as M import math import official.vision.classification.resnet.model as resnet import numpy as np class ResnetBody(M.Module): def __init__( self, block, init_channel, layers, channels, zero_init_residual=False, norm=M.BatchNorm2d, ): super(ResnetBody, self).__init__() self.in_channels = init_channel self.layer1 = self._make_layer( block, channels[0], layers[0], stride=1, norm=norm ) self.layer2 = self._make_layer( block, channels[1], layers[1], stride=2, norm=norm ) self.layer3 = self._make_layer( block, channels[2], layers[2], stride=2, norm=norm, ) self.layer4 = self._make_layer( block, channels[3], layers[3], stride=2, norm=norm, ) for m in self.modules(): if isinstance(m, M.Conv2d): M.init.msra_normal_(m.weight, mode="fan_out", nonlinearity="relu") if m.bias is not None: fan_in, _ = M.init.calculate_fan_in_and_fan_out(m.weight) bound = 1 / math.sqrt(fan_in) M.init.uniform_(m.bias, -bound, bound) elif isinstance(m, M.BatchNorm2d): M.init.ones_(m.weight) M.init.zeros_(m.bias) elif isinstance(m, M.Linear): M.init.msra_uniform_(m.weight, a=math.sqrt(5)) if m.bias is not None: fan_in, _ = M.init.calculate_fan_in_and_fan_out(m.weight) bound = 1 / math.sqrt(fan_in) M.init.uniform_(m.bias, -bound, bound) def _make_layer(self, block, channels, blocks, stride=1, norm=M.BatchNorm2d): layers = [] layers.append(block(self.in_channels, channels, stride, norm=norm)) self.in_channels = channels * block.expansion for _ in range(1, blocks): layers.append(block(self.in_channels, channels, norm=norm)) return M.Sequential(*layers) def forward(self, x): outputs = [] x = self.layer1(x) outputs.append(x) x = self.layer2(x) outputs.append(x) x = self.layer3(x) outputs.append(x) x = self.layer4(x) outputs.append(x) return outputs class SingleStage(M.Module): def __init__( self, block, init_channel, layers, channels, mid_channel, norm=M.BatchNorm2d ): super(SingleStage, self).__init__() self.down = ResnetBody(block, init_channel, layers, channels, norm) channel = block.expansion * channels[-1] self.up1 = M.Sequential(
M.Conv2d(channel, mid_channel, 1, 1, 0)
megengine.module.Conv2d
# -*- 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 megengine as mge import megengine.functional as F import megengine.hub as hub import megengine.module as M import math import official.vision.classification.resnet.model as resnet import numpy as np class ResnetBody(M.Module): def __init__( self, block, init_channel, layers, channels, zero_init_residual=False, norm=M.BatchNorm2d, ): super(ResnetBody, self).__init__() self.in_channels = init_channel self.layer1 = self._make_layer( block, channels[0], layers[0], stride=1, norm=norm ) self.layer2 = self._make_layer( block, channels[1], layers[1], stride=2, norm=norm ) self.layer3 = self._make_layer( block, channels[2], layers[2], stride=2, norm=norm, ) self.layer4 = self._make_layer( block, channels[3], layers[3], stride=2, norm=norm, ) for m in self.modules(): if isinstance(m, M.Conv2d): M.init.msra_normal_(m.weight, mode="fan_out", nonlinearity="relu") if m.bias is not None: fan_in, _ = M.init.calculate_fan_in_and_fan_out(m.weight) bound = 1 / math.sqrt(fan_in) M.init.uniform_(m.bias, -bound, bound) elif isinstance(m, M.BatchNorm2d): M.init.ones_(m.weight) M.init.zeros_(m.bias) elif isinstance(m, M.Linear): M.init.msra_uniform_(m.weight, a=math.sqrt(5)) if m.bias is not None: fan_in, _ = M.init.calculate_fan_in_and_fan_out(m.weight) bound = 1 / math.sqrt(fan_in) M.init.uniform_(m.bias, -bound, bound) def _make_layer(self, block, channels, blocks, stride=1, norm=M.BatchNorm2d): layers = [] layers.append(block(self.in_channels, channels, stride, norm=norm)) self.in_channels = channels * block.expansion for _ in range(1, blocks): layers.append(block(self.in_channels, channels, norm=norm)) return M.Sequential(*layers) def forward(self, x): outputs = [] x = self.layer1(x) outputs.append(x) x = self.layer2(x) outputs.append(x) x = self.layer3(x) outputs.append(x) x = self.layer4(x) outputs.append(x) return outputs class SingleStage(M.Module): def __init__( self, block, init_channel, layers, channels, mid_channel, norm=M.BatchNorm2d ): super(SingleStage, self).__init__() self.down = ResnetBody(block, init_channel, layers, channels, norm) channel = block.expansion * channels[-1] self.up1 = M.Sequential( M.Conv2d(channel, mid_channel, 1, 1, 0), norm(mid_channel) ) self.deconv1 = M.Sequential(
M.ConvTranspose2d(mid_channel, mid_channel, 4, 2, 1)
megengine.module.ConvTranspose2d