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-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import os import platform import time import numpy as np import pytest from megengine.data.collator import Collator from megengine.data.dataloader import DataLoader from megengine.data.dataset import ArrayDataset, StreamDataset from megengine.data.sampler import RandomSampler, SequentialSampler, StreamSampler from megengine.data.transform import ( Compose, Normalize, PseudoTransform, ToMode, Transform, ) def init_dataset(): sample_num = 100 rand_data = np.random.randint(0, 255, size=(sample_num, 1, 32, 32), dtype=np.uint8) label = np.random.randint(0, 10, size=(sample_num,), dtype=int) dataset = ArrayDataset(rand_data, label) return dataset def test_dataloader_init(): dataset = init_dataset() with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=2, divide=True) with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=-1) with pytest.raises(ValueError): dataloader = DataLoader(dataset, timeout=-1) with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=0, divide=True) dataloader = DataLoader(dataset) assert isinstance(dataloader.sampler, SequentialSampler) assert isinstance(dataloader.transform, PseudoTransform) assert isinstance(dataloader.collator, Collator) dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=6, drop_last=False) ) assert len(dataloader) == 17 dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=6, drop_last=True) ) assert len(dataloader) == 16 class MyStream(StreamDataset): def __init__(self, number, batch=False, error_foramt=False, block=False): self.number = number self.batch = batch self.error_format = error_foramt self.block = block def __iter__(self): for cnt in range(self.number): if self.block: for _ in range(10): time.sleep(1) if self.batch: data = np.random.randint(0, 256, (2, 2, 2, 3), dtype="uint8") yield (True, (data, [cnt, cnt - self.number])) else: data = np.random.randint(0, 256, (2, 2, 3), dtype="uint8") if self.error_format: yield (data, cnt) else: yield (False, (data, cnt)) raise StopIteration @pytest.mark.parametrize("batch", [True, False]) @pytest.mark.parametrize("num_workers", [0, 2]) def test_stream_dataloader(batch, num_workers): dataset = MyStream(100, batch=batch) sampler = StreamSampler(batch_size=4) dataloader = DataLoader( dataset, sampler, Compose([
Normalize(mean=(103, 116, 123), std=(57, 57, 58))
megengine.data.transform.Normalize
# -*- coding: utf-8 -*- # 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. import os import platform import time import numpy as np import pytest from megengine.data.collator import Collator from megengine.data.dataloader import DataLoader from megengine.data.dataset import ArrayDataset, StreamDataset from megengine.data.sampler import RandomSampler, SequentialSampler, StreamSampler from megengine.data.transform import ( Compose, Normalize, PseudoTransform, ToMode, Transform, ) def init_dataset(): sample_num = 100 rand_data = np.random.randint(0, 255, size=(sample_num, 1, 32, 32), dtype=np.uint8) label = np.random.randint(0, 10, size=(sample_num,), dtype=int) dataset = ArrayDataset(rand_data, label) return dataset def test_dataloader_init(): dataset = init_dataset() with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=2, divide=True) with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=-1) with pytest.raises(ValueError): dataloader = DataLoader(dataset, timeout=-1) with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=0, divide=True) dataloader = DataLoader(dataset) assert isinstance(dataloader.sampler, SequentialSampler) assert isinstance(dataloader.transform, PseudoTransform) assert isinstance(dataloader.collator, Collator) dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=6, drop_last=False) ) assert len(dataloader) == 17 dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=6, drop_last=True) ) assert len(dataloader) == 16 class MyStream(StreamDataset): def __init__(self, number, batch=False, error_foramt=False, block=False): self.number = number self.batch = batch self.error_format = error_foramt self.block = block def __iter__(self): for cnt in range(self.number): if self.block: for _ in range(10): time.sleep(1) if self.batch: data = np.random.randint(0, 256, (2, 2, 2, 3), dtype="uint8") yield (True, (data, [cnt, cnt - self.number])) else: data = np.random.randint(0, 256, (2, 2, 3), dtype="uint8") if self.error_format: yield (data, cnt) else: yield (False, (data, cnt)) raise StopIteration @pytest.mark.parametrize("batch", [True, False]) @pytest.mark.parametrize("num_workers", [0, 2]) def test_stream_dataloader(batch, num_workers): dataset = MyStream(100, batch=batch) sampler = StreamSampler(batch_size=4) dataloader = DataLoader( dataset, sampler, Compose([Normalize(mean=(103, 116, 123), std=(57, 57, 58)),
ToMode("CHW")
megengine.data.transform.ToMode
# -*- coding: utf-8 -*- # 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. import os import platform import time import numpy as np import pytest from megengine.data.collator import Collator from megengine.data.dataloader import DataLoader from megengine.data.dataset import ArrayDataset, StreamDataset from megengine.data.sampler import RandomSampler, SequentialSampler, StreamSampler from megengine.data.transform import ( Compose, Normalize, PseudoTransform, ToMode, Transform, ) def init_dataset(): sample_num = 100 rand_data = np.random.randint(0, 255, size=(sample_num, 1, 32, 32), dtype=np.uint8) label = np.random.randint(0, 10, size=(sample_num,), dtype=int) dataset = ArrayDataset(rand_data, label) return dataset def test_dataloader_init(): dataset = init_dataset() with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=2, divide=True) with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=-1) with pytest.raises(ValueError): dataloader = DataLoader(dataset, timeout=-1) with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=0, divide=True) dataloader = DataLoader(dataset) assert isinstance(dataloader.sampler, SequentialSampler) assert isinstance(dataloader.transform, PseudoTransform) assert isinstance(dataloader.collator, Collator) dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=6, drop_last=False) ) assert len(dataloader) == 17 dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=6, drop_last=True) ) assert len(dataloader) == 16 class MyStream(StreamDataset): def __init__(self, number, batch=False, error_foramt=False, block=False): self.number = number self.batch = batch self.error_format = error_foramt self.block = block def __iter__(self): for cnt in range(self.number): if self.block: for _ in range(10): time.sleep(1) if self.batch: data = np.random.randint(0, 256, (2, 2, 2, 3), dtype="uint8") yield (True, (data, [cnt, cnt - self.number])) else: data = np.random.randint(0, 256, (2, 2, 3), dtype="uint8") if self.error_format: yield (data, cnt) else: yield (False, (data, cnt)) raise StopIteration @pytest.mark.parametrize("batch", [True, False]) @pytest.mark.parametrize("num_workers", [0, 2]) def test_stream_dataloader(batch, num_workers): dataset = MyStream(100, batch=batch) sampler = StreamSampler(batch_size=4) dataloader = DataLoader( dataset, sampler, Compose([Normalize(mean=(103, 116, 123), std=(57, 57, 58)), ToMode("CHW")]), num_workers=num_workers, ) check_set = set() for step, data in enumerate(dataloader): if step == 10: break assert data[0].shape == (4, 3, 2, 2) assert data[1].shape == (4,) for i in data[1]: assert i not in check_set check_set.add(i) def test_stream_dataloader_error(): dataset = MyStream(100, error_foramt=True) sampler = StreamSampler(batch_size=4) dataloader = DataLoader(dataset, sampler) with pytest.raises(AssertionError, match=r".*tuple.*"): data_iter = iter(dataloader) next(data_iter) @pytest.mark.parametrize("num_workers", [0, 2]) def test_stream_dataloader_timeout(num_workers): dataset = MyStream(100, False, block=True) sampler = StreamSampler(batch_size=4) dataloader = DataLoader(dataset, sampler, num_workers=num_workers, timeout=2) with pytest.raises(RuntimeError, match=r".*timeout.*"): data_iter = iter(dataloader) next(data_iter) def test_dataloader_serial(): dataset = init_dataset() dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False) ) for (data, label) in dataloader: assert data.shape == (4, 1, 32, 32) assert label.shape == (4,) def test_dataloader_parallel(): # set max shared memory to 100M os.environ["MGE_PLASMA_MEMORY"] = "100000000" dataset = init_dataset() dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), num_workers=2, divide=False, ) for (data, label) in dataloader: assert data.shape == (4, 1, 32, 32) assert label.shape == (4,) dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), num_workers=2, divide=True, ) for (data, label) in dataloader: assert data.shape == (4, 1, 32, 32) assert label.shape == (4,) @pytest.mark.skipif( platform.system() == "Windows", reason="dataloader do not support parallel on windows", ) def test_dataloader_parallel_timeout(): dataset = init_dataset() class TimeoutTransform(Transform): def __init__(self): pass def apply(self, input): time.sleep(10) return input dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), transform=TimeoutTransform(), num_workers=2, timeout=2, ) with pytest.raises(RuntimeError, match=r".*timeout.*"): data_iter = iter(dataloader) batch_data = next(data_iter) @pytest.mark.skipif( platform.system() == "Windows", reason="dataloader do not support parallel on windows", ) def test_dataloader_parallel_worker_exception(): dataset = init_dataset() class FakeErrorTransform(Transform): def __init__(self): pass def apply(self, input): raise RuntimeError("test raise error") return input dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), transform=FakeErrorTransform(), num_workers=2, ) with pytest.raises(RuntimeError, match=r"worker.*died"): data_iter = iter(dataloader) batch_data = next(data_iter) def _multi_instances_parallel_dataloader_worker(): dataset = init_dataset() for divide_flag in [True, False]: train_dataloader = DataLoader( dataset, sampler=
RandomSampler(dataset, batch_size=4, drop_last=False)
megengine.data.sampler.RandomSampler
# -*- coding: utf-8 -*- # 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. import os import platform import time import numpy as np import pytest from megengine.data.collator import Collator from megengine.data.dataloader import DataLoader from megengine.data.dataset import ArrayDataset, StreamDataset from megengine.data.sampler import RandomSampler, SequentialSampler, StreamSampler from megengine.data.transform import ( Compose, Normalize, PseudoTransform, ToMode, Transform, ) def init_dataset(): sample_num = 100 rand_data = np.random.randint(0, 255, size=(sample_num, 1, 32, 32), dtype=np.uint8) label = np.random.randint(0, 10, size=(sample_num,), dtype=int) dataset = ArrayDataset(rand_data, label) return dataset def test_dataloader_init(): dataset = init_dataset() with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=2, divide=True) with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=-1) with pytest.raises(ValueError): dataloader = DataLoader(dataset, timeout=-1) with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=0, divide=True) dataloader = DataLoader(dataset) assert isinstance(dataloader.sampler, SequentialSampler) assert isinstance(dataloader.transform, PseudoTransform) assert isinstance(dataloader.collator, Collator) dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=6, drop_last=False) ) assert len(dataloader) == 17 dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=6, drop_last=True) ) assert len(dataloader) == 16 class MyStream(StreamDataset): def __init__(self, number, batch=False, error_foramt=False, block=False): self.number = number self.batch = batch self.error_format = error_foramt self.block = block def __iter__(self): for cnt in range(self.number): if self.block: for _ in range(10): time.sleep(1) if self.batch: data = np.random.randint(0, 256, (2, 2, 2, 3), dtype="uint8") yield (True, (data, [cnt, cnt - self.number])) else: data = np.random.randint(0, 256, (2, 2, 3), dtype="uint8") if self.error_format: yield (data, cnt) else: yield (False, (data, cnt)) raise StopIteration @pytest.mark.parametrize("batch", [True, False]) @pytest.mark.parametrize("num_workers", [0, 2]) def test_stream_dataloader(batch, num_workers): dataset = MyStream(100, batch=batch) sampler = StreamSampler(batch_size=4) dataloader = DataLoader( dataset, sampler, Compose([Normalize(mean=(103, 116, 123), std=(57, 57, 58)), ToMode("CHW")]), num_workers=num_workers, ) check_set = set() for step, data in enumerate(dataloader): if step == 10: break assert data[0].shape == (4, 3, 2, 2) assert data[1].shape == (4,) for i in data[1]: assert i not in check_set check_set.add(i) def test_stream_dataloader_error(): dataset = MyStream(100, error_foramt=True) sampler = StreamSampler(batch_size=4) dataloader = DataLoader(dataset, sampler) with pytest.raises(AssertionError, match=r".*tuple.*"): data_iter = iter(dataloader) next(data_iter) @pytest.mark.parametrize("num_workers", [0, 2]) def test_stream_dataloader_timeout(num_workers): dataset = MyStream(100, False, block=True) sampler = StreamSampler(batch_size=4) dataloader = DataLoader(dataset, sampler, num_workers=num_workers, timeout=2) with pytest.raises(RuntimeError, match=r".*timeout.*"): data_iter = iter(dataloader) next(data_iter) def test_dataloader_serial(): dataset = init_dataset() dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False) ) for (data, label) in dataloader: assert data.shape == (4, 1, 32, 32) assert label.shape == (4,) def test_dataloader_parallel(): # set max shared memory to 100M os.environ["MGE_PLASMA_MEMORY"] = "100000000" dataset = init_dataset() dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), num_workers=2, divide=False, ) for (data, label) in dataloader: assert data.shape == (4, 1, 32, 32) assert label.shape == (4,) dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), num_workers=2, divide=True, ) for (data, label) in dataloader: assert data.shape == (4, 1, 32, 32) assert label.shape == (4,) @pytest.mark.skipif( platform.system() == "Windows", reason="dataloader do not support parallel on windows", ) def test_dataloader_parallel_timeout(): dataset = init_dataset() class TimeoutTransform(Transform): def __init__(self): pass def apply(self, input): time.sleep(10) return input dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), transform=TimeoutTransform(), num_workers=2, timeout=2, ) with pytest.raises(RuntimeError, match=r".*timeout.*"): data_iter = iter(dataloader) batch_data = next(data_iter) @pytest.mark.skipif( platform.system() == "Windows", reason="dataloader do not support parallel on windows", ) def test_dataloader_parallel_worker_exception(): dataset = init_dataset() class FakeErrorTransform(Transform): def __init__(self): pass def apply(self, input): raise RuntimeError("test raise error") return input dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), transform=FakeErrorTransform(), num_workers=2, ) with pytest.raises(RuntimeError, match=r"worker.*died"): data_iter = iter(dataloader) batch_data = next(data_iter) def _multi_instances_parallel_dataloader_worker(): dataset = init_dataset() for divide_flag in [True, False]: train_dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), num_workers=2, divide=divide_flag, ) val_dataloader = DataLoader( dataset, sampler=
RandomSampler(dataset, batch_size=10, drop_last=False)
megengine.data.sampler.RandomSampler
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype =
dtype.qint8(scale)
megengine.core.tensor.dtype.qint8
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x =
F.round(x)
megengine.functional.round
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x =
F.clip(x, -128, 127)
megengine.functional.clip
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net =
Float.QuantStub()
megengine.module.QuantStub
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float =
QAT.QuantStub.from_float_module(normal_net)
megengine.module.qat.QuantStub.from_float_module
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval()
disable_observer(qat_from_float)
megengine.quantization.quantize.disable_observer
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float)
disable_fake_quant(qat_from_float)
megengine.quantization.quantize.disable_fake_quant
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net =
QAT.QuantStub()
megengine.module.qat.QuantStub
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval()
disable_observer(qat_net)
megengine.quantization.quantize.disable_observer
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net)
propagate_qconfig(qat_net, min_max_fakequant_qconfig)
megengine.quantization.quantize.propagate_qconfig
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net =
Q.QuantStub.from_qat_module(qat_net)
megengine.module.quantized.QuantStub.from_qat_module
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net =
Float.DequantStub()
megengine.module.DequantStub
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float =
QAT.DequantStub.from_float_module(normal_net)
megengine.module.qat.DequantStub.from_float_module
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval()
disable_fake_quant(qat_from_float)
megengine.quantization.quantize.disable_fake_quant
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float)
disable_observer(qat_from_float)
megengine.quantization.quantize.disable_observer
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net =
QAT.DequantStub()
megengine.module.qat.DequantStub
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval()
disable_observer(qat_net)
megengine.quantization.quantize.disable_observer
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net)
propagate_qconfig(qat_net, min_max_fakequant_qconfig)
megengine.quantization.quantize.propagate_qconfig
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net =
Q.DequantStub.from_qat_module(qat_net)
megengine.module.quantized.DequantStub.from_qat_module
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net =
Float.Elemwise(kind)
megengine.module.Elemwise
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float =
QAT.Elemwise.from_float_module(normal_net)
megengine.module.qat.Elemwise.from_float_module
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval()
disable_observer(qat_from_float)
megengine.quantization.quantize.disable_observer
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float)
disable_fake_quant(qat_from_float)
megengine.quantization.quantize.disable_fake_quant
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net =
QAT.Elemwise(kind)
megengine.module.qat.Elemwise
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval()
disable_observer(qat_net)
megengine.quantization.quantize.disable_observer
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net)
propagate_qconfig(qat_net, min_max_fakequant_qconfig)
megengine.quantization.quantize.propagate_qconfig
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net =
Q.Elemwise.from_qat_module(qat_net)
megengine.module.quantized.Elemwise.from_qat_module
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.Elemwise.from_qat_module(qat_net) q_net.eval() x1_scale = np.float32(np.random.rand() + 1) x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x1 = fake_quant(x1, x1_scale) x1.q_dict["scale"] = x1_scale x2_scale = np.float32(np.random.rand() + 1) x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x2 = fake_quant(x2, x2_scale) x2.q_dict["scale"] = x2_scale x1_int8 = quant(x1, x1_scale) x2_int8 = quant(x2, x2_scale) # test correctness of `Float`, `QAT` and `Quantized` if kind in ("ADD", "MUL", "FUSE_ADD_RELU"): normal = normal_net(x1, x2) qat_without_fakequant = qat_from_float(x1, x2) fake_quant_normal = fake_quant(normal_net(x1, x2), act_scale) qat = qat_net(x1, x2) q = q_net(x1_int8, x2_int8).numpy() * act_scale else: normal = normal_net(x1) qat_without_fakequant = qat_from_float(x1) fake_quant_normal = fake_quant(normal_net(x1), act_scale) qat = qat_net(x1) q = q_net(x1_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_linear(): normal_net =
Float.Linear(3, 3, bias=True)
megengine.module.Linear
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.Elemwise.from_qat_module(qat_net) q_net.eval() x1_scale = np.float32(np.random.rand() + 1) x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x1 = fake_quant(x1, x1_scale) x1.q_dict["scale"] = x1_scale x2_scale = np.float32(np.random.rand() + 1) x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x2 = fake_quant(x2, x2_scale) x2.q_dict["scale"] = x2_scale x1_int8 = quant(x1, x1_scale) x2_int8 = quant(x2, x2_scale) # test correctness of `Float`, `QAT` and `Quantized` if kind in ("ADD", "MUL", "FUSE_ADD_RELU"): normal = normal_net(x1, x2) qat_without_fakequant = qat_from_float(x1, x2) fake_quant_normal = fake_quant(normal_net(x1, x2), act_scale) qat = qat_net(x1, x2) q = q_net(x1_int8, x2_int8).numpy() * act_scale else: normal = normal_net(x1) qat_without_fakequant = qat_from_float(x1) fake_quant_normal = fake_quant(normal_net(x1), act_scale) qat = qat_net(x1) q = q_net(x1_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_linear(): normal_net = Float.Linear(3, 3, bias=True) normal_net.eval() qat_net =
QAT.Linear(3, 3, bias=True)
megengine.module.qat.Linear
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.Elemwise.from_qat_module(qat_net) q_net.eval() x1_scale = np.float32(np.random.rand() + 1) x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x1 = fake_quant(x1, x1_scale) x1.q_dict["scale"] = x1_scale x2_scale = np.float32(np.random.rand() + 1) x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x2 = fake_quant(x2, x2_scale) x2.q_dict["scale"] = x2_scale x1_int8 = quant(x1, x1_scale) x2_int8 = quant(x2, x2_scale) # test correctness of `Float`, `QAT` and `Quantized` if kind in ("ADD", "MUL", "FUSE_ADD_RELU"): normal = normal_net(x1, x2) qat_without_fakequant = qat_from_float(x1, x2) fake_quant_normal = fake_quant(normal_net(x1, x2), act_scale) qat = qat_net(x1, x2) q = q_net(x1_int8, x2_int8).numpy() * act_scale else: normal = normal_net(x1) qat_without_fakequant = qat_from_float(x1) fake_quant_normal = fake_quant(normal_net(x1), act_scale) qat = qat_net(x1) q = q_net(x1_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_linear(): normal_net = Float.Linear(3, 3, bias=True) normal_net.eval() qat_net = QAT.Linear(3, 3, bias=True) qat_net.eval()
disable_observer(qat_net)
megengine.quantization.quantize.disable_observer
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.Elemwise.from_qat_module(qat_net) q_net.eval() x1_scale = np.float32(np.random.rand() + 1) x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x1 = fake_quant(x1, x1_scale) x1.q_dict["scale"] = x1_scale x2_scale = np.float32(np.random.rand() + 1) x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x2 = fake_quant(x2, x2_scale) x2.q_dict["scale"] = x2_scale x1_int8 = quant(x1, x1_scale) x2_int8 = quant(x2, x2_scale) # test correctness of `Float`, `QAT` and `Quantized` if kind in ("ADD", "MUL", "FUSE_ADD_RELU"): normal = normal_net(x1, x2) qat_without_fakequant = qat_from_float(x1, x2) fake_quant_normal = fake_quant(normal_net(x1, x2), act_scale) qat = qat_net(x1, x2) q = q_net(x1_int8, x2_int8).numpy() * act_scale else: normal = normal_net(x1) qat_without_fakequant = qat_from_float(x1) fake_quant_normal = fake_quant(normal_net(x1), act_scale) qat = qat_net(x1) q = q_net(x1_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_linear(): normal_net = Float.Linear(3, 3, bias=True) normal_net.eval() qat_net = QAT.Linear(3, 3, bias=True) qat_net.eval() disable_observer(qat_net)
propagate_qconfig(qat_net, min_max_fakequant_qconfig)
megengine.quantization.quantize.propagate_qconfig
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.Elemwise.from_qat_module(qat_net) q_net.eval() x1_scale = np.float32(np.random.rand() + 1) x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x1 = fake_quant(x1, x1_scale) x1.q_dict["scale"] = x1_scale x2_scale = np.float32(np.random.rand() + 1) x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x2 = fake_quant(x2, x2_scale) x2.q_dict["scale"] = x2_scale x1_int8 = quant(x1, x1_scale) x2_int8 = quant(x2, x2_scale) # test correctness of `Float`, `QAT` and `Quantized` if kind in ("ADD", "MUL", "FUSE_ADD_RELU"): normal = normal_net(x1, x2) qat_without_fakequant = qat_from_float(x1, x2) fake_quant_normal = fake_quant(normal_net(x1, x2), act_scale) qat = qat_net(x1, x2) q = q_net(x1_int8, x2_int8).numpy() * act_scale else: normal = normal_net(x1) qat_without_fakequant = qat_from_float(x1) fake_quant_normal = fake_quant(normal_net(x1), act_scale) qat = qat_net(x1) q = q_net(x1_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_linear(): normal_net = Float.Linear(3, 3, bias=True) normal_net.eval() qat_net = QAT.Linear(3, 3, bias=True) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale x_int8 = quant(x, inp_scale) weight = np.random.normal(size=(3, 3)).astype("float32") bias = np.random.normal(size=(3,)).astype("float32") normal_net.weight.set_value(fake_quant(weight, weight_scale)) normal_net.bias.set_value(fake_quant(bias, inp_scale * weight_scale)) qat_net.weight.set_value(weight) qat_net.bias.set_value(bias) qat_from_float =
QAT.Linear.from_float_module(normal_net)
megengine.module.qat.Linear.from_float_module
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.Elemwise.from_qat_module(qat_net) q_net.eval() x1_scale = np.float32(np.random.rand() + 1) x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x1 = fake_quant(x1, x1_scale) x1.q_dict["scale"] = x1_scale x2_scale = np.float32(np.random.rand() + 1) x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x2 = fake_quant(x2, x2_scale) x2.q_dict["scale"] = x2_scale x1_int8 = quant(x1, x1_scale) x2_int8 = quant(x2, x2_scale) # test correctness of `Float`, `QAT` and `Quantized` if kind in ("ADD", "MUL", "FUSE_ADD_RELU"): normal = normal_net(x1, x2) qat_without_fakequant = qat_from_float(x1, x2) fake_quant_normal = fake_quant(normal_net(x1, x2), act_scale) qat = qat_net(x1, x2) q = q_net(x1_int8, x2_int8).numpy() * act_scale else: normal = normal_net(x1) qat_without_fakequant = qat_from_float(x1) fake_quant_normal = fake_quant(normal_net(x1), act_scale) qat = qat_net(x1) q = q_net(x1_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_linear(): normal_net = Float.Linear(3, 3, bias=True) normal_net.eval() qat_net = QAT.Linear(3, 3, bias=True) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale x_int8 = quant(x, inp_scale) weight = np.random.normal(size=(3, 3)).astype("float32") bias = np.random.normal(size=(3,)).astype("float32") normal_net.weight.set_value(fake_quant(weight, weight_scale)) normal_net.bias.set_value(fake_quant(bias, inp_scale * weight_scale)) qat_net.weight.set_value(weight) qat_net.bias.set_value(bias) qat_from_float = QAT.Linear.from_float_module(normal_net) qat_from_float.eval()
disable_fake_quant(qat_from_float)
megengine.quantization.quantize.disable_fake_quant
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.Elemwise.from_qat_module(qat_net) q_net.eval() x1_scale = np.float32(np.random.rand() + 1) x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x1 = fake_quant(x1, x1_scale) x1.q_dict["scale"] = x1_scale x2_scale = np.float32(np.random.rand() + 1) x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x2 = fake_quant(x2, x2_scale) x2.q_dict["scale"] = x2_scale x1_int8 = quant(x1, x1_scale) x2_int8 = quant(x2, x2_scale) # test correctness of `Float`, `QAT` and `Quantized` if kind in ("ADD", "MUL", "FUSE_ADD_RELU"): normal = normal_net(x1, x2) qat_without_fakequant = qat_from_float(x1, x2) fake_quant_normal = fake_quant(normal_net(x1, x2), act_scale) qat = qat_net(x1, x2) q = q_net(x1_int8, x2_int8).numpy() * act_scale else: normal = normal_net(x1) qat_without_fakequant = qat_from_float(x1) fake_quant_normal = fake_quant(normal_net(x1), act_scale) qat = qat_net(x1) q = q_net(x1_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_linear(): normal_net = Float.Linear(3, 3, bias=True) normal_net.eval() qat_net = QAT.Linear(3, 3, bias=True) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale x_int8 = quant(x, inp_scale) weight = np.random.normal(size=(3, 3)).astype("float32") bias = np.random.normal(size=(3,)).astype("float32") normal_net.weight.set_value(fake_quant(weight, weight_scale)) normal_net.bias.set_value(fake_quant(bias, inp_scale * weight_scale)) qat_net.weight.set_value(weight) qat_net.bias.set_value(bias) qat_from_float = QAT.Linear.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float)
disable_observer(qat_from_float)
megengine.quantization.quantize.disable_observer
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.Elemwise.from_qat_module(qat_net) q_net.eval() x1_scale = np.float32(np.random.rand() + 1) x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x1 = fake_quant(x1, x1_scale) x1.q_dict["scale"] = x1_scale x2_scale = np.float32(np.random.rand() + 1) x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x2 = fake_quant(x2, x2_scale) x2.q_dict["scale"] = x2_scale x1_int8 = quant(x1, x1_scale) x2_int8 = quant(x2, x2_scale) # test correctness of `Float`, `QAT` and `Quantized` if kind in ("ADD", "MUL", "FUSE_ADD_RELU"): normal = normal_net(x1, x2) qat_without_fakequant = qat_from_float(x1, x2) fake_quant_normal = fake_quant(normal_net(x1, x2), act_scale) qat = qat_net(x1, x2) q = q_net(x1_int8, x2_int8).numpy() * act_scale else: normal = normal_net(x1) qat_without_fakequant = qat_from_float(x1) fake_quant_normal = fake_quant(normal_net(x1), act_scale) qat = qat_net(x1) q = q_net(x1_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_linear(): normal_net = Float.Linear(3, 3, bias=True) normal_net.eval() qat_net = QAT.Linear(3, 3, bias=True) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale x_int8 = quant(x, inp_scale) weight = np.random.normal(size=(3, 3)).astype("float32") bias = np.random.normal(size=(3,)).astype("float32") normal_net.weight.set_value(fake_quant(weight, weight_scale)) normal_net.bias.set_value(fake_quant(bias, inp_scale * weight_scale)) qat_net.weight.set_value(weight) qat_net.bias.set_value(bias) qat_from_float = QAT.Linear.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) q_net =
Q.Linear.from_qat_module(qat_net)
megengine.module.quantized.Linear.from_qat_module
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.Elemwise.from_qat_module(qat_net) q_net.eval() x1_scale = np.float32(np.random.rand() + 1) x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x1 = fake_quant(x1, x1_scale) x1.q_dict["scale"] = x1_scale x2_scale = np.float32(np.random.rand() + 1) x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x2 = fake_quant(x2, x2_scale) x2.q_dict["scale"] = x2_scale x1_int8 = quant(x1, x1_scale) x2_int8 = quant(x2, x2_scale) # test correctness of `Float`, `QAT` and `Quantized` if kind in ("ADD", "MUL", "FUSE_ADD_RELU"): normal = normal_net(x1, x2) qat_without_fakequant = qat_from_float(x1, x2) fake_quant_normal = fake_quant(normal_net(x1, x2), act_scale) qat = qat_net(x1, x2) q = q_net(x1_int8, x2_int8).numpy() * act_scale else: normal = normal_net(x1) qat_without_fakequant = qat_from_float(x1) fake_quant_normal = fake_quant(normal_net(x1), act_scale) qat = qat_net(x1) q = q_net(x1_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_linear(): normal_net = Float.Linear(3, 3, bias=True) normal_net.eval() qat_net = QAT.Linear(3, 3, bias=True) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale x_int8 = quant(x, inp_scale) weight = np.random.normal(size=(3, 3)).astype("float32") bias = np.random.normal(size=(3,)).astype("float32") normal_net.weight.set_value(fake_quant(weight, weight_scale)) normal_net.bias.set_value(fake_quant(bias, inp_scale * weight_scale)) qat_net.weight.set_value(weight) qat_net.bias.set_value(bias) qat_from_float = QAT.Linear.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) q_net = Q.Linear.from_qat_module(qat_net) q_net.eval() normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("module", ["Conv2d", "ConvBn2d", "ConvBnRelu2d"]) def test_conv(module): normal_net = getattr(Float, module)(3, 3, 3, 1, 1, 1, bias=True) normal_net.eval() qat_net = getattr(QAT, module)(3, 3, 3, 1, 1, 1, bias=True) qat_net.eval()
disable_observer(qat_net)
megengine.quantization.quantize.disable_observer
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.Elemwise.from_qat_module(qat_net) q_net.eval() x1_scale = np.float32(np.random.rand() + 1) x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x1 = fake_quant(x1, x1_scale) x1.q_dict["scale"] = x1_scale x2_scale = np.float32(np.random.rand() + 1) x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x2 = fake_quant(x2, x2_scale) x2.q_dict["scale"] = x2_scale x1_int8 = quant(x1, x1_scale) x2_int8 = quant(x2, x2_scale) # test correctness of `Float`, `QAT` and `Quantized` if kind in ("ADD", "MUL", "FUSE_ADD_RELU"): normal = normal_net(x1, x2) qat_without_fakequant = qat_from_float(x1, x2) fake_quant_normal = fake_quant(normal_net(x1, x2), act_scale) qat = qat_net(x1, x2) q = q_net(x1_int8, x2_int8).numpy() * act_scale else: normal = normal_net(x1) qat_without_fakequant = qat_from_float(x1) fake_quant_normal = fake_quant(normal_net(x1), act_scale) qat = qat_net(x1) q = q_net(x1_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_linear(): normal_net = Float.Linear(3, 3, bias=True) normal_net.eval() qat_net = QAT.Linear(3, 3, bias=True) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale x_int8 = quant(x, inp_scale) weight = np.random.normal(size=(3, 3)).astype("float32") bias = np.random.normal(size=(3,)).astype("float32") normal_net.weight.set_value(fake_quant(weight, weight_scale)) normal_net.bias.set_value(fake_quant(bias, inp_scale * weight_scale)) qat_net.weight.set_value(weight) qat_net.bias.set_value(bias) qat_from_float = QAT.Linear.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) q_net = Q.Linear.from_qat_module(qat_net) q_net.eval() normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("module", ["Conv2d", "ConvBn2d", "ConvBnRelu2d"]) def test_conv(module): normal_net = getattr(Float, module)(3, 3, 3, 1, 1, 1, bias=True) normal_net.eval() qat_net = getattr(QAT, module)(3, 3, 3, 1, 1, 1, bias=True) qat_net.eval() disable_observer(qat_net)
propagate_qconfig(qat_net, min_max_fakequant_qconfig)
megengine.quantization.quantize.propagate_qconfig
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.Elemwise.from_qat_module(qat_net) q_net.eval() x1_scale = np.float32(np.random.rand() + 1) x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x1 = fake_quant(x1, x1_scale) x1.q_dict["scale"] = x1_scale x2_scale = np.float32(np.random.rand() + 1) x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x2 = fake_quant(x2, x2_scale) x2.q_dict["scale"] = x2_scale x1_int8 = quant(x1, x1_scale) x2_int8 = quant(x2, x2_scale) # test correctness of `Float`, `QAT` and `Quantized` if kind in ("ADD", "MUL", "FUSE_ADD_RELU"): normal = normal_net(x1, x2) qat_without_fakequant = qat_from_float(x1, x2) fake_quant_normal = fake_quant(normal_net(x1, x2), act_scale) qat = qat_net(x1, x2) q = q_net(x1_int8, x2_int8).numpy() * act_scale else: normal = normal_net(x1) qat_without_fakequant = qat_from_float(x1) fake_quant_normal = fake_quant(normal_net(x1), act_scale) qat = qat_net(x1) q = q_net(x1_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_linear(): normal_net = Float.Linear(3, 3, bias=True) normal_net.eval() qat_net = QAT.Linear(3, 3, bias=True) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale x_int8 = quant(x, inp_scale) weight = np.random.normal(size=(3, 3)).astype("float32") bias = np.random.normal(size=(3,)).astype("float32") normal_net.weight.set_value(fake_quant(weight, weight_scale)) normal_net.bias.set_value(fake_quant(bias, inp_scale * weight_scale)) qat_net.weight.set_value(weight) qat_net.bias.set_value(bias) qat_from_float = QAT.Linear.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) q_net = Q.Linear.from_qat_module(qat_net) q_net.eval() normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("module", ["Conv2d", "ConvBn2d", "ConvBnRelu2d"]) def test_conv(module): normal_net = getattr(Float, module)(3, 3, 3, 1, 1, 1, bias=True) normal_net.eval() qat_net = getattr(QAT, module)(3, 3, 3, 1, 1, 1, bias=True) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) x = mge.tensor(np.random.normal(size=(1, 3, 3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale x_int8 = quant(x, inp_scale) weight = np.random.normal(size=(3, 3, 3, 3)).astype("float32") bias = np.random.normal(size=(1, 3, 1, 1)).astype("float32") if module in ("ConvBn2d", "ConvBnRelu2d"): normal_net.conv.weight.set_value(fake_quant(weight, weight_scale)) normal_net.conv.bias.set_value(fake_quant(bias, inp_scale * weight_scale)) qat_net.conv.weight.set_value(weight) qat_net.conv.bias.set_value(bias) else: normal_net.weight.set_value(fake_quant(weight, weight_scale)) normal_net.bias.set_value(fake_quant(bias, inp_scale * weight_scale)) qat_net.weight.set_value(weight) qat_net.bias.set_value(bias) qat_from_float = getattr(QAT, module).from_float_module(normal_net) qat_from_float.eval()
disable_observer(qat_from_float)
megengine.quantization.quantize.disable_observer
import numpy as np import pytest import megengine as mge import megengine.functional as F import megengine.module as Float import megengine.module.qat as QAT import megengine.module.quantized as Q from megengine.core.tensor import dtype from megengine.quantization import min_max_fakequant_qconfig from megengine.quantization.quantize import ( disable_fake_quant, disable_observer, propagate_qconfig, ) """ Calculate testing scales based on ``min_max_fakequant_qconfig`` """ inp_scale = np.float32(np.random.rand() + 1) min_val = np.random.randint(-127, 0, size=(2,)).astype("float32") max_val = np.random.randint(1, 127, size=(2,)).astype("float32") weight_scale = np.float32(np.max([-min_val[0], max_val[0]]) / 254 * 2) act_scale = np.float32(np.max([-min_val[1], max_val[1]]) / 255 * 2) def quant(x, scale): inp_dtype = dtype.qint8(scale) return x.astype(inp_dtype) def fake_quant(x, scale): x = x / scale x = F.round(x) x = F.clip(x, -128, 127) x = x * scale return x def init_qat_net(net): if net.with_weight: net.weight_observer.min_val.set_value(min_val[0]) net.weight_observer.max_val.set_value(max_val[0]) if net.with_act: net.act_observer.min_val.set_value(min_val[1]) net.act_observer.max_val.set_value(max_val[1]) def test_quant_stub(): normal_net = Float.QuantStub() normal_net.eval() qat_from_float = QAT.QuantStub.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.QuantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.QuantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_dequant_stub(): normal_net = Float.DequantStub() normal_net.eval() qat_from_float = QAT.DequantStub.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) qat_net = QAT.DequantStub() qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.DequantStub.from_qat_module(qat_net) q_net.eval() x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = normal_net(x) qat = qat_net(x) q = q_net(quant(x, inp_scale)).numpy() np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("kind", ["COS", "RELU", "ADD", "MUL", "FUSE_ADD_RELU"]) def test_elemwise(kind): normal_net = Float.Elemwise(kind) normal_net.eval() qat_from_float = QAT.Elemwise.from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float) disable_fake_quant(qat_from_float) qat_net = QAT.Elemwise(kind) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) q_net = Q.Elemwise.from_qat_module(qat_net) q_net.eval() x1_scale = np.float32(np.random.rand() + 1) x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x1 = fake_quant(x1, x1_scale) x1.q_dict["scale"] = x1_scale x2_scale = np.float32(np.random.rand() + 1) x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x2 = fake_quant(x2, x2_scale) x2.q_dict["scale"] = x2_scale x1_int8 = quant(x1, x1_scale) x2_int8 = quant(x2, x2_scale) # test correctness of `Float`, `QAT` and `Quantized` if kind in ("ADD", "MUL", "FUSE_ADD_RELU"): normal = normal_net(x1, x2) qat_without_fakequant = qat_from_float(x1, x2) fake_quant_normal = fake_quant(normal_net(x1, x2), act_scale) qat = qat_net(x1, x2) q = q_net(x1_int8, x2_int8).numpy() * act_scale else: normal = normal_net(x1) qat_without_fakequant = qat_from_float(x1) fake_quant_normal = fake_quant(normal_net(x1), act_scale) qat = qat_net(x1) q = q_net(x1_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) def test_linear(): normal_net = Float.Linear(3, 3, bias=True) normal_net.eval() qat_net = QAT.Linear(3, 3, bias=True) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) x = mge.tensor(np.random.normal(size=(3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale x_int8 = quant(x, inp_scale) weight = np.random.normal(size=(3, 3)).astype("float32") bias = np.random.normal(size=(3,)).astype("float32") normal_net.weight.set_value(fake_quant(weight, weight_scale)) normal_net.bias.set_value(fake_quant(bias, inp_scale * weight_scale)) qat_net.weight.set_value(weight) qat_net.bias.set_value(bias) qat_from_float = QAT.Linear.from_float_module(normal_net) qat_from_float.eval() disable_fake_quant(qat_from_float) disable_observer(qat_from_float) q_net = Q.Linear.from_qat_module(qat_net) q_net.eval() normal = normal_net(x) qat_without_fakequant = qat_from_float(x) fake_quant_normal = fake_quant(normal_net(x), act_scale) qat = qat_net(x) q = q_net(x_int8).numpy() * act_scale np.testing.assert_allclose(qat_without_fakequant, normal) np.testing.assert_allclose(qat, fake_quant_normal) np.testing.assert_allclose(q, fake_quant_normal.numpy()) @pytest.mark.parametrize("module", ["Conv2d", "ConvBn2d", "ConvBnRelu2d"]) def test_conv(module): normal_net = getattr(Float, module)(3, 3, 3, 1, 1, 1, bias=True) normal_net.eval() qat_net = getattr(QAT, module)(3, 3, 3, 1, 1, 1, bias=True) qat_net.eval() disable_observer(qat_net) propagate_qconfig(qat_net, min_max_fakequant_qconfig) init_qat_net(qat_net) x = mge.tensor(np.random.normal(size=(1, 3, 3, 3)).astype("float32")) x = fake_quant(x, inp_scale) x.q_dict["scale"] = inp_scale x_int8 = quant(x, inp_scale) weight = np.random.normal(size=(3, 3, 3, 3)).astype("float32") bias = np.random.normal(size=(1, 3, 1, 1)).astype("float32") if module in ("ConvBn2d", "ConvBnRelu2d"): normal_net.conv.weight.set_value(fake_quant(weight, weight_scale)) normal_net.conv.bias.set_value(fake_quant(bias, inp_scale * weight_scale)) qat_net.conv.weight.set_value(weight) qat_net.conv.bias.set_value(bias) else: normal_net.weight.set_value(fake_quant(weight, weight_scale)) normal_net.bias.set_value(fake_quant(bias, inp_scale * weight_scale)) qat_net.weight.set_value(weight) qat_net.bias.set_value(bias) qat_from_float = getattr(QAT, module).from_float_module(normal_net) qat_from_float.eval() disable_observer(qat_from_float)
disable_fake_quant(qat_from_float)
megengine.quantization.quantize.disable_fake_quant
# Copyright (c) Megvii, Inc. and its affiliates. """do the evaluation work with single gpu """ import argparse import os import megengine as mge import megengine.data as data import megengine.data.transform as T import megengine.functional as F import numpy as np from tqdm.auto import tqdm from recognition.datasets import get_eval_dataset from recognition.models import FaceRecognitionModel from recognition.tools.utils import load_config_from_path logger =
mge.get_logger(__name__)
megengine.get_logger
# Copyright (c) Megvii, Inc. and its affiliates. """do the evaluation work with single gpu """ import argparse import os import megengine as mge import megengine.data as data import megengine.data.transform as T import megengine.functional as F import numpy as np from tqdm.auto import tqdm from recognition.datasets import get_eval_dataset from recognition.models import FaceRecognitionModel from recognition.tools.utils import load_config_from_path logger = mge.get_logger(__name__) def get_inference_func(configs): """load checkpoint and construct inference function Args: configs (dict): configuration, required fields include: base_dir: base directory of experiment outputs evaluate_epoch: model of evaluate_epoch to evaluate Raises: FileNotFoundError: model of given epoch is not found Returns: inference_func (function): inference function mapping image to embedding """ model = FaceRecognitionModel(configs) evaluate_epoch = configs["evaluate_epoch"] checkpoint_path = os.path.join(configs["base_dir"], f"epoch-{evaluate_epoch}-checkpoint.pkl") if os.path.exists(checkpoint_path): checkpoint_data = mge.load(checkpoint_path) model.load_state_dict(checkpoint_data["state_dict"], strict=False) else: raise FileNotFoundError(f"{checkpoint_path} not found!!!") def inference_func(images): model.eval() # classic test-time mirror augment embedding_origin = model.forward_embedding_only(images) embedding_mirror = model.forward_embedding_only(images[:, :, :, ::-1]) embedding = embedding_origin + embedding_mirror embedding = F.normalize(embedding, axis=1) return embedding return inference_func def extract_feature_and_clean_noise(configs, inference_func): """extract feature and clean noise. the noise cleaning algorithm is proposed in `"ArcFace: Additive Angular Margin Loss for Deep Face Recognition" <https://arxiv.org/pdf/1801.07698.pdf>`_ please refer to https://github.com/deepinsight/insightface/blob/master/Evaluation/Megaface/remove_noises.py for more detail. this implement does basicly the same thing as the above, but with much higher speed Args: configs (dict): configuration, required fields include: batch_size: inference batch size feature_dim: model output feature dimension base_dir: base directory of experiment outputs dataset_dir: directory of dataset root inference_func (function): constructed inference function Returns: facescrub_feature (np.array): noise-cleaned feature of facescrub (shape: n * (feature_dim + 1)) facescrub_label (np.array): label of facescrub (shape: n) megaface_feature (np.array): noise-cleaned feature of megaface (shape: m * (feature_dim + 1)) """ def prepare_dataset(name): """prepare dataset Args: name (str): name of the dataset, should be one of {facescrub, megaface} Returns: dataset (data.Dataset): required dataset queue (data.DataLoader): corresponding dataloader """ preprocess = T.Compose([T.Normalize(mean=127.5, std=128), T.ToMode("CHW")]) dataset = get_eval_dataset(name, dataset_dir=configs["dataset_dir"]) sampler = data.SequentialSampler(dataset, batch_size=configs["batch_size"]) queue = data.DataLoader(dataset, sampler=sampler, transform=preprocess) return dataset, queue def extract_vanilla_feature(n, data_queue): """extract features without any postprocessing Args: n (int): size of dataset data_queue (data.DataLoader): dataloader to extract feature Returns: feature_store (np.array): extracted feature (shape: n * feature_dim) label (np.array): label of this instance, -1 if unknown (shape: n) is_noise (np.array): whether this instance is a noise (shape: n) """ feature_store = np.zeros((n, configs["feature_dim"]), dtype="float32") label_store = np.zeros(n, dtype="int32") is_noise_store = np.zeros(n, dtype="bool") for images, indice, labels, is_noise in tqdm(data_queue): images = mge.tensor(images, dtype="float32") embedding = inference_func(images) embedding = embedding.numpy() feature_store[indice] = embedding label_store[indice] = labels is_noise_store[indice] = is_noise return feature_store, label_store, is_noise_store # prepare facescrub dataset logger.info("preparing facescrub dataset...") facescrub_dataset, facescrub_queue = prepare_dataset("facescrub") # extract facescrub feature logger.info("extracting facescrub...") facescrub_feature_store, facescrub_label, facescrub_is_noise = extract_vanilla_feature( n=len(facescrub_dataset), data_queue=facescrub_queue ) # prepare megaface dataset logger.info("preparing megaface dataset...") megaface_dataset, megaface_queue = prepare_dataset("megaface") # extract feature for megaface logger.info("extracting megaface...") megaface_feature_store, _, megaface_is_noise = extract_vanilla_feature( n=len(megaface_dataset), data_queue=megaface_queue ) # parse facescrub noise, replace noisy feature with class center of same person facescrub_feature_center = np.zeros((facescrub_dataset.num_class, configs["feature_dim"]), dtype="float32") for i in range(facescrub_dataset.num_class): mask = (facescrub_label == i) & (~facescrub_is_noise) center = facescrub_feature_store[mask].sum(axis=0) center = center / np.linalg.norm(center) facescrub_feature_center[i] = center for index in np.where(facescrub_is_noise)[0]: center = facescrub_feature_center[facescrub_label[index]] disturb = np.random.uniform(-1e-5, 1e-5, (configs["feature_dim"],)) feat = center + disturb # avoid identical features with minor disturb feat = feat / np.linalg.norm(feat) facescrub_feature_store[index] = feat # extend feature by 1 dimension # the extended feature is infinitly large (100) if and only if megaface noise, 0 otherwise # so, the distance between probe and a noisy distractor is infinitly large, while other distances remain unchanged facescrub_feature_extend = np.zeros((len(facescrub_dataset), 1), dtype="float32") facescrub_feature = np.concatenate([facescrub_feature_store, facescrub_feature_extend], axis=1) megaface_feature_extend = megaface_is_noise.astype("float32").reshape(-1, 1) * 100 megaface_feature = np.concatenate([megaface_feature_store, megaface_feature_extend], axis=1) # write to file system facescrub_feature_path = os.path.join(configs["base_dir"], "facescrub.npy") np.save(facescrub_feature_path, facescrub_feature) facescrub_label_path = os.path.join(configs["base_dir"], "facescrub_label.npy") np.save(facescrub_label_path, facescrub_label) megaface_feature_path = os.path.join(configs["base_dir"], "megaface.npy") np.save(megaface_feature_path, megaface_feature) return facescrub_feature, facescrub_label, megaface_feature def calculate_score(configs, facescrub, labels, megaface): """calculate megaface identification top1 score. this evaluation implement strictly follows the description of `"The MegaFace Benchmark: 1 Million Faces for Recognition at Scale" <https://arxiv.org/pdf/1512.00596.pdf>`_ this implement outputs exactly the same as dev-sdk provided by the official, but with much higher speed Args: configs (dict): configuration facescrub (np.array): feature of facescrub labels (np.array): label of facescrub megaface (np.array): feature of megaface Returns: megaface_score (float): top1 score of megaface """ facescrub =
mge.tensor(facescrub, dtype="float32")
megengine.tensor
# Copyright (c) Megvii, Inc. and its affiliates. """do the evaluation work with single gpu """ import argparse import os import megengine as mge import megengine.data as data import megengine.data.transform as T import megengine.functional as F import numpy as np from tqdm.auto import tqdm from recognition.datasets import get_eval_dataset from recognition.models import FaceRecognitionModel from recognition.tools.utils import load_config_from_path logger = mge.get_logger(__name__) def get_inference_func(configs): """load checkpoint and construct inference function Args: configs (dict): configuration, required fields include: base_dir: base directory of experiment outputs evaluate_epoch: model of evaluate_epoch to evaluate Raises: FileNotFoundError: model of given epoch is not found Returns: inference_func (function): inference function mapping image to embedding """ model = FaceRecognitionModel(configs) evaluate_epoch = configs["evaluate_epoch"] checkpoint_path = os.path.join(configs["base_dir"], f"epoch-{evaluate_epoch}-checkpoint.pkl") if os.path.exists(checkpoint_path): checkpoint_data = mge.load(checkpoint_path) model.load_state_dict(checkpoint_data["state_dict"], strict=False) else: raise FileNotFoundError(f"{checkpoint_path} not found!!!") def inference_func(images): model.eval() # classic test-time mirror augment embedding_origin = model.forward_embedding_only(images) embedding_mirror = model.forward_embedding_only(images[:, :, :, ::-1]) embedding = embedding_origin + embedding_mirror embedding = F.normalize(embedding, axis=1) return embedding return inference_func def extract_feature_and_clean_noise(configs, inference_func): """extract feature and clean noise. the noise cleaning algorithm is proposed in `"ArcFace: Additive Angular Margin Loss for Deep Face Recognition" <https://arxiv.org/pdf/1801.07698.pdf>`_ please refer to https://github.com/deepinsight/insightface/blob/master/Evaluation/Megaface/remove_noises.py for more detail. this implement does basicly the same thing as the above, but with much higher speed Args: configs (dict): configuration, required fields include: batch_size: inference batch size feature_dim: model output feature dimension base_dir: base directory of experiment outputs dataset_dir: directory of dataset root inference_func (function): constructed inference function Returns: facescrub_feature (np.array): noise-cleaned feature of facescrub (shape: n * (feature_dim + 1)) facescrub_label (np.array): label of facescrub (shape: n) megaface_feature (np.array): noise-cleaned feature of megaface (shape: m * (feature_dim + 1)) """ def prepare_dataset(name): """prepare dataset Args: name (str): name of the dataset, should be one of {facescrub, megaface} Returns: dataset (data.Dataset): required dataset queue (data.DataLoader): corresponding dataloader """ preprocess = T.Compose([T.Normalize(mean=127.5, std=128), T.ToMode("CHW")]) dataset = get_eval_dataset(name, dataset_dir=configs["dataset_dir"]) sampler = data.SequentialSampler(dataset, batch_size=configs["batch_size"]) queue = data.DataLoader(dataset, sampler=sampler, transform=preprocess) return dataset, queue def extract_vanilla_feature(n, data_queue): """extract features without any postprocessing Args: n (int): size of dataset data_queue (data.DataLoader): dataloader to extract feature Returns: feature_store (np.array): extracted feature (shape: n * feature_dim) label (np.array): label of this instance, -1 if unknown (shape: n) is_noise (np.array): whether this instance is a noise (shape: n) """ feature_store = np.zeros((n, configs["feature_dim"]), dtype="float32") label_store = np.zeros(n, dtype="int32") is_noise_store = np.zeros(n, dtype="bool") for images, indice, labels, is_noise in tqdm(data_queue): images = mge.tensor(images, dtype="float32") embedding = inference_func(images) embedding = embedding.numpy() feature_store[indice] = embedding label_store[indice] = labels is_noise_store[indice] = is_noise return feature_store, label_store, is_noise_store # prepare facescrub dataset logger.info("preparing facescrub dataset...") facescrub_dataset, facescrub_queue = prepare_dataset("facescrub") # extract facescrub feature logger.info("extracting facescrub...") facescrub_feature_store, facescrub_label, facescrub_is_noise = extract_vanilla_feature( n=len(facescrub_dataset), data_queue=facescrub_queue ) # prepare megaface dataset logger.info("preparing megaface dataset...") megaface_dataset, megaface_queue = prepare_dataset("megaface") # extract feature for megaface logger.info("extracting megaface...") megaface_feature_store, _, megaface_is_noise = extract_vanilla_feature( n=len(megaface_dataset), data_queue=megaface_queue ) # parse facescrub noise, replace noisy feature with class center of same person facescrub_feature_center = np.zeros((facescrub_dataset.num_class, configs["feature_dim"]), dtype="float32") for i in range(facescrub_dataset.num_class): mask = (facescrub_label == i) & (~facescrub_is_noise) center = facescrub_feature_store[mask].sum(axis=0) center = center / np.linalg.norm(center) facescrub_feature_center[i] = center for index in np.where(facescrub_is_noise)[0]: center = facescrub_feature_center[facescrub_label[index]] disturb = np.random.uniform(-1e-5, 1e-5, (configs["feature_dim"],)) feat = center + disturb # avoid identical features with minor disturb feat = feat / np.linalg.norm(feat) facescrub_feature_store[index] = feat # extend feature by 1 dimension # the extended feature is infinitly large (100) if and only if megaface noise, 0 otherwise # so, the distance between probe and a noisy distractor is infinitly large, while other distances remain unchanged facescrub_feature_extend = np.zeros((len(facescrub_dataset), 1), dtype="float32") facescrub_feature = np.concatenate([facescrub_feature_store, facescrub_feature_extend], axis=1) megaface_feature_extend = megaface_is_noise.astype("float32").reshape(-1, 1) * 100 megaface_feature = np.concatenate([megaface_feature_store, megaface_feature_extend], axis=1) # write to file system facescrub_feature_path = os.path.join(configs["base_dir"], "facescrub.npy") np.save(facescrub_feature_path, facescrub_feature) facescrub_label_path = os.path.join(configs["base_dir"], "facescrub_label.npy") np.save(facescrub_label_path, facescrub_label) megaface_feature_path = os.path.join(configs["base_dir"], "megaface.npy") np.save(megaface_feature_path, megaface_feature) return facescrub_feature, facescrub_label, megaface_feature def calculate_score(configs, facescrub, labels, megaface): """calculate megaface identification top1 score. this evaluation implement strictly follows the description of `"The MegaFace Benchmark: 1 Million Faces for Recognition at Scale" <https://arxiv.org/pdf/1512.00596.pdf>`_ this implement outputs exactly the same as dev-sdk provided by the official, but with much higher speed Args: configs (dict): configuration facescrub (np.array): feature of facescrub labels (np.array): label of facescrub megaface (np.array): feature of megaface Returns: megaface_score (float): top1 score of megaface """ facescrub = mge.tensor(facescrub, dtype="float32") megaface =
mge.tensor(megaface, dtype="float32")
megengine.tensor
# Copyright (c) Megvii, Inc. and its affiliates. """do the evaluation work with single gpu """ import argparse import os import megengine as mge import megengine.data as data import megengine.data.transform as T import megengine.functional as F import numpy as np from tqdm.auto import tqdm from recognition.datasets import get_eval_dataset from recognition.models import FaceRecognitionModel from recognition.tools.utils import load_config_from_path logger = mge.get_logger(__name__) def get_inference_func(configs): """load checkpoint and construct inference function Args: configs (dict): configuration, required fields include: base_dir: base directory of experiment outputs evaluate_epoch: model of evaluate_epoch to evaluate Raises: FileNotFoundError: model of given epoch is not found Returns: inference_func (function): inference function mapping image to embedding """ model = FaceRecognitionModel(configs) evaluate_epoch = configs["evaluate_epoch"] checkpoint_path = os.path.join(configs["base_dir"], f"epoch-{evaluate_epoch}-checkpoint.pkl") if os.path.exists(checkpoint_path): checkpoint_data = mge.load(checkpoint_path) model.load_state_dict(checkpoint_data["state_dict"], strict=False) else: raise FileNotFoundError(f"{checkpoint_path} not found!!!") def inference_func(images): model.eval() # classic test-time mirror augment embedding_origin = model.forward_embedding_only(images) embedding_mirror = model.forward_embedding_only(images[:, :, :, ::-1]) embedding = embedding_origin + embedding_mirror embedding = F.normalize(embedding, axis=1) return embedding return inference_func def extract_feature_and_clean_noise(configs, inference_func): """extract feature and clean noise. the noise cleaning algorithm is proposed in `"ArcFace: Additive Angular Margin Loss for Deep Face Recognition" <https://arxiv.org/pdf/1801.07698.pdf>`_ please refer to https://github.com/deepinsight/insightface/blob/master/Evaluation/Megaface/remove_noises.py for more detail. this implement does basicly the same thing as the above, but with much higher speed Args: configs (dict): configuration, required fields include: batch_size: inference batch size feature_dim: model output feature dimension base_dir: base directory of experiment outputs dataset_dir: directory of dataset root inference_func (function): constructed inference function Returns: facescrub_feature (np.array): noise-cleaned feature of facescrub (shape: n * (feature_dim + 1)) facescrub_label (np.array): label of facescrub (shape: n) megaface_feature (np.array): noise-cleaned feature of megaface (shape: m * (feature_dim + 1)) """ def prepare_dataset(name): """prepare dataset Args: name (str): name of the dataset, should be one of {facescrub, megaface} Returns: dataset (data.Dataset): required dataset queue (data.DataLoader): corresponding dataloader """ preprocess = T.Compose([T.Normalize(mean=127.5, std=128), T.ToMode("CHW")]) dataset = get_eval_dataset(name, dataset_dir=configs["dataset_dir"]) sampler = data.SequentialSampler(dataset, batch_size=configs["batch_size"]) queue = data.DataLoader(dataset, sampler=sampler, transform=preprocess) return dataset, queue def extract_vanilla_feature(n, data_queue): """extract features without any postprocessing Args: n (int): size of dataset data_queue (data.DataLoader): dataloader to extract feature Returns: feature_store (np.array): extracted feature (shape: n * feature_dim) label (np.array): label of this instance, -1 if unknown (shape: n) is_noise (np.array): whether this instance is a noise (shape: n) """ feature_store = np.zeros((n, configs["feature_dim"]), dtype="float32") label_store = np.zeros(n, dtype="int32") is_noise_store = np.zeros(n, dtype="bool") for images, indice, labels, is_noise in tqdm(data_queue): images = mge.tensor(images, dtype="float32") embedding = inference_func(images) embedding = embedding.numpy() feature_store[indice] = embedding label_store[indice] = labels is_noise_store[indice] = is_noise return feature_store, label_store, is_noise_store # prepare facescrub dataset logger.info("preparing facescrub dataset...") facescrub_dataset, facescrub_queue = prepare_dataset("facescrub") # extract facescrub feature logger.info("extracting facescrub...") facescrub_feature_store, facescrub_label, facescrub_is_noise = extract_vanilla_feature( n=len(facescrub_dataset), data_queue=facescrub_queue ) # prepare megaface dataset logger.info("preparing megaface dataset...") megaface_dataset, megaface_queue = prepare_dataset("megaface") # extract feature for megaface logger.info("extracting megaface...") megaface_feature_store, _, megaface_is_noise = extract_vanilla_feature( n=len(megaface_dataset), data_queue=megaface_queue ) # parse facescrub noise, replace noisy feature with class center of same person facescrub_feature_center = np.zeros((facescrub_dataset.num_class, configs["feature_dim"]), dtype="float32") for i in range(facescrub_dataset.num_class): mask = (facescrub_label == i) & (~facescrub_is_noise) center = facescrub_feature_store[mask].sum(axis=0) center = center / np.linalg.norm(center) facescrub_feature_center[i] = center for index in np.where(facescrub_is_noise)[0]: center = facescrub_feature_center[facescrub_label[index]] disturb = np.random.uniform(-1e-5, 1e-5, (configs["feature_dim"],)) feat = center + disturb # avoid identical features with minor disturb feat = feat / np.linalg.norm(feat) facescrub_feature_store[index] = feat # extend feature by 1 dimension # the extended feature is infinitly large (100) if and only if megaface noise, 0 otherwise # so, the distance between probe and a noisy distractor is infinitly large, while other distances remain unchanged facescrub_feature_extend = np.zeros((len(facescrub_dataset), 1), dtype="float32") facescrub_feature = np.concatenate([facescrub_feature_store, facescrub_feature_extend], axis=1) megaface_feature_extend = megaface_is_noise.astype("float32").reshape(-1, 1) * 100 megaface_feature = np.concatenate([megaface_feature_store, megaface_feature_extend], axis=1) # write to file system facescrub_feature_path = os.path.join(configs["base_dir"], "facescrub.npy") np.save(facescrub_feature_path, facescrub_feature) facescrub_label_path = os.path.join(configs["base_dir"], "facescrub_label.npy") np.save(facescrub_label_path, facescrub_label) megaface_feature_path = os.path.join(configs["base_dir"], "megaface.npy") np.save(megaface_feature_path, megaface_feature) return facescrub_feature, facescrub_label, megaface_feature def calculate_score(configs, facescrub, labels, megaface): """calculate megaface identification top1 score. this evaluation implement strictly follows the description of `"The MegaFace Benchmark: 1 Million Faces for Recognition at Scale" <https://arxiv.org/pdf/1512.00596.pdf>`_ this implement outputs exactly the same as dev-sdk provided by the official, but with much higher speed Args: configs (dict): configuration facescrub (np.array): feature of facescrub labels (np.array): label of facescrub megaface (np.array): feature of megaface Returns: megaface_score (float): top1 score of megaface """ facescrub = mge.tensor(facescrub, dtype="float32") megaface = mge.tensor(megaface, dtype="float32") # note: (x - y) ** 2 = x ** 2 + y ** 2 - 2 * x * y # facescrub_score[i][j] = l2-dist(facescrub[i], facescrub[j]) facescrub_score = ( (facescrub ** 2).sum(axis=-1, keepdims=True) + (facescrub ** 2).sum(axis=-1, keepdims=True).transpose(1, 0) - 2 * F.matmul(facescrub, facescrub.transpose(1, 0)) ) facescrub_score = facescrub_score.numpy() def get_score_min_megaface(x): distr_score = (x ** 2).sum(axis=-1) + (megaface ** 2).sum(axis=-1) - 2 * (x * megaface).sum(axis=-1) return distr_score.min() up, down = 0, 0 for probe_i in tqdm(range(len(facescrub))): distr_score_min = get_score_min_megaface(facescrub[probe_i]).numpy() mask = (labels == labels[probe_i]) & (np.arange(len(facescrub)) != probe_i) for probe_j in np.where(mask)[0]: probe_score = facescrub_score[probe_i][probe_j] up += probe_score < distr_score_min down += 1 megaface_score = up / down * 100 return megaface_score def main(args): configs = load_config_from_path(args.config_file) configs["evaluate_epoch"] = args.epoch if args.epoch is not None else configs["num_epoch"] # write log to worklog.txt os.makedirs(configs["base_dir"], exist_ok=True) worklog_path = os.path.join(configs["base_dir"], "worklog.txt")
mge.set_log_file(worklog_path)
megengine.set_log_file
# Copyright (c) Megvii, Inc. and its affiliates. """do the evaluation work with single gpu """ import argparse import os import megengine as mge import megengine.data as data import megengine.data.transform as T import megengine.functional as F import numpy as np from tqdm.auto import tqdm from recognition.datasets import get_eval_dataset from recognition.models import FaceRecognitionModel from recognition.tools.utils import load_config_from_path logger = mge.get_logger(__name__) def get_inference_func(configs): """load checkpoint and construct inference function Args: configs (dict): configuration, required fields include: base_dir: base directory of experiment outputs evaluate_epoch: model of evaluate_epoch to evaluate Raises: FileNotFoundError: model of given epoch is not found Returns: inference_func (function): inference function mapping image to embedding """ model = FaceRecognitionModel(configs) evaluate_epoch = configs["evaluate_epoch"] checkpoint_path = os.path.join(configs["base_dir"], f"epoch-{evaluate_epoch}-checkpoint.pkl") if os.path.exists(checkpoint_path): checkpoint_data =
mge.load(checkpoint_path)
megengine.load
# Copyright (c) Megvii, Inc. and its affiliates. """do the evaluation work with single gpu """ import argparse import os import megengine as mge import megengine.data as data import megengine.data.transform as T import megengine.functional as F import numpy as np from tqdm.auto import tqdm from recognition.datasets import get_eval_dataset from recognition.models import FaceRecognitionModel from recognition.tools.utils import load_config_from_path logger = mge.get_logger(__name__) def get_inference_func(configs): """load checkpoint and construct inference function Args: configs (dict): configuration, required fields include: base_dir: base directory of experiment outputs evaluate_epoch: model of evaluate_epoch to evaluate Raises: FileNotFoundError: model of given epoch is not found Returns: inference_func (function): inference function mapping image to embedding """ model = FaceRecognitionModel(configs) evaluate_epoch = configs["evaluate_epoch"] checkpoint_path = os.path.join(configs["base_dir"], f"epoch-{evaluate_epoch}-checkpoint.pkl") if os.path.exists(checkpoint_path): checkpoint_data = mge.load(checkpoint_path) model.load_state_dict(checkpoint_data["state_dict"], strict=False) else: raise FileNotFoundError(f"{checkpoint_path} not found!!!") def inference_func(images): model.eval() # classic test-time mirror augment embedding_origin = model.forward_embedding_only(images) embedding_mirror = model.forward_embedding_only(images[:, :, :, ::-1]) embedding = embedding_origin + embedding_mirror embedding =
F.normalize(embedding, axis=1)
megengine.functional.normalize
# Copyright (c) Megvii, Inc. and its affiliates. """do the evaluation work with single gpu """ import argparse import os import megengine as mge import megengine.data as data import megengine.data.transform as T import megengine.functional as F import numpy as np from tqdm.auto import tqdm from recognition.datasets import get_eval_dataset from recognition.models import FaceRecognitionModel from recognition.tools.utils import load_config_from_path logger = mge.get_logger(__name__) def get_inference_func(configs): """load checkpoint and construct inference function Args: configs (dict): configuration, required fields include: base_dir: base directory of experiment outputs evaluate_epoch: model of evaluate_epoch to evaluate Raises: FileNotFoundError: model of given epoch is not found Returns: inference_func (function): inference function mapping image to embedding """ model = FaceRecognitionModel(configs) evaluate_epoch = configs["evaluate_epoch"] checkpoint_path = os.path.join(configs["base_dir"], f"epoch-{evaluate_epoch}-checkpoint.pkl") if os.path.exists(checkpoint_path): checkpoint_data = mge.load(checkpoint_path) model.load_state_dict(checkpoint_data["state_dict"], strict=False) else: raise FileNotFoundError(f"{checkpoint_path} not found!!!") def inference_func(images): model.eval() # classic test-time mirror augment embedding_origin = model.forward_embedding_only(images) embedding_mirror = model.forward_embedding_only(images[:, :, :, ::-1]) embedding = embedding_origin + embedding_mirror embedding = F.normalize(embedding, axis=1) return embedding return inference_func def extract_feature_and_clean_noise(configs, inference_func): """extract feature and clean noise. the noise cleaning algorithm is proposed in `"ArcFace: Additive Angular Margin Loss for Deep Face Recognition" <https://arxiv.org/pdf/1801.07698.pdf>`_ please refer to https://github.com/deepinsight/insightface/blob/master/Evaluation/Megaface/remove_noises.py for more detail. this implement does basicly the same thing as the above, but with much higher speed Args: configs (dict): configuration, required fields include: batch_size: inference batch size feature_dim: model output feature dimension base_dir: base directory of experiment outputs dataset_dir: directory of dataset root inference_func (function): constructed inference function Returns: facescrub_feature (np.array): noise-cleaned feature of facescrub (shape: n * (feature_dim + 1)) facescrub_label (np.array): label of facescrub (shape: n) megaface_feature (np.array): noise-cleaned feature of megaface (shape: m * (feature_dim + 1)) """ def prepare_dataset(name): """prepare dataset Args: name (str): name of the dataset, should be one of {facescrub, megaface} Returns: dataset (data.Dataset): required dataset queue (data.DataLoader): corresponding dataloader """ preprocess = T.Compose([T.Normalize(mean=127.5, std=128), T.ToMode("CHW")]) dataset = get_eval_dataset(name, dataset_dir=configs["dataset_dir"]) sampler =
data.SequentialSampler(dataset, batch_size=configs["batch_size"])
megengine.data.SequentialSampler
# Copyright (c) Megvii, Inc. and its affiliates. """do the evaluation work with single gpu """ import argparse import os import megengine as mge import megengine.data as data import megengine.data.transform as T import megengine.functional as F import numpy as np from tqdm.auto import tqdm from recognition.datasets import get_eval_dataset from recognition.models import FaceRecognitionModel from recognition.tools.utils import load_config_from_path logger = mge.get_logger(__name__) def get_inference_func(configs): """load checkpoint and construct inference function Args: configs (dict): configuration, required fields include: base_dir: base directory of experiment outputs evaluate_epoch: model of evaluate_epoch to evaluate Raises: FileNotFoundError: model of given epoch is not found Returns: inference_func (function): inference function mapping image to embedding """ model = FaceRecognitionModel(configs) evaluate_epoch = configs["evaluate_epoch"] checkpoint_path = os.path.join(configs["base_dir"], f"epoch-{evaluate_epoch}-checkpoint.pkl") if os.path.exists(checkpoint_path): checkpoint_data = mge.load(checkpoint_path) model.load_state_dict(checkpoint_data["state_dict"], strict=False) else: raise FileNotFoundError(f"{checkpoint_path} not found!!!") def inference_func(images): model.eval() # classic test-time mirror augment embedding_origin = model.forward_embedding_only(images) embedding_mirror = model.forward_embedding_only(images[:, :, :, ::-1]) embedding = embedding_origin + embedding_mirror embedding = F.normalize(embedding, axis=1) return embedding return inference_func def extract_feature_and_clean_noise(configs, inference_func): """extract feature and clean noise. the noise cleaning algorithm is proposed in `"ArcFace: Additive Angular Margin Loss for Deep Face Recognition" <https://arxiv.org/pdf/1801.07698.pdf>`_ please refer to https://github.com/deepinsight/insightface/blob/master/Evaluation/Megaface/remove_noises.py for more detail. this implement does basicly the same thing as the above, but with much higher speed Args: configs (dict): configuration, required fields include: batch_size: inference batch size feature_dim: model output feature dimension base_dir: base directory of experiment outputs dataset_dir: directory of dataset root inference_func (function): constructed inference function Returns: facescrub_feature (np.array): noise-cleaned feature of facescrub (shape: n * (feature_dim + 1)) facescrub_label (np.array): label of facescrub (shape: n) megaface_feature (np.array): noise-cleaned feature of megaface (shape: m * (feature_dim + 1)) """ def prepare_dataset(name): """prepare dataset Args: name (str): name of the dataset, should be one of {facescrub, megaface} Returns: dataset (data.Dataset): required dataset queue (data.DataLoader): corresponding dataloader """ preprocess = T.Compose([T.Normalize(mean=127.5, std=128), T.ToMode("CHW")]) dataset = get_eval_dataset(name, dataset_dir=configs["dataset_dir"]) sampler = data.SequentialSampler(dataset, batch_size=configs["batch_size"]) queue =
data.DataLoader(dataset, sampler=sampler, transform=preprocess)
megengine.data.DataLoader
# Copyright (c) Megvii, Inc. and its affiliates. """do the evaluation work with single gpu """ import argparse import os import megengine as mge import megengine.data as data import megengine.data.transform as T import megengine.functional as F import numpy as np from tqdm.auto import tqdm from recognition.datasets import get_eval_dataset from recognition.models import FaceRecognitionModel from recognition.tools.utils import load_config_from_path logger = mge.get_logger(__name__) def get_inference_func(configs): """load checkpoint and construct inference function Args: configs (dict): configuration, required fields include: base_dir: base directory of experiment outputs evaluate_epoch: model of evaluate_epoch to evaluate Raises: FileNotFoundError: model of given epoch is not found Returns: inference_func (function): inference function mapping image to embedding """ model = FaceRecognitionModel(configs) evaluate_epoch = configs["evaluate_epoch"] checkpoint_path = os.path.join(configs["base_dir"], f"epoch-{evaluate_epoch}-checkpoint.pkl") if os.path.exists(checkpoint_path): checkpoint_data = mge.load(checkpoint_path) model.load_state_dict(checkpoint_data["state_dict"], strict=False) else: raise FileNotFoundError(f"{checkpoint_path} not found!!!") def inference_func(images): model.eval() # classic test-time mirror augment embedding_origin = model.forward_embedding_only(images) embedding_mirror = model.forward_embedding_only(images[:, :, :, ::-1]) embedding = embedding_origin + embedding_mirror embedding = F.normalize(embedding, axis=1) return embedding return inference_func def extract_feature_and_clean_noise(configs, inference_func): """extract feature and clean noise. the noise cleaning algorithm is proposed in `"ArcFace: Additive Angular Margin Loss for Deep Face Recognition" <https://arxiv.org/pdf/1801.07698.pdf>`_ please refer to https://github.com/deepinsight/insightface/blob/master/Evaluation/Megaface/remove_noises.py for more detail. this implement does basicly the same thing as the above, but with much higher speed Args: configs (dict): configuration, required fields include: batch_size: inference batch size feature_dim: model output feature dimension base_dir: base directory of experiment outputs dataset_dir: directory of dataset root inference_func (function): constructed inference function Returns: facescrub_feature (np.array): noise-cleaned feature of facescrub (shape: n * (feature_dim + 1)) facescrub_label (np.array): label of facescrub (shape: n) megaface_feature (np.array): noise-cleaned feature of megaface (shape: m * (feature_dim + 1)) """ def prepare_dataset(name): """prepare dataset Args: name (str): name of the dataset, should be one of {facescrub, megaface} Returns: dataset (data.Dataset): required dataset queue (data.DataLoader): corresponding dataloader """ preprocess = T.Compose([T.Normalize(mean=127.5, std=128), T.ToMode("CHW")]) dataset = get_eval_dataset(name, dataset_dir=configs["dataset_dir"]) sampler = data.SequentialSampler(dataset, batch_size=configs["batch_size"]) queue = data.DataLoader(dataset, sampler=sampler, transform=preprocess) return dataset, queue def extract_vanilla_feature(n, data_queue): """extract features without any postprocessing Args: n (int): size of dataset data_queue (data.DataLoader): dataloader to extract feature Returns: feature_store (np.array): extracted feature (shape: n * feature_dim) label (np.array): label of this instance, -1 if unknown (shape: n) is_noise (np.array): whether this instance is a noise (shape: n) """ feature_store = np.zeros((n, configs["feature_dim"]), dtype="float32") label_store = np.zeros(n, dtype="int32") is_noise_store = np.zeros(n, dtype="bool") for images, indice, labels, is_noise in tqdm(data_queue): images =
mge.tensor(images, dtype="float32")
megengine.tensor
# Copyright (c) Megvii, Inc. and its affiliates. """do the evaluation work with single gpu """ import argparse import os import megengine as mge import megengine.data as data import megengine.data.transform as T import megengine.functional as F import numpy as np from tqdm.auto import tqdm from recognition.datasets import get_eval_dataset from recognition.models import FaceRecognitionModel from recognition.tools.utils import load_config_from_path logger = mge.get_logger(__name__) def get_inference_func(configs): """load checkpoint and construct inference function Args: configs (dict): configuration, required fields include: base_dir: base directory of experiment outputs evaluate_epoch: model of evaluate_epoch to evaluate Raises: FileNotFoundError: model of given epoch is not found Returns: inference_func (function): inference function mapping image to embedding """ model = FaceRecognitionModel(configs) evaluate_epoch = configs["evaluate_epoch"] checkpoint_path = os.path.join(configs["base_dir"], f"epoch-{evaluate_epoch}-checkpoint.pkl") if os.path.exists(checkpoint_path): checkpoint_data = mge.load(checkpoint_path) model.load_state_dict(checkpoint_data["state_dict"], strict=False) else: raise FileNotFoundError(f"{checkpoint_path} not found!!!") def inference_func(images): model.eval() # classic test-time mirror augment embedding_origin = model.forward_embedding_only(images) embedding_mirror = model.forward_embedding_only(images[:, :, :, ::-1]) embedding = embedding_origin + embedding_mirror embedding = F.normalize(embedding, axis=1) return embedding return inference_func def extract_feature_and_clean_noise(configs, inference_func): """extract feature and clean noise. the noise cleaning algorithm is proposed in `"ArcFace: Additive Angular Margin Loss for Deep Face Recognition" <https://arxiv.org/pdf/1801.07698.pdf>`_ please refer to https://github.com/deepinsight/insightface/blob/master/Evaluation/Megaface/remove_noises.py for more detail. this implement does basicly the same thing as the above, but with much higher speed Args: configs (dict): configuration, required fields include: batch_size: inference batch size feature_dim: model output feature dimension base_dir: base directory of experiment outputs dataset_dir: directory of dataset root inference_func (function): constructed inference function Returns: facescrub_feature (np.array): noise-cleaned feature of facescrub (shape: n * (feature_dim + 1)) facescrub_label (np.array): label of facescrub (shape: n) megaface_feature (np.array): noise-cleaned feature of megaface (shape: m * (feature_dim + 1)) """ def prepare_dataset(name): """prepare dataset Args: name (str): name of the dataset, should be one of {facescrub, megaface} Returns: dataset (data.Dataset): required dataset queue (data.DataLoader): corresponding dataloader """ preprocess = T.Compose([
T.Normalize(mean=127.5, std=128)
megengine.data.transform.Normalize
# Copyright (c) Megvii, Inc. and its affiliates. """do the evaluation work with single gpu """ import argparse import os import megengine as mge import megengine.data as data import megengine.data.transform as T import megengine.functional as F import numpy as np from tqdm.auto import tqdm from recognition.datasets import get_eval_dataset from recognition.models import FaceRecognitionModel from recognition.tools.utils import load_config_from_path logger = mge.get_logger(__name__) def get_inference_func(configs): """load checkpoint and construct inference function Args: configs (dict): configuration, required fields include: base_dir: base directory of experiment outputs evaluate_epoch: model of evaluate_epoch to evaluate Raises: FileNotFoundError: model of given epoch is not found Returns: inference_func (function): inference function mapping image to embedding """ model = FaceRecognitionModel(configs) evaluate_epoch = configs["evaluate_epoch"] checkpoint_path = os.path.join(configs["base_dir"], f"epoch-{evaluate_epoch}-checkpoint.pkl") if os.path.exists(checkpoint_path): checkpoint_data = mge.load(checkpoint_path) model.load_state_dict(checkpoint_data["state_dict"], strict=False) else: raise FileNotFoundError(f"{checkpoint_path} not found!!!") def inference_func(images): model.eval() # classic test-time mirror augment embedding_origin = model.forward_embedding_only(images) embedding_mirror = model.forward_embedding_only(images[:, :, :, ::-1]) embedding = embedding_origin + embedding_mirror embedding = F.normalize(embedding, axis=1) return embedding return inference_func def extract_feature_and_clean_noise(configs, inference_func): """extract feature and clean noise. the noise cleaning algorithm is proposed in `"ArcFace: Additive Angular Margin Loss for Deep Face Recognition" <https://arxiv.org/pdf/1801.07698.pdf>`_ please refer to https://github.com/deepinsight/insightface/blob/master/Evaluation/Megaface/remove_noises.py for more detail. this implement does basicly the same thing as the above, but with much higher speed Args: configs (dict): configuration, required fields include: batch_size: inference batch size feature_dim: model output feature dimension base_dir: base directory of experiment outputs dataset_dir: directory of dataset root inference_func (function): constructed inference function Returns: facescrub_feature (np.array): noise-cleaned feature of facescrub (shape: n * (feature_dim + 1)) facescrub_label (np.array): label of facescrub (shape: n) megaface_feature (np.array): noise-cleaned feature of megaface (shape: m * (feature_dim + 1)) """ def prepare_dataset(name): """prepare dataset Args: name (str): name of the dataset, should be one of {facescrub, megaface} Returns: dataset (data.Dataset): required dataset queue (data.DataLoader): corresponding dataloader """ preprocess = T.Compose([T.Normalize(mean=127.5, std=128),
T.ToMode("CHW")
megengine.data.transform.ToMode
# -*- coding: utf-8 -*- # 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. import argparse import numpy as np import yaml from megengine import jit from megengine.module.external import ExternOprSubgraph # "1,3,224,224" -> (1,3,224,224) def str2tuple(x): x = x.split(",") x = [int(a) for a in x] x = tuple(x) return x def main(): parser = argparse.ArgumentParser( description="load a .pb model and convert to corresponding " "load-and-run model" ) parser.add_argument("input", help="mace model file") parser.add_argument("param", help="mace param file") parser.add_argument( "output", help="converted model that can be fed to dump_with_testcase_mge.py" ) parser.add_argument("config", help="config file with yaml format") args = parser.parse_args() with open(args.config, "r") as f: configs = yaml.load(f) for model_name in configs["models"]: # ignore several sub models currently sub_model = configs["models"][model_name]["subgraphs"][0] # input/output shapes isizes = [str2tuple(x) for x in sub_model["input_shapes"]] # input/output names input_names = sub_model["input_tensors"] if "check_tensors" in sub_model: output_names = sub_model["check_tensors"] osizes = [str2tuple(x) for x in sub_model["check_shapes"]] else: output_names = sub_model["output_tensors"] osizes = [str2tuple(x) for x in sub_model["output_shapes"]] with open(args.input, "rb") as fin: raw_model = fin.read() with open(args.param, "rb") as fin: raw_param = fin.read() model_size = (len(raw_model)).to_bytes(4, byteorder="little") param_size = (len(raw_param)).to_bytes(4, byteorder="little") n_inputs = (len(input_names)).to_bytes(4, byteorder="little") n_outputs = (len(output_names)).to_bytes(4, byteorder="little") names_buffer = n_inputs + n_outputs for iname in input_names: names_buffer += (len(iname)).to_bytes(4, byteorder="little") names_buffer += str.encode(iname) for oname in output_names: names_buffer += (len(oname)).to_bytes(4, byteorder="little") names_buffer += str.encode(oname) shapes_buffer = n_outputs for oshape in osizes: shapes_buffer += (len(oshape)).to_bytes(4, byteorder="little") for oi in oshape: shapes_buffer += oi.to_bytes(4, byteorder="little") # raw content contains: # input/output names + output shapes + model buffer + param buffer wk_raw_content = ( names_buffer + shapes_buffer + model_size + raw_model + param_size + raw_param ) net =
ExternOprSubgraph(wk_raw_content, "mace", osizes)
megengine.module.external.ExternOprSubgraph
# -*- coding: utf-8 -*- # 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. import argparse import numpy as np import yaml from megengine import jit from megengine.module.external import ExternOprSubgraph # "1,3,224,224" -> (1,3,224,224) def str2tuple(x): x = x.split(",") x = [int(a) for a in x] x = tuple(x) return x def main(): parser = argparse.ArgumentParser( description="load a .pb model and convert to corresponding " "load-and-run model" ) parser.add_argument("input", help="mace model file") parser.add_argument("param", help="mace param file") parser.add_argument( "output", help="converted model that can be fed to dump_with_testcase_mge.py" ) parser.add_argument("config", help="config file with yaml format") args = parser.parse_args() with open(args.config, "r") as f: configs = yaml.load(f) for model_name in configs["models"]: # ignore several sub models currently sub_model = configs["models"][model_name]["subgraphs"][0] # input/output shapes isizes = [str2tuple(x) for x in sub_model["input_shapes"]] # input/output names input_names = sub_model["input_tensors"] if "check_tensors" in sub_model: output_names = sub_model["check_tensors"] osizes = [str2tuple(x) for x in sub_model["check_shapes"]] else: output_names = sub_model["output_tensors"] osizes = [str2tuple(x) for x in sub_model["output_shapes"]] with open(args.input, "rb") as fin: raw_model = fin.read() with open(args.param, "rb") as fin: raw_param = fin.read() model_size = (len(raw_model)).to_bytes(4, byteorder="little") param_size = (len(raw_param)).to_bytes(4, byteorder="little") n_inputs = (len(input_names)).to_bytes(4, byteorder="little") n_outputs = (len(output_names)).to_bytes(4, byteorder="little") names_buffer = n_inputs + n_outputs for iname in input_names: names_buffer += (len(iname)).to_bytes(4, byteorder="little") names_buffer += str.encode(iname) for oname in output_names: names_buffer += (len(oname)).to_bytes(4, byteorder="little") names_buffer += str.encode(oname) shapes_buffer = n_outputs for oshape in osizes: shapes_buffer += (len(oshape)).to_bytes(4, byteorder="little") for oi in oshape: shapes_buffer += oi.to_bytes(4, byteorder="little") # raw content contains: # input/output names + output shapes + model buffer + param buffer wk_raw_content = ( names_buffer + shapes_buffer + model_size + raw_model + param_size + raw_param ) net = ExternOprSubgraph(wk_raw_content, "mace", osizes) net.eval() @
jit.trace(symbolic=True)
megengine.jit.trace
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info
mge.random.seed(args.seed)
megengine.random.seed
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size()
mge.dtr.enable()
megengine.dtr.enable
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss =
F.abs(flow_preds[i] - flow_gt)
megengine.functional.abs
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size =
dist.get_rank()
megengine.distributed.get_rank
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(),
dist.get_world_size()
megengine.distributed.get_world_size
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [dist.make_allreduce_cb("mean")] gm = autodiff.GradManager().attach(model.parameters(), callbacks=dist_callbacks) scaler =
mge.amp.GradScaler()
megengine.amp.GradScaler
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [dist.make_allreduce_cb("mean")] gm = autodiff.GradManager().attach(model.parameters(), callbacks=dist_callbacks) scaler = mge.amp.GradScaler() if args.mixed_precision else None if rank == 0: # tensorboard tb_log = SummaryWriter(os.path.join(args.log_dir, "train.events")) # worklog logging.basicConfig(level=eval(args.log_level)) worklog = logging.getLogger("train_logger") worklog.propagate = False fileHandler = logging.FileHandler( os.path.join(args.log_dir, "worklog.txt"), mode="a", encoding="utf8" ) formatter = logging.Formatter( fmt="%(asctime)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( fmt="\x1b[32m%(asctime)s\x1b[0m %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) consoleHandler.setFormatter(formatter) worklog.handlers = [fileHandler, consoleHandler] # params stat worklog.info(f"Use {world_size} GPU(s)") worklog.info("Params: %s" % sum([p.size for p in model.parameters()])) # load pretrained model if exist chk_path = os.path.join(log_model_dir, "latest.mge") if args.loadmodel is not None: chk_path = args.loadmodel elif not os.path.exists(chk_path): chk_path = None if chk_path is not None: if rank == 0: worklog.info(f"loading model: {chk_path}") pretrained_dict =
mge.load(chk_path, map_location="cpu")
megengine.load
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [dist.make_allreduce_cb("mean")] gm = autodiff.GradManager().attach(model.parameters(), callbacks=dist_callbacks) scaler = mge.amp.GradScaler() if args.mixed_precision else None if rank == 0: # tensorboard tb_log = SummaryWriter(os.path.join(args.log_dir, "train.events")) # worklog logging.basicConfig(level=eval(args.log_level)) worklog = logging.getLogger("train_logger") worklog.propagate = False fileHandler = logging.FileHandler( os.path.join(args.log_dir, "worklog.txt"), mode="a", encoding="utf8" ) formatter = logging.Formatter( fmt="%(asctime)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( fmt="\x1b[32m%(asctime)s\x1b[0m %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) consoleHandler.setFormatter(formatter) worklog.handlers = [fileHandler, consoleHandler] # params stat worklog.info(f"Use {world_size} GPU(s)") worklog.info("Params: %s" % sum([p.size for p in model.parameters()])) # load pretrained model if exist chk_path = os.path.join(log_model_dir, "latest.mge") if args.loadmodel is not None: chk_path = args.loadmodel elif not os.path.exists(chk_path): chk_path = None if chk_path is not None: if rank == 0: worklog.info(f"loading model: {chk_path}") pretrained_dict = mge.load(chk_path, map_location="cpu") resume_epoch_idx = pretrained_dict["epoch"] resume_iters = pretrained_dict["iters"] model.load_state_dict(pretrained_dict["state_dict"], strict=True) optimizer.load_state_dict(pretrained_dict["optim_state_dict"]) start_epoch_idx = resume_epoch_idx + 1 start_iters = resume_iters else: start_epoch_idx = 1 start_iters = 0 # auxiliary if world_size > 1: dist.bcast_list_(model.tensors()) # datasets dataset = CREStereoDataset(args.training_data_path) if rank == 0: worklog.info(f"Dataset size: {len(dataset)}") inf_sampler = Infinite( RandomSampler( dataset, batch_size=args.batch_size_single, drop_last=False, world_size=world_size, rank=rank, seed=args.seed, ) ) dataloader = DataLoader( dataset, sampler=inf_sampler, num_workers=0, divide=False, preload=True ) # counter cur_iters = start_iters total_iters = args.minibatch_per_epoch * args.n_total_epoch t0 = time.perf_counter() for epoch_idx in range(start_epoch_idx, args.n_total_epoch + 1): # adjust learning rate epoch_total_train_loss = 0 adjust_learning_rate(optimizer, epoch_idx) model.train() t1 = time.perf_counter() batch_idx = 0 for mini_batch_data in dataloader: if batch_idx % args.minibatch_per_epoch == 0 and batch_idx != 0: break batch_idx += 1 cur_iters += 1 # parse data left, right, gt_disp, valid_mask = ( mini_batch_data["left"], mini_batch_data["right"], mini_batch_data["disparity"], mini_batch_data["mask"], ) t2 = time.perf_counter() with gm: # GradManager with mge.amp.autocast(enabled=args.mixed_precision): # pre-process left = mge.tensor(left) right = mge.tensor(right) gt_disp = mge.tensor(gt_disp) valid_mask = mge.tensor(valid_mask) gt_disp = F.expand_dims(gt_disp, axis=1) gt_flow = F.concat([gt_disp, gt_disp * 0], axis=1) # forward flow_predictions = model(left, right) # loss & backword loss = sequence_loss( flow_predictions, gt_flow, valid_mask, gamma=0.8 ) if args.mixed_precision: scaler.backward(gm, loss) else: gm.backward(loss) optimizer.step().clear_grad() # loss stats loss_item = loss.item() epoch_total_train_loss += loss_item t3 = time.perf_counter() # terminal print log if rank == 0: if cur_iters % 5 == 0: tdata = t2 - t1 time_train_passed = t3 - t0 time_iter_passed = t3 - t1 step_passed = cur_iters - start_iters eta = ( (total_iters - cur_iters) / max(step_passed, 1e-7) * time_train_passed ) meta_info = list() meta_info.append("{:.2g} b/s".format(1.0 / time_iter_passed)) meta_info.append("passed:{}".format(format_time(time_train_passed))) meta_info.append("eta:{}".format(format_time(eta))) meta_info.append( "data_time:{:.2g}".format(tdata / time_iter_passed) ) meta_info.append( "lr:{:.5g}".format(optimizer.param_groups[0]["lr"]) ) meta_info.append( "[{}/{}:{}/{}]".format( epoch_idx, args.n_total_epoch, batch_idx, args.minibatch_per_epoch, ) ) loss_info = [" ==> {}:{:.4g}".format("loss", loss_item)] # exp_name = ['\n' + os.path.basename(os.getcwd())] info = [",".join(meta_info)] + loss_info worklog.info("".join(info)) # minibatch loss tb_log.add_scalar("train/loss_batch", loss_item, cur_iters) tb_log.add_scalar( "train/lr", optimizer.param_groups[0]["lr"], cur_iters ) tb_log.flush() t1 = time.perf_counter() if rank == 0: # epoch loss tb_log.add_scalar( "train/loss", epoch_total_train_loss / args.minibatch_per_epoch, epoch_idx, ) tb_log.flush() # save model params ckp_data = { "epoch": epoch_idx, "iters": cur_iters, "batch_size": args.batch_size_single * args.nr_gpus, "epoch_size": args.minibatch_per_epoch, "train_loss": epoch_total_train_loss / args.minibatch_per_epoch, "state_dict": model.state_dict(), "optim_state_dict": optimizer.state_dict(), } mge.save(ckp_data, os.path.join(log_model_dir, "latest.mge")) if epoch_idx % args.model_save_freq_epoch == 0: save_path = os.path.join(log_model_dir, "epoch-%d.mge" % epoch_idx) worklog.info(f"Model params saved: {save_path}") mge.save(ckp_data, save_path) if rank == 0: worklog.info("Training is done, exit.") if __name__ == "__main__": # train configuration args = parse_yaml("cfgs/train.yaml") # distributed training run = main if mge.get_device_count("gpu") == 1 else
dist.launcher(main)
megengine.distributed.launcher
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [
dist.make_allreduce_cb("mean")
megengine.distributed.make_allreduce_cb
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [dist.make_allreduce_cb("mean")] gm =
autodiff.GradManager()
megengine.autodiff.GradManager
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [dist.make_allreduce_cb("mean")] gm = autodiff.GradManager().attach(model.parameters(), callbacks=dist_callbacks) scaler = mge.amp.GradScaler() if args.mixed_precision else None if rank == 0: # tensorboard tb_log = SummaryWriter(os.path.join(args.log_dir, "train.events")) # worklog logging.basicConfig(level=eval(args.log_level)) worklog = logging.getLogger("train_logger") worklog.propagate = False fileHandler = logging.FileHandler( os.path.join(args.log_dir, "worklog.txt"), mode="a", encoding="utf8" ) formatter = logging.Formatter( fmt="%(asctime)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( fmt="\x1b[32m%(asctime)s\x1b[0m %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) consoleHandler.setFormatter(formatter) worklog.handlers = [fileHandler, consoleHandler] # params stat worklog.info(f"Use {world_size} GPU(s)") worklog.info("Params: %s" % sum([p.size for p in model.parameters()])) # load pretrained model if exist chk_path = os.path.join(log_model_dir, "latest.mge") if args.loadmodel is not None: chk_path = args.loadmodel elif not os.path.exists(chk_path): chk_path = None if chk_path is not None: if rank == 0: worklog.info(f"loading model: {chk_path}") pretrained_dict = mge.load(chk_path, map_location="cpu") resume_epoch_idx = pretrained_dict["epoch"] resume_iters = pretrained_dict["iters"] model.load_state_dict(pretrained_dict["state_dict"], strict=True) optimizer.load_state_dict(pretrained_dict["optim_state_dict"]) start_epoch_idx = resume_epoch_idx + 1 start_iters = resume_iters else: start_epoch_idx = 1 start_iters = 0 # auxiliary if world_size > 1: dist.bcast_list_(model.tensors()) # datasets dataset = CREStereoDataset(args.training_data_path) if rank == 0: worklog.info(f"Dataset size: {len(dataset)}") inf_sampler = Infinite( RandomSampler( dataset, batch_size=args.batch_size_single, drop_last=False, world_size=world_size, rank=rank, seed=args.seed, ) ) dataloader = DataLoader( dataset, sampler=inf_sampler, num_workers=0, divide=False, preload=True ) # counter cur_iters = start_iters total_iters = args.minibatch_per_epoch * args.n_total_epoch t0 = time.perf_counter() for epoch_idx in range(start_epoch_idx, args.n_total_epoch + 1): # adjust learning rate epoch_total_train_loss = 0 adjust_learning_rate(optimizer, epoch_idx) model.train() t1 = time.perf_counter() batch_idx = 0 for mini_batch_data in dataloader: if batch_idx % args.minibatch_per_epoch == 0 and batch_idx != 0: break batch_idx += 1 cur_iters += 1 # parse data left, right, gt_disp, valid_mask = ( mini_batch_data["left"], mini_batch_data["right"], mini_batch_data["disparity"], mini_batch_data["mask"], ) t2 = time.perf_counter() with gm: # GradManager with mge.amp.autocast(enabled=args.mixed_precision): # pre-process left = mge.tensor(left) right = mge.tensor(right) gt_disp = mge.tensor(gt_disp) valid_mask = mge.tensor(valid_mask) gt_disp = F.expand_dims(gt_disp, axis=1) gt_flow = F.concat([gt_disp, gt_disp * 0], axis=1) # forward flow_predictions = model(left, right) # loss & backword loss = sequence_loss( flow_predictions, gt_flow, valid_mask, gamma=0.8 ) if args.mixed_precision: scaler.backward(gm, loss) else: gm.backward(loss) optimizer.step().clear_grad() # loss stats loss_item = loss.item() epoch_total_train_loss += loss_item t3 = time.perf_counter() # terminal print log if rank == 0: if cur_iters % 5 == 0: tdata = t2 - t1 time_train_passed = t3 - t0 time_iter_passed = t3 - t1 step_passed = cur_iters - start_iters eta = ( (total_iters - cur_iters) / max(step_passed, 1e-7) * time_train_passed ) meta_info = list() meta_info.append("{:.2g} b/s".format(1.0 / time_iter_passed)) meta_info.append("passed:{}".format(format_time(time_train_passed))) meta_info.append("eta:{}".format(format_time(eta))) meta_info.append( "data_time:{:.2g}".format(tdata / time_iter_passed) ) meta_info.append( "lr:{:.5g}".format(optimizer.param_groups[0]["lr"]) ) meta_info.append( "[{}/{}:{}/{}]".format( epoch_idx, args.n_total_epoch, batch_idx, args.minibatch_per_epoch, ) ) loss_info = [" ==> {}:{:.4g}".format("loss", loss_item)] # exp_name = ['\n' + os.path.basename(os.getcwd())] info = [",".join(meta_info)] + loss_info worklog.info("".join(info)) # minibatch loss tb_log.add_scalar("train/loss_batch", loss_item, cur_iters) tb_log.add_scalar( "train/lr", optimizer.param_groups[0]["lr"], cur_iters ) tb_log.flush() t1 = time.perf_counter() if rank == 0: # epoch loss tb_log.add_scalar( "train/loss", epoch_total_train_loss / args.minibatch_per_epoch, epoch_idx, ) tb_log.flush() # save model params ckp_data = { "epoch": epoch_idx, "iters": cur_iters, "batch_size": args.batch_size_single * args.nr_gpus, "epoch_size": args.minibatch_per_epoch, "train_loss": epoch_total_train_loss / args.minibatch_per_epoch, "state_dict": model.state_dict(), "optim_state_dict": optimizer.state_dict(), } mge.save(ckp_data, os.path.join(log_model_dir, "latest.mge")) if epoch_idx % args.model_save_freq_epoch == 0: save_path = os.path.join(log_model_dir, "epoch-%d.mge" % epoch_idx) worklog.info(f"Model params saved: {save_path}") mge.save(ckp_data, save_path) if rank == 0: worklog.info("Training is done, exit.") if __name__ == "__main__": # train configuration args = parse_yaml("cfgs/train.yaml") # distributed training run = main if
mge.get_device_count("gpu")
megengine.get_device_count
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [dist.make_allreduce_cb("mean")] gm = autodiff.GradManager().attach(model.parameters(), callbacks=dist_callbacks) scaler = mge.amp.GradScaler() if args.mixed_precision else None if rank == 0: # tensorboard tb_log = SummaryWriter(os.path.join(args.log_dir, "train.events")) # worklog logging.basicConfig(level=eval(args.log_level)) worklog = logging.getLogger("train_logger") worklog.propagate = False fileHandler = logging.FileHandler( os.path.join(args.log_dir, "worklog.txt"), mode="a", encoding="utf8" ) formatter = logging.Formatter( fmt="%(asctime)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( fmt="\x1b[32m%(asctime)s\x1b[0m %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) consoleHandler.setFormatter(formatter) worklog.handlers = [fileHandler, consoleHandler] # params stat worklog.info(f"Use {world_size} GPU(s)") worklog.info("Params: %s" % sum([p.size for p in model.parameters()])) # load pretrained model if exist chk_path = os.path.join(log_model_dir, "latest.mge") if args.loadmodel is not None: chk_path = args.loadmodel elif not os.path.exists(chk_path): chk_path = None if chk_path is not None: if rank == 0: worklog.info(f"loading model: {chk_path}") pretrained_dict = mge.load(chk_path, map_location="cpu") resume_epoch_idx = pretrained_dict["epoch"] resume_iters = pretrained_dict["iters"] model.load_state_dict(pretrained_dict["state_dict"], strict=True) optimizer.load_state_dict(pretrained_dict["optim_state_dict"]) start_epoch_idx = resume_epoch_idx + 1 start_iters = resume_iters else: start_epoch_idx = 1 start_iters = 0 # auxiliary if world_size > 1: dist.bcast_list_(model.tensors()) # datasets dataset = CREStereoDataset(args.training_data_path) if rank == 0: worklog.info(f"Dataset size: {len(dataset)}") inf_sampler = Infinite( RandomSampler( dataset, batch_size=args.batch_size_single, drop_last=False, world_size=world_size, rank=rank, seed=args.seed, ) ) dataloader = DataLoader( dataset, sampler=inf_sampler, num_workers=0, divide=False, preload=True ) # counter cur_iters = start_iters total_iters = args.minibatch_per_epoch * args.n_total_epoch t0 = time.perf_counter() for epoch_idx in range(start_epoch_idx, args.n_total_epoch + 1): # adjust learning rate epoch_total_train_loss = 0 adjust_learning_rate(optimizer, epoch_idx) model.train() t1 = time.perf_counter() batch_idx = 0 for mini_batch_data in dataloader: if batch_idx % args.minibatch_per_epoch == 0 and batch_idx != 0: break batch_idx += 1 cur_iters += 1 # parse data left, right, gt_disp, valid_mask = ( mini_batch_data["left"], mini_batch_data["right"], mini_batch_data["disparity"], mini_batch_data["mask"], ) t2 = time.perf_counter() with gm: # GradManager with mge.amp.autocast(enabled=args.mixed_precision): # pre-process left = mge.tensor(left) right = mge.tensor(right) gt_disp = mge.tensor(gt_disp) valid_mask = mge.tensor(valid_mask) gt_disp = F.expand_dims(gt_disp, axis=1) gt_flow = F.concat([gt_disp, gt_disp * 0], axis=1) # forward flow_predictions = model(left, right) # loss & backword loss = sequence_loss( flow_predictions, gt_flow, valid_mask, gamma=0.8 ) if args.mixed_precision: scaler.backward(gm, loss) else: gm.backward(loss) optimizer.step().clear_grad() # loss stats loss_item = loss.item() epoch_total_train_loss += loss_item t3 = time.perf_counter() # terminal print log if rank == 0: if cur_iters % 5 == 0: tdata = t2 - t1 time_train_passed = t3 - t0 time_iter_passed = t3 - t1 step_passed = cur_iters - start_iters eta = ( (total_iters - cur_iters) / max(step_passed, 1e-7) * time_train_passed ) meta_info = list() meta_info.append("{:.2g} b/s".format(1.0 / time_iter_passed)) meta_info.append("passed:{}".format(format_time(time_train_passed))) meta_info.append("eta:{}".format(format_time(eta))) meta_info.append( "data_time:{:.2g}".format(tdata / time_iter_passed) ) meta_info.append( "lr:{:.5g}".format(optimizer.param_groups[0]["lr"]) ) meta_info.append( "[{}/{}:{}/{}]".format( epoch_idx, args.n_total_epoch, batch_idx, args.minibatch_per_epoch, ) ) loss_info = [" ==> {}:{:.4g}".format("loss", loss_item)] # exp_name = ['\n' + os.path.basename(os.getcwd())] info = [",".join(meta_info)] + loss_info worklog.info("".join(info)) # minibatch loss tb_log.add_scalar("train/loss_batch", loss_item, cur_iters) tb_log.add_scalar( "train/lr", optimizer.param_groups[0]["lr"], cur_iters ) tb_log.flush() t1 = time.perf_counter() if rank == 0: # epoch loss tb_log.add_scalar( "train/loss", epoch_total_train_loss / args.minibatch_per_epoch, epoch_idx, ) tb_log.flush() # save model params ckp_data = { "epoch": epoch_idx, "iters": cur_iters, "batch_size": args.batch_size_single * args.nr_gpus, "epoch_size": args.minibatch_per_epoch, "train_loss": epoch_total_train_loss / args.minibatch_per_epoch, "state_dict": model.state_dict(), "optim_state_dict": optimizer.state_dict(), } mge.save(ckp_data, os.path.join(log_model_dir, "latest.mge")) if epoch_idx % args.model_save_freq_epoch == 0: save_path = os.path.join(log_model_dir, "epoch-%d.mge" % epoch_idx) worklog.info(f"Model params saved: {save_path}")
mge.save(ckp_data, save_path)
megengine.save
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [dist.make_allreduce_cb("mean")] gm = autodiff.GradManager().attach(model.parameters(), callbacks=dist_callbacks) scaler = mge.amp.GradScaler() if args.mixed_precision else None if rank == 0: # tensorboard tb_log = SummaryWriter(os.path.join(args.log_dir, "train.events")) # worklog logging.basicConfig(level=eval(args.log_level)) worklog = logging.getLogger("train_logger") worklog.propagate = False fileHandler = logging.FileHandler( os.path.join(args.log_dir, "worklog.txt"), mode="a", encoding="utf8" ) formatter = logging.Formatter( fmt="%(asctime)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( fmt="\x1b[32m%(asctime)s\x1b[0m %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) consoleHandler.setFormatter(formatter) worklog.handlers = [fileHandler, consoleHandler] # params stat worklog.info(f"Use {world_size} GPU(s)") worklog.info("Params: %s" % sum([p.size for p in model.parameters()])) # load pretrained model if exist chk_path = os.path.join(log_model_dir, "latest.mge") if args.loadmodel is not None: chk_path = args.loadmodel elif not os.path.exists(chk_path): chk_path = None if chk_path is not None: if rank == 0: worklog.info(f"loading model: {chk_path}") pretrained_dict = mge.load(chk_path, map_location="cpu") resume_epoch_idx = pretrained_dict["epoch"] resume_iters = pretrained_dict["iters"] model.load_state_dict(pretrained_dict["state_dict"], strict=True) optimizer.load_state_dict(pretrained_dict["optim_state_dict"]) start_epoch_idx = resume_epoch_idx + 1 start_iters = resume_iters else: start_epoch_idx = 1 start_iters = 0 # auxiliary if world_size > 1: dist.bcast_list_(model.tensors()) # datasets dataset = CREStereoDataset(args.training_data_path) if rank == 0: worklog.info(f"Dataset size: {len(dataset)}") inf_sampler = Infinite( RandomSampler( dataset, batch_size=args.batch_size_single, drop_last=False, world_size=world_size, rank=rank, seed=args.seed, ) ) dataloader = DataLoader( dataset, sampler=inf_sampler, num_workers=0, divide=False, preload=True ) # counter cur_iters = start_iters total_iters = args.minibatch_per_epoch * args.n_total_epoch t0 = time.perf_counter() for epoch_idx in range(start_epoch_idx, args.n_total_epoch + 1): # adjust learning rate epoch_total_train_loss = 0 adjust_learning_rate(optimizer, epoch_idx) model.train() t1 = time.perf_counter() batch_idx = 0 for mini_batch_data in dataloader: if batch_idx % args.minibatch_per_epoch == 0 and batch_idx != 0: break batch_idx += 1 cur_iters += 1 # parse data left, right, gt_disp, valid_mask = ( mini_batch_data["left"], mini_batch_data["right"], mini_batch_data["disparity"], mini_batch_data["mask"], ) t2 = time.perf_counter() with gm: # GradManager with
mge.amp.autocast(enabled=args.mixed_precision)
megengine.amp.autocast
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [dist.make_allreduce_cb("mean")] gm = autodiff.GradManager().attach(model.parameters(), callbacks=dist_callbacks) scaler = mge.amp.GradScaler() if args.mixed_precision else None if rank == 0: # tensorboard tb_log = SummaryWriter(os.path.join(args.log_dir, "train.events")) # worklog logging.basicConfig(level=eval(args.log_level)) worklog = logging.getLogger("train_logger") worklog.propagate = False fileHandler = logging.FileHandler( os.path.join(args.log_dir, "worklog.txt"), mode="a", encoding="utf8" ) formatter = logging.Formatter( fmt="%(asctime)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( fmt="\x1b[32m%(asctime)s\x1b[0m %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) consoleHandler.setFormatter(formatter) worklog.handlers = [fileHandler, consoleHandler] # params stat worklog.info(f"Use {world_size} GPU(s)") worklog.info("Params: %s" % sum([p.size for p in model.parameters()])) # load pretrained model if exist chk_path = os.path.join(log_model_dir, "latest.mge") if args.loadmodel is not None: chk_path = args.loadmodel elif not os.path.exists(chk_path): chk_path = None if chk_path is not None: if rank == 0: worklog.info(f"loading model: {chk_path}") pretrained_dict = mge.load(chk_path, map_location="cpu") resume_epoch_idx = pretrained_dict["epoch"] resume_iters = pretrained_dict["iters"] model.load_state_dict(pretrained_dict["state_dict"], strict=True) optimizer.load_state_dict(pretrained_dict["optim_state_dict"]) start_epoch_idx = resume_epoch_idx + 1 start_iters = resume_iters else: start_epoch_idx = 1 start_iters = 0 # auxiliary if world_size > 1: dist.bcast_list_(model.tensors()) # datasets dataset = CREStereoDataset(args.training_data_path) if rank == 0: worklog.info(f"Dataset size: {len(dataset)}") inf_sampler = Infinite( RandomSampler( dataset, batch_size=args.batch_size_single, drop_last=False, world_size=world_size, rank=rank, seed=args.seed, ) ) dataloader = DataLoader( dataset, sampler=inf_sampler, num_workers=0, divide=False, preload=True ) # counter cur_iters = start_iters total_iters = args.minibatch_per_epoch * args.n_total_epoch t0 = time.perf_counter() for epoch_idx in range(start_epoch_idx, args.n_total_epoch + 1): # adjust learning rate epoch_total_train_loss = 0 adjust_learning_rate(optimizer, epoch_idx) model.train() t1 = time.perf_counter() batch_idx = 0 for mini_batch_data in dataloader: if batch_idx % args.minibatch_per_epoch == 0 and batch_idx != 0: break batch_idx += 1 cur_iters += 1 # parse data left, right, gt_disp, valid_mask = ( mini_batch_data["left"], mini_batch_data["right"], mini_batch_data["disparity"], mini_batch_data["mask"], ) t2 = time.perf_counter() with gm: # GradManager with mge.amp.autocast(enabled=args.mixed_precision): # pre-process left =
mge.tensor(left)
megengine.tensor
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [dist.make_allreduce_cb("mean")] gm = autodiff.GradManager().attach(model.parameters(), callbacks=dist_callbacks) scaler = mge.amp.GradScaler() if args.mixed_precision else None if rank == 0: # tensorboard tb_log = SummaryWriter(os.path.join(args.log_dir, "train.events")) # worklog logging.basicConfig(level=eval(args.log_level)) worklog = logging.getLogger("train_logger") worklog.propagate = False fileHandler = logging.FileHandler( os.path.join(args.log_dir, "worklog.txt"), mode="a", encoding="utf8" ) formatter = logging.Formatter( fmt="%(asctime)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( fmt="\x1b[32m%(asctime)s\x1b[0m %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) consoleHandler.setFormatter(formatter) worklog.handlers = [fileHandler, consoleHandler] # params stat worklog.info(f"Use {world_size} GPU(s)") worklog.info("Params: %s" % sum([p.size for p in model.parameters()])) # load pretrained model if exist chk_path = os.path.join(log_model_dir, "latest.mge") if args.loadmodel is not None: chk_path = args.loadmodel elif not os.path.exists(chk_path): chk_path = None if chk_path is not None: if rank == 0: worklog.info(f"loading model: {chk_path}") pretrained_dict = mge.load(chk_path, map_location="cpu") resume_epoch_idx = pretrained_dict["epoch"] resume_iters = pretrained_dict["iters"] model.load_state_dict(pretrained_dict["state_dict"], strict=True) optimizer.load_state_dict(pretrained_dict["optim_state_dict"]) start_epoch_idx = resume_epoch_idx + 1 start_iters = resume_iters else: start_epoch_idx = 1 start_iters = 0 # auxiliary if world_size > 1: dist.bcast_list_(model.tensors()) # datasets dataset = CREStereoDataset(args.training_data_path) if rank == 0: worklog.info(f"Dataset size: {len(dataset)}") inf_sampler = Infinite( RandomSampler( dataset, batch_size=args.batch_size_single, drop_last=False, world_size=world_size, rank=rank, seed=args.seed, ) ) dataloader = DataLoader( dataset, sampler=inf_sampler, num_workers=0, divide=False, preload=True ) # counter cur_iters = start_iters total_iters = args.minibatch_per_epoch * args.n_total_epoch t0 = time.perf_counter() for epoch_idx in range(start_epoch_idx, args.n_total_epoch + 1): # adjust learning rate epoch_total_train_loss = 0 adjust_learning_rate(optimizer, epoch_idx) model.train() t1 = time.perf_counter() batch_idx = 0 for mini_batch_data in dataloader: if batch_idx % args.minibatch_per_epoch == 0 and batch_idx != 0: break batch_idx += 1 cur_iters += 1 # parse data left, right, gt_disp, valid_mask = ( mini_batch_data["left"], mini_batch_data["right"], mini_batch_data["disparity"], mini_batch_data["mask"], ) t2 = time.perf_counter() with gm: # GradManager with mge.amp.autocast(enabled=args.mixed_precision): # pre-process left = mge.tensor(left) right =
mge.tensor(right)
megengine.tensor
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [dist.make_allreduce_cb("mean")] gm = autodiff.GradManager().attach(model.parameters(), callbacks=dist_callbacks) scaler = mge.amp.GradScaler() if args.mixed_precision else None if rank == 0: # tensorboard tb_log = SummaryWriter(os.path.join(args.log_dir, "train.events")) # worklog logging.basicConfig(level=eval(args.log_level)) worklog = logging.getLogger("train_logger") worklog.propagate = False fileHandler = logging.FileHandler( os.path.join(args.log_dir, "worklog.txt"), mode="a", encoding="utf8" ) formatter = logging.Formatter( fmt="%(asctime)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( fmt="\x1b[32m%(asctime)s\x1b[0m %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) consoleHandler.setFormatter(formatter) worklog.handlers = [fileHandler, consoleHandler] # params stat worklog.info(f"Use {world_size} GPU(s)") worklog.info("Params: %s" % sum([p.size for p in model.parameters()])) # load pretrained model if exist chk_path = os.path.join(log_model_dir, "latest.mge") if args.loadmodel is not None: chk_path = args.loadmodel elif not os.path.exists(chk_path): chk_path = None if chk_path is not None: if rank == 0: worklog.info(f"loading model: {chk_path}") pretrained_dict = mge.load(chk_path, map_location="cpu") resume_epoch_idx = pretrained_dict["epoch"] resume_iters = pretrained_dict["iters"] model.load_state_dict(pretrained_dict["state_dict"], strict=True) optimizer.load_state_dict(pretrained_dict["optim_state_dict"]) start_epoch_idx = resume_epoch_idx + 1 start_iters = resume_iters else: start_epoch_idx = 1 start_iters = 0 # auxiliary if world_size > 1: dist.bcast_list_(model.tensors()) # datasets dataset = CREStereoDataset(args.training_data_path) if rank == 0: worklog.info(f"Dataset size: {len(dataset)}") inf_sampler = Infinite( RandomSampler( dataset, batch_size=args.batch_size_single, drop_last=False, world_size=world_size, rank=rank, seed=args.seed, ) ) dataloader = DataLoader( dataset, sampler=inf_sampler, num_workers=0, divide=False, preload=True ) # counter cur_iters = start_iters total_iters = args.minibatch_per_epoch * args.n_total_epoch t0 = time.perf_counter() for epoch_idx in range(start_epoch_idx, args.n_total_epoch + 1): # adjust learning rate epoch_total_train_loss = 0 adjust_learning_rate(optimizer, epoch_idx) model.train() t1 = time.perf_counter() batch_idx = 0 for mini_batch_data in dataloader: if batch_idx % args.minibatch_per_epoch == 0 and batch_idx != 0: break batch_idx += 1 cur_iters += 1 # parse data left, right, gt_disp, valid_mask = ( mini_batch_data["left"], mini_batch_data["right"], mini_batch_data["disparity"], mini_batch_data["mask"], ) t2 = time.perf_counter() with gm: # GradManager with mge.amp.autocast(enabled=args.mixed_precision): # pre-process left = mge.tensor(left) right = mge.tensor(right) gt_disp =
mge.tensor(gt_disp)
megengine.tensor
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [dist.make_allreduce_cb("mean")] gm = autodiff.GradManager().attach(model.parameters(), callbacks=dist_callbacks) scaler = mge.amp.GradScaler() if args.mixed_precision else None if rank == 0: # tensorboard tb_log = SummaryWriter(os.path.join(args.log_dir, "train.events")) # worklog logging.basicConfig(level=eval(args.log_level)) worklog = logging.getLogger("train_logger") worklog.propagate = False fileHandler = logging.FileHandler( os.path.join(args.log_dir, "worklog.txt"), mode="a", encoding="utf8" ) formatter = logging.Formatter( fmt="%(asctime)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( fmt="\x1b[32m%(asctime)s\x1b[0m %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) consoleHandler.setFormatter(formatter) worklog.handlers = [fileHandler, consoleHandler] # params stat worklog.info(f"Use {world_size} GPU(s)") worklog.info("Params: %s" % sum([p.size for p in model.parameters()])) # load pretrained model if exist chk_path = os.path.join(log_model_dir, "latest.mge") if args.loadmodel is not None: chk_path = args.loadmodel elif not os.path.exists(chk_path): chk_path = None if chk_path is not None: if rank == 0: worklog.info(f"loading model: {chk_path}") pretrained_dict = mge.load(chk_path, map_location="cpu") resume_epoch_idx = pretrained_dict["epoch"] resume_iters = pretrained_dict["iters"] model.load_state_dict(pretrained_dict["state_dict"], strict=True) optimizer.load_state_dict(pretrained_dict["optim_state_dict"]) start_epoch_idx = resume_epoch_idx + 1 start_iters = resume_iters else: start_epoch_idx = 1 start_iters = 0 # auxiliary if world_size > 1: dist.bcast_list_(model.tensors()) # datasets dataset = CREStereoDataset(args.training_data_path) if rank == 0: worklog.info(f"Dataset size: {len(dataset)}") inf_sampler = Infinite( RandomSampler( dataset, batch_size=args.batch_size_single, drop_last=False, world_size=world_size, rank=rank, seed=args.seed, ) ) dataloader = DataLoader( dataset, sampler=inf_sampler, num_workers=0, divide=False, preload=True ) # counter cur_iters = start_iters total_iters = args.minibatch_per_epoch * args.n_total_epoch t0 = time.perf_counter() for epoch_idx in range(start_epoch_idx, args.n_total_epoch + 1): # adjust learning rate epoch_total_train_loss = 0 adjust_learning_rate(optimizer, epoch_idx) model.train() t1 = time.perf_counter() batch_idx = 0 for mini_batch_data in dataloader: if batch_idx % args.minibatch_per_epoch == 0 and batch_idx != 0: break batch_idx += 1 cur_iters += 1 # parse data left, right, gt_disp, valid_mask = ( mini_batch_data["left"], mini_batch_data["right"], mini_batch_data["disparity"], mini_batch_data["mask"], ) t2 = time.perf_counter() with gm: # GradManager with mge.amp.autocast(enabled=args.mixed_precision): # pre-process left = mge.tensor(left) right = mge.tensor(right) gt_disp = mge.tensor(gt_disp) valid_mask =
mge.tensor(valid_mask)
megengine.tensor
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [dist.make_allreduce_cb("mean")] gm = autodiff.GradManager().attach(model.parameters(), callbacks=dist_callbacks) scaler = mge.amp.GradScaler() if args.mixed_precision else None if rank == 0: # tensorboard tb_log = SummaryWriter(os.path.join(args.log_dir, "train.events")) # worklog logging.basicConfig(level=eval(args.log_level)) worklog = logging.getLogger("train_logger") worklog.propagate = False fileHandler = logging.FileHandler( os.path.join(args.log_dir, "worklog.txt"), mode="a", encoding="utf8" ) formatter = logging.Formatter( fmt="%(asctime)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( fmt="\x1b[32m%(asctime)s\x1b[0m %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) consoleHandler.setFormatter(formatter) worklog.handlers = [fileHandler, consoleHandler] # params stat worklog.info(f"Use {world_size} GPU(s)") worklog.info("Params: %s" % sum([p.size for p in model.parameters()])) # load pretrained model if exist chk_path = os.path.join(log_model_dir, "latest.mge") if args.loadmodel is not None: chk_path = args.loadmodel elif not os.path.exists(chk_path): chk_path = None if chk_path is not None: if rank == 0: worklog.info(f"loading model: {chk_path}") pretrained_dict = mge.load(chk_path, map_location="cpu") resume_epoch_idx = pretrained_dict["epoch"] resume_iters = pretrained_dict["iters"] model.load_state_dict(pretrained_dict["state_dict"], strict=True) optimizer.load_state_dict(pretrained_dict["optim_state_dict"]) start_epoch_idx = resume_epoch_idx + 1 start_iters = resume_iters else: start_epoch_idx = 1 start_iters = 0 # auxiliary if world_size > 1: dist.bcast_list_(model.tensors()) # datasets dataset = CREStereoDataset(args.training_data_path) if rank == 0: worklog.info(f"Dataset size: {len(dataset)}") inf_sampler = Infinite( RandomSampler( dataset, batch_size=args.batch_size_single, drop_last=False, world_size=world_size, rank=rank, seed=args.seed, ) ) dataloader = DataLoader( dataset, sampler=inf_sampler, num_workers=0, divide=False, preload=True ) # counter cur_iters = start_iters total_iters = args.minibatch_per_epoch * args.n_total_epoch t0 = time.perf_counter() for epoch_idx in range(start_epoch_idx, args.n_total_epoch + 1): # adjust learning rate epoch_total_train_loss = 0 adjust_learning_rate(optimizer, epoch_idx) model.train() t1 = time.perf_counter() batch_idx = 0 for mini_batch_data in dataloader: if batch_idx % args.minibatch_per_epoch == 0 and batch_idx != 0: break batch_idx += 1 cur_iters += 1 # parse data left, right, gt_disp, valid_mask = ( mini_batch_data["left"], mini_batch_data["right"], mini_batch_data["disparity"], mini_batch_data["mask"], ) t2 = time.perf_counter() with gm: # GradManager with mge.amp.autocast(enabled=args.mixed_precision): # pre-process left = mge.tensor(left) right = mge.tensor(right) gt_disp = mge.tensor(gt_disp) valid_mask = mge.tensor(valid_mask) gt_disp =
F.expand_dims(gt_disp, axis=1)
megengine.functional.expand_dims
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (F.expand_dims(valid, axis=1) * i_loss).mean() return flow_loss def main(args): # initial info mge.random.seed(args.seed) rank, world_size = dist.get_rank(), dist.get_world_size() mge.dtr.enable() # Dynamic tensor rematerialization for memory optimization # directory check log_model_dir = os.path.join(args.log_dir, "models") ensure_dir(log_model_dir) # model / optimizer model = Model( max_disp=args.max_disp, mixed_precision=args.mixed_precision, test_mode=False ) optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999)) dist_callbacks = None if world_size == 1 else [dist.make_allreduce_cb("mean")] gm = autodiff.GradManager().attach(model.parameters(), callbacks=dist_callbacks) scaler = mge.amp.GradScaler() if args.mixed_precision else None if rank == 0: # tensorboard tb_log = SummaryWriter(os.path.join(args.log_dir, "train.events")) # worklog logging.basicConfig(level=eval(args.log_level)) worklog = logging.getLogger("train_logger") worklog.propagate = False fileHandler = logging.FileHandler( os.path.join(args.log_dir, "worklog.txt"), mode="a", encoding="utf8" ) formatter = logging.Formatter( fmt="%(asctime)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( fmt="\x1b[32m%(asctime)s\x1b[0m %(message)s", datefmt="%Y/%m/%d %H:%M:%S" ) consoleHandler.setFormatter(formatter) worklog.handlers = [fileHandler, consoleHandler] # params stat worklog.info(f"Use {world_size} GPU(s)") worklog.info("Params: %s" % sum([p.size for p in model.parameters()])) # load pretrained model if exist chk_path = os.path.join(log_model_dir, "latest.mge") if args.loadmodel is not None: chk_path = args.loadmodel elif not os.path.exists(chk_path): chk_path = None if chk_path is not None: if rank == 0: worklog.info(f"loading model: {chk_path}") pretrained_dict = mge.load(chk_path, map_location="cpu") resume_epoch_idx = pretrained_dict["epoch"] resume_iters = pretrained_dict["iters"] model.load_state_dict(pretrained_dict["state_dict"], strict=True) optimizer.load_state_dict(pretrained_dict["optim_state_dict"]) start_epoch_idx = resume_epoch_idx + 1 start_iters = resume_iters else: start_epoch_idx = 1 start_iters = 0 # auxiliary if world_size > 1: dist.bcast_list_(model.tensors()) # datasets dataset = CREStereoDataset(args.training_data_path) if rank == 0: worklog.info(f"Dataset size: {len(dataset)}") inf_sampler = Infinite( RandomSampler( dataset, batch_size=args.batch_size_single, drop_last=False, world_size=world_size, rank=rank, seed=args.seed, ) ) dataloader = DataLoader( dataset, sampler=inf_sampler, num_workers=0, divide=False, preload=True ) # counter cur_iters = start_iters total_iters = args.minibatch_per_epoch * args.n_total_epoch t0 = time.perf_counter() for epoch_idx in range(start_epoch_idx, args.n_total_epoch + 1): # adjust learning rate epoch_total_train_loss = 0 adjust_learning_rate(optimizer, epoch_idx) model.train() t1 = time.perf_counter() batch_idx = 0 for mini_batch_data in dataloader: if batch_idx % args.minibatch_per_epoch == 0 and batch_idx != 0: break batch_idx += 1 cur_iters += 1 # parse data left, right, gt_disp, valid_mask = ( mini_batch_data["left"], mini_batch_data["right"], mini_batch_data["disparity"], mini_batch_data["mask"], ) t2 = time.perf_counter() with gm: # GradManager with mge.amp.autocast(enabled=args.mixed_precision): # pre-process left = mge.tensor(left) right = mge.tensor(right) gt_disp = mge.tensor(gt_disp) valid_mask = mge.tensor(valid_mask) gt_disp = F.expand_dims(gt_disp, axis=1) gt_flow =
F.concat([gt_disp, gt_disp * 0], axis=1)
megengine.functional.concat
import os import sys import time import logging from collections import namedtuple import megengine as mge import megengine.distributed as dist import megengine.functional as F import megengine.autodiff as autodiff import megengine.optimizer as optim import yaml from tensorboardX import SummaryWriter from nets import Model from dataset import CREStereoDataset from megengine.data import DataLoader, RandomSampler, Infinite def parse_yaml(file_path: str) -> namedtuple: """Parse yaml configuration file and return the object in `namedtuple`.""" with open(file_path, "rb") as f: cfg: dict = yaml.safe_load(f) args = namedtuple("train_args", cfg.keys())(*cfg.values()) return args def format_time(elapse): elapse = int(elapse) hour = elapse // 3600 minute = elapse % 3600 // 60 seconds = elapse % 60 return "{:02d}:{:02d}:{:02d}".format(hour, minute, seconds) def ensure_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) def adjust_learning_rate(optimizer, epoch): warm_up = 0.02 const_range = 0.6 min_lr_rate = 0.05 if epoch <= args.n_total_epoch * warm_up: lr = (1 - min_lr_rate) * args.base_lr / ( args.n_total_epoch * warm_up ) * epoch + min_lr_rate * args.base_lr elif args.n_total_epoch * warm_up < epoch <= args.n_total_epoch * const_range: lr = args.base_lr else: lr = (min_lr_rate - 1) * args.base_lr / ( (1 - const_range) * args.n_total_epoch ) * epoch + (1 - min_lr_rate * const_range) / (1 - const_range) * args.base_lr optimizer.param_groups[0]["lr"] = lr def sequence_loss(flow_preds, flow_gt, valid, gamma=0.8): n_predictions = len(flow_preds) flow_loss = 0.0 for i in range(n_predictions): i_weight = gamma ** (n_predictions - i - 1) i_loss = F.abs(flow_preds[i] - flow_gt) flow_loss += i_weight * (
F.expand_dims(valid, axis=1)
megengine.functional.expand_dims
# -*- 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 functools from typing import Iterable, List, Optional, Union import numpy as np import megengine._internal as mgb from megengine._internal import CompGraph, CompNode from ..core import zeros from ..core.graph import _use_default_if_none from ..core.tensor import Tensor, wrap_io_tensor from .elemwise import ceil from .utils import _decide_comp_node_and_comp_graph @wrap_io_tensor def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor: """ Broadcast a tensor to ``shape`` :param inp: The input tensor :param shape: The target shape :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3)) out = F.broadcast_to(data, (4, 2, 3)) print(out.numpy()) Outputs: .. testoutput:: [[[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]]] """ if isinstance(shape, int): shape = (shape,) return
mgb.opr.broadcast(inp, shape)
megengine._internal.opr.broadcast
# -*- 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 functools from typing import Iterable, List, Optional, Union import numpy as np import megengine._internal as mgb from megengine._internal import CompGraph, CompNode from ..core import zeros from ..core.graph import _use_default_if_none from ..core.tensor import Tensor, wrap_io_tensor from .elemwise import ceil from .utils import _decide_comp_node_and_comp_graph @wrap_io_tensor def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor: """ Broadcast a tensor to ``shape`` :param inp: The input tensor :param shape: The target shape :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3)) out = F.broadcast_to(data, (4, 2, 3)) print(out.numpy()) Outputs: .. testoutput:: [[[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]]] """ if isinstance(shape, int): shape = (shape,) return mgb.opr.broadcast(inp, shape) def _get_idx(index, axis): index_dims = len(index.imm_shape) idx = [] comp_node, comp_graph = _decide_comp_node_and_comp_graph(index) for i in range(index_dims): if i != axis: shape = [1] * index_dims shape[i] = index.axis_shape(i) arange = mgb.opr.linspace( 0, index.axis_shape(i) - 1, index.axis_shape(i), comp_node=comp_node, comp_graph=comp_graph, ) arange = ( arange.reshape(*shape) .broadcast(index.shape) .reshape(-1) .astype(np.int32) ) idx.append(arange) else: idx.append(index.reshape(-1)) return tuple(idx) @wrap_io_tensor def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor: r""" Gather data from :attr:`inp` on :attr:`axis` using :attr:`index`. For a 3-D tensor, the output is specified by:: out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0 out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1 out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2 if :attr:`inp` is an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i, then :attr:`index` must be an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and output will have the same size as :attr:`index`. :param inp: the source tensor :param axis: the axis along which to index :param index: the indices of elements to gather Examples: .. testcode:: import megengine.functional as F from megengine.core import tensor inp = tensor([ [1,2], [3,4], [5,6], ]) index = tensor([[0,2], [1,0]]) oup = F.gather(inp, 0, index) print(oup.numpy()) Outputs: .. testoutput:: [[1 6] [3 2]] """ input_shape = inp.imm_shape index_shape = index.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) if input_dims != index_dims: raise ValueError( "The index tensor must have same dimensions as input tensor, " "But the input dims:{}, the index dims:{}".format(input_dims, index_dims) ) if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(input_dims): if i != axis and input_shape[i] != index_shape[i]: raise ValueError( "The input {} and index {} must have the same size apart from axis {}".format( input_shape, index_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.advanced_indexing(inp)[idx].reshape( index.shape ) # pylint: disable=no-member @wrap_io_tensor def concat( inps: Iterable[Tensor], axis: int = 0, device: Optional[CompNode] = None, comp_graph: Optional[CompGraph] = None, ) -> Tensor: r""" Concat some tensors :param inps: Input tensors to concat :param axis: the dimension over which the tensors are concatenated. Default: 0 :param device: The comp node output on. Default: None :param comp_graph: The graph in which output is. Default: None :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3))) data2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3))) out = F.concat([data1, data2]) print(out.numpy()) Outputs: .. testoutput:: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.] [ 9. 10. 11.]] """ # Output buffer not supported return mgb.opr.concat( *list(inps), axis=axis, comp_node=device, comp_graph=comp_graph ) @wrap_io_tensor def scatter(inp: Tensor, axis: int, index: Tensor, source: Tensor) -> Tensor: r""" Writes all values from the tensor :attr:`source` into :attr:`inp` at the indices specified in the :attr:`index` tensor. For each value in :attr:`source`, its output index is specified by its index in :attr:`source` for ``axis != dimension`` and by the corresponding value in :attr:`index` for ``axis = dimension``. For a 3-D tensor, :attr:`inp` is updated as:: inp[index[i][j][k]][j][k] = source[i][j][k] # if axis == 0 inp[i][index[i][j][k]][k] = source[i][j][k] # if axis == 1 inp[i][j][index[i][j][k]] = source[i][j][k] # if axis == 2 :attr:`inp`, :attr:`index` and :attr:`source` should have same number of dimensions. It is also required that ``source.shape(d) <= inp.shape(d)`` and ``index.shape(d) == source.shape(d)`` for all dimensions ``d``. Moreover, the values of :attr:`index` must be between ``0`` and ``inp.shape(axis) - 1`` inclusive. .. note:: Please notice that, due to performance issues, the result is uncertain on the GPU device if scatter difference positions from source to the same destination position regard to index tensor. Show the case using the following examples, the oup[0][2] is maybe from source[0][2] which value is 0.2256 or source[1][2] which value is 0.5339 if set the index[1][2] from 1 to 0. :param inp: the inp tensor which to be scattered :param axis: the axis along which to index :param index: the indices of elements to scatter :param source: the source element(s) to scatter Examples: .. testcode:: import numpy as np import megengine.functional as F from megengine.core import tensor inp = tensor(np.zeros(shape=(3,5),dtype=np.float32)) source = tensor([[0.9935,0.9465,0.2256,0.8926,0.4396],[0.7723,0.0718,0.5939,0.357,0.4576]]) index = tensor([[0,2,0,2,1],[2,0,1,1,2]]) oup = F.scatter(inp, 0, index,source) print(oup.numpy()) Outputs: .. testoutput:: [[0.9935 0.0718 0.2256 0. 0. ] [0. 0. 0.5939 0.357 0.4396] [0.7723 0.9465 0. 0.8926 0.4576]] """ input_shape = inp.imm_shape index_shape = index.imm_shape source_shape = source.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) source_dims = len(source_shape) if input_dims != index_dims or input_dims != source_dims: raise ValueError("The input, source and index tensor must have same dimensions") if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(source_dims): if source_shape[i] > input_shape[i]: raise ValueError( "The each shape size for source {} must be less than or equal to input {} ".format( source_shape, input_shape ) ) for i in range(index_dims): if index_shape[i] != source_shape[i]: raise ValueError( "The each shape size for index {} must be equal to source {} ".format( index_shape, source_shape ) ) for i in range(index_dims): if i != axis and index_shape[i] > input_shape[i]: raise ValueError( "The index {} must be less than or equal to input {} size apart from axis {}".format( index_shape, input_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.set_advanced_indexing(inp, source.flatten())[idx] @wrap_io_tensor def where(mask: Tensor, x: Tensor, y: Tensor) -> Tensor: r""" Select elements either from Tensor x or Tensor y, according to mask. .. math:: \textrm{out}_i = x_i \textrm{ if } \textrm{mask}_i \textrm{ is True else } y_i :param mask: a mask used for choosing x or y :param x: the first choice :param y: the second choice Examples: .. testcode:: from megengine import tensor import megengine.functional as F mask = tensor(np.array([[1, 0], [0, 1]], dtype=np.int32)) x = tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)) y = tensor(np.array([[5, 6], [7, 8]], dtype=np.float32)) out = F.where(mask, x, y) print(out.numpy()) Outputs: .. testoutput:: [[1. 6.] [7. 4.]] """ v0, index0 = mgb.opr.cond_take( x, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=1 ) v1, index1 = mgb.opr.cond_take( y, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=0 ) out = x.flatten() index =
mgb.opr.concat(index0, index1, axis=0)
megengine._internal.opr.concat
# -*- 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 functools from typing import Iterable, List, Optional, Union import numpy as np import megengine._internal as mgb from megengine._internal import CompGraph, CompNode from ..core import zeros from ..core.graph import _use_default_if_none from ..core.tensor import Tensor, wrap_io_tensor from .elemwise import ceil from .utils import _decide_comp_node_and_comp_graph @wrap_io_tensor def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor: """ Broadcast a tensor to ``shape`` :param inp: The input tensor :param shape: The target shape :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3)) out = F.broadcast_to(data, (4, 2, 3)) print(out.numpy()) Outputs: .. testoutput:: [[[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]]] """ if isinstance(shape, int): shape = (shape,) return mgb.opr.broadcast(inp, shape) def _get_idx(index, axis): index_dims = len(index.imm_shape) idx = [] comp_node, comp_graph = _decide_comp_node_and_comp_graph(index) for i in range(index_dims): if i != axis: shape = [1] * index_dims shape[i] = index.axis_shape(i) arange = mgb.opr.linspace( 0, index.axis_shape(i) - 1, index.axis_shape(i), comp_node=comp_node, comp_graph=comp_graph, ) arange = ( arange.reshape(*shape) .broadcast(index.shape) .reshape(-1) .astype(np.int32) ) idx.append(arange) else: idx.append(index.reshape(-1)) return tuple(idx) @wrap_io_tensor def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor: r""" Gather data from :attr:`inp` on :attr:`axis` using :attr:`index`. For a 3-D tensor, the output is specified by:: out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0 out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1 out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2 if :attr:`inp` is an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i, then :attr:`index` must be an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and output will have the same size as :attr:`index`. :param inp: the source tensor :param axis: the axis along which to index :param index: the indices of elements to gather Examples: .. testcode:: import megengine.functional as F from megengine.core import tensor inp = tensor([ [1,2], [3,4], [5,6], ]) index = tensor([[0,2], [1,0]]) oup = F.gather(inp, 0, index) print(oup.numpy()) Outputs: .. testoutput:: [[1 6] [3 2]] """ input_shape = inp.imm_shape index_shape = index.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) if input_dims != index_dims: raise ValueError( "The index tensor must have same dimensions as input tensor, " "But the input dims:{}, the index dims:{}".format(input_dims, index_dims) ) if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(input_dims): if i != axis and input_shape[i] != index_shape[i]: raise ValueError( "The input {} and index {} must have the same size apart from axis {}".format( input_shape, index_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.advanced_indexing(inp)[idx].reshape( index.shape ) # pylint: disable=no-member @wrap_io_tensor def concat( inps: Iterable[Tensor], axis: int = 0, device: Optional[CompNode] = None, comp_graph: Optional[CompGraph] = None, ) -> Tensor: r""" Concat some tensors :param inps: Input tensors to concat :param axis: the dimension over which the tensors are concatenated. Default: 0 :param device: The comp node output on. Default: None :param comp_graph: The graph in which output is. Default: None :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3))) data2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3))) out = F.concat([data1, data2]) print(out.numpy()) Outputs: .. testoutput:: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.] [ 9. 10. 11.]] """ # Output buffer not supported return mgb.opr.concat( *list(inps), axis=axis, comp_node=device, comp_graph=comp_graph ) @wrap_io_tensor def scatter(inp: Tensor, axis: int, index: Tensor, source: Tensor) -> Tensor: r""" Writes all values from the tensor :attr:`source` into :attr:`inp` at the indices specified in the :attr:`index` tensor. For each value in :attr:`source`, its output index is specified by its index in :attr:`source` for ``axis != dimension`` and by the corresponding value in :attr:`index` for ``axis = dimension``. For a 3-D tensor, :attr:`inp` is updated as:: inp[index[i][j][k]][j][k] = source[i][j][k] # if axis == 0 inp[i][index[i][j][k]][k] = source[i][j][k] # if axis == 1 inp[i][j][index[i][j][k]] = source[i][j][k] # if axis == 2 :attr:`inp`, :attr:`index` and :attr:`source` should have same number of dimensions. It is also required that ``source.shape(d) <= inp.shape(d)`` and ``index.shape(d) == source.shape(d)`` for all dimensions ``d``. Moreover, the values of :attr:`index` must be between ``0`` and ``inp.shape(axis) - 1`` inclusive. .. note:: Please notice that, due to performance issues, the result is uncertain on the GPU device if scatter difference positions from source to the same destination position regard to index tensor. Show the case using the following examples, the oup[0][2] is maybe from source[0][2] which value is 0.2256 or source[1][2] which value is 0.5339 if set the index[1][2] from 1 to 0. :param inp: the inp tensor which to be scattered :param axis: the axis along which to index :param index: the indices of elements to scatter :param source: the source element(s) to scatter Examples: .. testcode:: import numpy as np import megengine.functional as F from megengine.core import tensor inp = tensor(np.zeros(shape=(3,5),dtype=np.float32)) source = tensor([[0.9935,0.9465,0.2256,0.8926,0.4396],[0.7723,0.0718,0.5939,0.357,0.4576]]) index = tensor([[0,2,0,2,1],[2,0,1,1,2]]) oup = F.scatter(inp, 0, index,source) print(oup.numpy()) Outputs: .. testoutput:: [[0.9935 0.0718 0.2256 0. 0. ] [0. 0. 0.5939 0.357 0.4396] [0.7723 0.9465 0. 0.8926 0.4576]] """ input_shape = inp.imm_shape index_shape = index.imm_shape source_shape = source.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) source_dims = len(source_shape) if input_dims != index_dims or input_dims != source_dims: raise ValueError("The input, source and index tensor must have same dimensions") if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(source_dims): if source_shape[i] > input_shape[i]: raise ValueError( "The each shape size for source {} must be less than or equal to input {} ".format( source_shape, input_shape ) ) for i in range(index_dims): if index_shape[i] != source_shape[i]: raise ValueError( "The each shape size for index {} must be equal to source {} ".format( index_shape, source_shape ) ) for i in range(index_dims): if i != axis and index_shape[i] > input_shape[i]: raise ValueError( "The index {} must be less than or equal to input {} size apart from axis {}".format( index_shape, input_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.set_advanced_indexing(inp, source.flatten())[idx] @wrap_io_tensor def where(mask: Tensor, x: Tensor, y: Tensor) -> Tensor: r""" Select elements either from Tensor x or Tensor y, according to mask. .. math:: \textrm{out}_i = x_i \textrm{ if } \textrm{mask}_i \textrm{ is True else } y_i :param mask: a mask used for choosing x or y :param x: the first choice :param y: the second choice Examples: .. testcode:: from megengine import tensor import megengine.functional as F mask = tensor(np.array([[1, 0], [0, 1]], dtype=np.int32)) x = tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)) y = tensor(np.array([[5, 6], [7, 8]], dtype=np.float32)) out = F.where(mask, x, y) print(out.numpy()) Outputs: .. testoutput:: [[1. 6.] [7. 4.]] """ v0, index0 = mgb.opr.cond_take( x, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=1 ) v1, index1 = mgb.opr.cond_take( y, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=0 ) out = x.flatten() index = mgb.opr.concat(index0, index1, axis=0) v =
mgb.opr.concat(v0, v1, axis=0)
megengine._internal.opr.concat
# -*- 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 functools from typing import Iterable, List, Optional, Union import numpy as np import megengine._internal as mgb from megengine._internal import CompGraph, CompNode from ..core import zeros from ..core.graph import _use_default_if_none from ..core.tensor import Tensor, wrap_io_tensor from .elemwise import ceil from .utils import _decide_comp_node_and_comp_graph @wrap_io_tensor def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor: """ Broadcast a tensor to ``shape`` :param inp: The input tensor :param shape: The target shape :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3)) out = F.broadcast_to(data, (4, 2, 3)) print(out.numpy()) Outputs: .. testoutput:: [[[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]]] """ if isinstance(shape, int): shape = (shape,) return mgb.opr.broadcast(inp, shape) def _get_idx(index, axis): index_dims = len(index.imm_shape) idx = [] comp_node, comp_graph = _decide_comp_node_and_comp_graph(index) for i in range(index_dims): if i != axis: shape = [1] * index_dims shape[i] = index.axis_shape(i) arange = mgb.opr.linspace( 0, index.axis_shape(i) - 1, index.axis_shape(i), comp_node=comp_node, comp_graph=comp_graph, ) arange = ( arange.reshape(*shape) .broadcast(index.shape) .reshape(-1) .astype(np.int32) ) idx.append(arange) else: idx.append(index.reshape(-1)) return tuple(idx) @wrap_io_tensor def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor: r""" Gather data from :attr:`inp` on :attr:`axis` using :attr:`index`. For a 3-D tensor, the output is specified by:: out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0 out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1 out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2 if :attr:`inp` is an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i, then :attr:`index` must be an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and output will have the same size as :attr:`index`. :param inp: the source tensor :param axis: the axis along which to index :param index: the indices of elements to gather Examples: .. testcode:: import megengine.functional as F from megengine.core import tensor inp = tensor([ [1,2], [3,4], [5,6], ]) index = tensor([[0,2], [1,0]]) oup = F.gather(inp, 0, index) print(oup.numpy()) Outputs: .. testoutput:: [[1 6] [3 2]] """ input_shape = inp.imm_shape index_shape = index.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) if input_dims != index_dims: raise ValueError( "The index tensor must have same dimensions as input tensor, " "But the input dims:{}, the index dims:{}".format(input_dims, index_dims) ) if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(input_dims): if i != axis and input_shape[i] != index_shape[i]: raise ValueError( "The input {} and index {} must have the same size apart from axis {}".format( input_shape, index_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.advanced_indexing(inp)[idx].reshape( index.shape ) # pylint: disable=no-member @wrap_io_tensor def concat( inps: Iterable[Tensor], axis: int = 0, device: Optional[CompNode] = None, comp_graph: Optional[CompGraph] = None, ) -> Tensor: r""" Concat some tensors :param inps: Input tensors to concat :param axis: the dimension over which the tensors are concatenated. Default: 0 :param device: The comp node output on. Default: None :param comp_graph: The graph in which output is. Default: None :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3))) data2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3))) out = F.concat([data1, data2]) print(out.numpy()) Outputs: .. testoutput:: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.] [ 9. 10. 11.]] """ # Output buffer not supported return mgb.opr.concat( *list(inps), axis=axis, comp_node=device, comp_graph=comp_graph ) @wrap_io_tensor def scatter(inp: Tensor, axis: int, index: Tensor, source: Tensor) -> Tensor: r""" Writes all values from the tensor :attr:`source` into :attr:`inp` at the indices specified in the :attr:`index` tensor. For each value in :attr:`source`, its output index is specified by its index in :attr:`source` for ``axis != dimension`` and by the corresponding value in :attr:`index` for ``axis = dimension``. For a 3-D tensor, :attr:`inp` is updated as:: inp[index[i][j][k]][j][k] = source[i][j][k] # if axis == 0 inp[i][index[i][j][k]][k] = source[i][j][k] # if axis == 1 inp[i][j][index[i][j][k]] = source[i][j][k] # if axis == 2 :attr:`inp`, :attr:`index` and :attr:`source` should have same number of dimensions. It is also required that ``source.shape(d) <= inp.shape(d)`` and ``index.shape(d) == source.shape(d)`` for all dimensions ``d``. Moreover, the values of :attr:`index` must be between ``0`` and ``inp.shape(axis) - 1`` inclusive. .. note:: Please notice that, due to performance issues, the result is uncertain on the GPU device if scatter difference positions from source to the same destination position regard to index tensor. Show the case using the following examples, the oup[0][2] is maybe from source[0][2] which value is 0.2256 or source[1][2] which value is 0.5339 if set the index[1][2] from 1 to 0. :param inp: the inp tensor which to be scattered :param axis: the axis along which to index :param index: the indices of elements to scatter :param source: the source element(s) to scatter Examples: .. testcode:: import numpy as np import megengine.functional as F from megengine.core import tensor inp = tensor(np.zeros(shape=(3,5),dtype=np.float32)) source = tensor([[0.9935,0.9465,0.2256,0.8926,0.4396],[0.7723,0.0718,0.5939,0.357,0.4576]]) index = tensor([[0,2,0,2,1],[2,0,1,1,2]]) oup = F.scatter(inp, 0, index,source) print(oup.numpy()) Outputs: .. testoutput:: [[0.9935 0.0718 0.2256 0. 0. ] [0. 0. 0.5939 0.357 0.4396] [0.7723 0.9465 0. 0.8926 0.4576]] """ input_shape = inp.imm_shape index_shape = index.imm_shape source_shape = source.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) source_dims = len(source_shape) if input_dims != index_dims or input_dims != source_dims: raise ValueError("The input, source and index tensor must have same dimensions") if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(source_dims): if source_shape[i] > input_shape[i]: raise ValueError( "The each shape size for source {} must be less than or equal to input {} ".format( source_shape, input_shape ) ) for i in range(index_dims): if index_shape[i] != source_shape[i]: raise ValueError( "The each shape size for index {} must be equal to source {} ".format( index_shape, source_shape ) ) for i in range(index_dims): if i != axis and index_shape[i] > input_shape[i]: raise ValueError( "The index {} must be less than or equal to input {} size apart from axis {}".format( index_shape, input_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.set_advanced_indexing(inp, source.flatten())[idx] @wrap_io_tensor def where(mask: Tensor, x: Tensor, y: Tensor) -> Tensor: r""" Select elements either from Tensor x or Tensor y, according to mask. .. math:: \textrm{out}_i = x_i \textrm{ if } \textrm{mask}_i \textrm{ is True else } y_i :param mask: a mask used for choosing x or y :param x: the first choice :param y: the second choice Examples: .. testcode:: from megengine import tensor import megengine.functional as F mask = tensor(np.array([[1, 0], [0, 1]], dtype=np.int32)) x = tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)) y = tensor(np.array([[5, 6], [7, 8]], dtype=np.float32)) out = F.where(mask, x, y) print(out.numpy()) Outputs: .. testoutput:: [[1. 6.] [7. 4.]] """ v0, index0 = mgb.opr.cond_take( x, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=1 ) v1, index1 = mgb.opr.cond_take( y, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=0 ) out = x.flatten() index = mgb.opr.concat(index0, index1, axis=0) v = mgb.opr.concat(v0, v1, axis=0) out = mgb.opr.set_advanced_indexing(out, v)[index] out = out.reshape(x.shape) return out @wrap_io_tensor def cond_take(mask: Tensor, x: Tensor, val=1) -> Tensor: r""" Take elements from data if specific condition is satisfied on mask. This operator has two outputs: the first is the elements taken, and the second is the indices corresponding to those elements; they are both 1-dimensional. High-dimension input would first be flattened. :param mask: condition param; must be the same shape with data :param x: input tensor from which to take elements :param val: value to be compared to by mode Examples: .. testcode:: from megengine import tensor import megengine.functional as F mask = tensor(np.array([[1, 0], [0, 1]], dtype=np.int32)) x = tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)) v, index = F.cond_take(mask, x, 1) print(v, index) Outputs: .. testoutput:: Tensor([1. 4.]) Tensor([0 3], dtype=int32) """ v, index = mgb.opr.cond_take( x, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=val ) return v, index def shapeof(x: Tensor, axis=None): r""" The shape of input tensor. """ return x.shapeof(axis=axis) @wrap_io_tensor def dimshuffle(inp: Tensor, pattern: Iterable[int]) -> Tensor: r""" Swap shapes and strides according to given pattern :param inp: Input tensor :param pattern: a list of integers including 0, 1, ... , ``ndim``-1, and any number of ``'x'`` char in dimensions where this tensor should be broadcasted. For examples: * (``'x'``) -> make a 0d (scalar) into a 1d vector * (0, 1) -> identity for 2d vectors * (1, 0) -> inverts the first and second dimensions * (``'x'``, 0) -> make a row out of a 1d vector (N to 1xN) * (0, ``'x'``) -> make a column out of a 1d vector (N to Nx1) * (2, 0, 1) -> AxBxC to CxAxB * (0, ``'x'``, 1) -> AxB to Ax1xB * (1, ``'x'``, 0) -> AxB to Bx1xA * (1,) -> This remove dimensions 0. It must be a broadcastable dimension (1xA to A) :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor(np.array([[1, 1], [0, 0]], dtype=np.int32)) out = F.dimshuffle(x, (1, 0)) print(out.numpy()) Outputs: .. testoutput:: [[1 0] [1 0]] """ return
mgb.opr.dimshuffle(inp, pattern)
megengine._internal.opr.dimshuffle
# -*- 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 functools from typing import Iterable, List, Optional, Union import numpy as np import megengine._internal as mgb from megengine._internal import CompGraph, CompNode from ..core import zeros from ..core.graph import _use_default_if_none from ..core.tensor import Tensor, wrap_io_tensor from .elemwise import ceil from .utils import _decide_comp_node_and_comp_graph @wrap_io_tensor def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor: """ Broadcast a tensor to ``shape`` :param inp: The input tensor :param shape: The target shape :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3)) out = F.broadcast_to(data, (4, 2, 3)) print(out.numpy()) Outputs: .. testoutput:: [[[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]]] """ if isinstance(shape, int): shape = (shape,) return mgb.opr.broadcast(inp, shape) def _get_idx(index, axis): index_dims = len(index.imm_shape) idx = [] comp_node, comp_graph = _decide_comp_node_and_comp_graph(index) for i in range(index_dims): if i != axis: shape = [1] * index_dims shape[i] = index.axis_shape(i) arange = mgb.opr.linspace( 0, index.axis_shape(i) - 1, index.axis_shape(i), comp_node=comp_node, comp_graph=comp_graph, ) arange = ( arange.reshape(*shape) .broadcast(index.shape) .reshape(-1) .astype(np.int32) ) idx.append(arange) else: idx.append(index.reshape(-1)) return tuple(idx) @wrap_io_tensor def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor: r""" Gather data from :attr:`inp` on :attr:`axis` using :attr:`index`. For a 3-D tensor, the output is specified by:: out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0 out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1 out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2 if :attr:`inp` is an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i, then :attr:`index` must be an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and output will have the same size as :attr:`index`. :param inp: the source tensor :param axis: the axis along which to index :param index: the indices of elements to gather Examples: .. testcode:: import megengine.functional as F from megengine.core import tensor inp = tensor([ [1,2], [3,4], [5,6], ]) index = tensor([[0,2], [1,0]]) oup = F.gather(inp, 0, index) print(oup.numpy()) Outputs: .. testoutput:: [[1 6] [3 2]] """ input_shape = inp.imm_shape index_shape = index.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) if input_dims != index_dims: raise ValueError( "The index tensor must have same dimensions as input tensor, " "But the input dims:{}, the index dims:{}".format(input_dims, index_dims) ) if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(input_dims): if i != axis and input_shape[i] != index_shape[i]: raise ValueError( "The input {} and index {} must have the same size apart from axis {}".format( input_shape, index_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.advanced_indexing(inp)[idx].reshape( index.shape ) # pylint: disable=no-member @wrap_io_tensor def concat( inps: Iterable[Tensor], axis: int = 0, device: Optional[CompNode] = None, comp_graph: Optional[CompGraph] = None, ) -> Tensor: r""" Concat some tensors :param inps: Input tensors to concat :param axis: the dimension over which the tensors are concatenated. Default: 0 :param device: The comp node output on. Default: None :param comp_graph: The graph in which output is. Default: None :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3))) data2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3))) out = F.concat([data1, data2]) print(out.numpy()) Outputs: .. testoutput:: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.] [ 9. 10. 11.]] """ # Output buffer not supported return mgb.opr.concat( *list(inps), axis=axis, comp_node=device, comp_graph=comp_graph ) @wrap_io_tensor def scatter(inp: Tensor, axis: int, index: Tensor, source: Tensor) -> Tensor: r""" Writes all values from the tensor :attr:`source` into :attr:`inp` at the indices specified in the :attr:`index` tensor. For each value in :attr:`source`, its output index is specified by its index in :attr:`source` for ``axis != dimension`` and by the corresponding value in :attr:`index` for ``axis = dimension``. For a 3-D tensor, :attr:`inp` is updated as:: inp[index[i][j][k]][j][k] = source[i][j][k] # if axis == 0 inp[i][index[i][j][k]][k] = source[i][j][k] # if axis == 1 inp[i][j][index[i][j][k]] = source[i][j][k] # if axis == 2 :attr:`inp`, :attr:`index` and :attr:`source` should have same number of dimensions. It is also required that ``source.shape(d) <= inp.shape(d)`` and ``index.shape(d) == source.shape(d)`` for all dimensions ``d``. Moreover, the values of :attr:`index` must be between ``0`` and ``inp.shape(axis) - 1`` inclusive. .. note:: Please notice that, due to performance issues, the result is uncertain on the GPU device if scatter difference positions from source to the same destination position regard to index tensor. Show the case using the following examples, the oup[0][2] is maybe from source[0][2] which value is 0.2256 or source[1][2] which value is 0.5339 if set the index[1][2] from 1 to 0. :param inp: the inp tensor which to be scattered :param axis: the axis along which to index :param index: the indices of elements to scatter :param source: the source element(s) to scatter Examples: .. testcode:: import numpy as np import megengine.functional as F from megengine.core import tensor inp = tensor(np.zeros(shape=(3,5),dtype=np.float32)) source = tensor([[0.9935,0.9465,0.2256,0.8926,0.4396],[0.7723,0.0718,0.5939,0.357,0.4576]]) index = tensor([[0,2,0,2,1],[2,0,1,1,2]]) oup = F.scatter(inp, 0, index,source) print(oup.numpy()) Outputs: .. testoutput:: [[0.9935 0.0718 0.2256 0. 0. ] [0. 0. 0.5939 0.357 0.4396] [0.7723 0.9465 0. 0.8926 0.4576]] """ input_shape = inp.imm_shape index_shape = index.imm_shape source_shape = source.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) source_dims = len(source_shape) if input_dims != index_dims or input_dims != source_dims: raise ValueError("The input, source and index tensor must have same dimensions") if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(source_dims): if source_shape[i] > input_shape[i]: raise ValueError( "The each shape size for source {} must be less than or equal to input {} ".format( source_shape, input_shape ) ) for i in range(index_dims): if index_shape[i] != source_shape[i]: raise ValueError( "The each shape size for index {} must be equal to source {} ".format( index_shape, source_shape ) ) for i in range(index_dims): if i != axis and index_shape[i] > input_shape[i]: raise ValueError( "The index {} must be less than or equal to input {} size apart from axis {}".format( index_shape, input_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.set_advanced_indexing(inp, source.flatten())[idx] @wrap_io_tensor def where(mask: Tensor, x: Tensor, y: Tensor) -> Tensor: r""" Select elements either from Tensor x or Tensor y, according to mask. .. math:: \textrm{out}_i = x_i \textrm{ if } \textrm{mask}_i \textrm{ is True else } y_i :param mask: a mask used for choosing x or y :param x: the first choice :param y: the second choice Examples: .. testcode:: from megengine import tensor import megengine.functional as F mask = tensor(np.array([[1, 0], [0, 1]], dtype=np.int32)) x = tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)) y = tensor(np.array([[5, 6], [7, 8]], dtype=np.float32)) out = F.where(mask, x, y) print(out.numpy()) Outputs: .. testoutput:: [[1. 6.] [7. 4.]] """ v0, index0 = mgb.opr.cond_take( x, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=1 ) v1, index1 = mgb.opr.cond_take( y, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=0 ) out = x.flatten() index = mgb.opr.concat(index0, index1, axis=0) v = mgb.opr.concat(v0, v1, axis=0) out = mgb.opr.set_advanced_indexing(out, v)[index] out = out.reshape(x.shape) return out @wrap_io_tensor def cond_take(mask: Tensor, x: Tensor, val=1) -> Tensor: r""" Take elements from data if specific condition is satisfied on mask. This operator has two outputs: the first is the elements taken, and the second is the indices corresponding to those elements; they are both 1-dimensional. High-dimension input would first be flattened. :param mask: condition param; must be the same shape with data :param x: input tensor from which to take elements :param val: value to be compared to by mode Examples: .. testcode:: from megengine import tensor import megengine.functional as F mask = tensor(np.array([[1, 0], [0, 1]], dtype=np.int32)) x = tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)) v, index = F.cond_take(mask, x, 1) print(v, index) Outputs: .. testoutput:: Tensor([1. 4.]) Tensor([0 3], dtype=int32) """ v, index = mgb.opr.cond_take( x, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=val ) return v, index def shapeof(x: Tensor, axis=None): r""" The shape of input tensor. """ return x.shapeof(axis=axis) @wrap_io_tensor def dimshuffle(inp: Tensor, pattern: Iterable[int]) -> Tensor: r""" Swap shapes and strides according to given pattern :param inp: Input tensor :param pattern: a list of integers including 0, 1, ... , ``ndim``-1, and any number of ``'x'`` char in dimensions where this tensor should be broadcasted. For examples: * (``'x'``) -> make a 0d (scalar) into a 1d vector * (0, 1) -> identity for 2d vectors * (1, 0) -> inverts the first and second dimensions * (``'x'``, 0) -> make a row out of a 1d vector (N to 1xN) * (0, ``'x'``) -> make a column out of a 1d vector (N to Nx1) * (2, 0, 1) -> AxBxC to CxAxB * (0, ``'x'``, 1) -> AxB to Ax1xB * (1, ``'x'``, 0) -> AxB to Bx1xA * (1,) -> This remove dimensions 0. It must be a broadcastable dimension (1xA to A) :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor(np.array([[1, 1], [0, 0]], dtype=np.int32)) out = F.dimshuffle(x, (1, 0)) print(out.numpy()) Outputs: .. testoutput:: [[1 0] [1 0]] """ return mgb.opr.dimshuffle(inp, pattern) @wrap_io_tensor def reshape(inp: Tensor, target_shape: Iterable[int]) -> Tensor: r""" Reshape a tensor to given target shape; total number of logical elements must remain unchanged :param inp: Input tensor :param target_shape: target shape, the components would be concatenated to form the target shape, and it can contain an element of -1 representing unspec_axis. Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor(np.arange(12, dtype=np.int32)) out = F.reshape(x, (3, 2, 2)) print(out.numpy()) Outputs: .. testoutput:: [[[ 0 1] [ 2 3]] [[ 4 5] [ 6 7]] [[ 8 9] [10 11]]] """ return
mgb.opr.reshape(inp, target_shape)
megengine._internal.opr.reshape
# -*- 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 functools from typing import Iterable, List, Optional, Union import numpy as np import megengine._internal as mgb from megengine._internal import CompGraph, CompNode from ..core import zeros from ..core.graph import _use_default_if_none from ..core.tensor import Tensor, wrap_io_tensor from .elemwise import ceil from .utils import _decide_comp_node_and_comp_graph @wrap_io_tensor def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor: """ Broadcast a tensor to ``shape`` :param inp: The input tensor :param shape: The target shape :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3)) out = F.broadcast_to(data, (4, 2, 3)) print(out.numpy()) Outputs: .. testoutput:: [[[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]]] """ if isinstance(shape, int): shape = (shape,) return mgb.opr.broadcast(inp, shape) def _get_idx(index, axis): index_dims = len(index.imm_shape) idx = [] comp_node, comp_graph = _decide_comp_node_and_comp_graph(index) for i in range(index_dims): if i != axis: shape = [1] * index_dims shape[i] = index.axis_shape(i) arange = mgb.opr.linspace( 0, index.axis_shape(i) - 1, index.axis_shape(i), comp_node=comp_node, comp_graph=comp_graph, ) arange = ( arange.reshape(*shape) .broadcast(index.shape) .reshape(-1) .astype(np.int32) ) idx.append(arange) else: idx.append(index.reshape(-1)) return tuple(idx) @wrap_io_tensor def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor: r""" Gather data from :attr:`inp` on :attr:`axis` using :attr:`index`. For a 3-D tensor, the output is specified by:: out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0 out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1 out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2 if :attr:`inp` is an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i, then :attr:`index` must be an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and output will have the same size as :attr:`index`. :param inp: the source tensor :param axis: the axis along which to index :param index: the indices of elements to gather Examples: .. testcode:: import megengine.functional as F from megengine.core import tensor inp = tensor([ [1,2], [3,4], [5,6], ]) index = tensor([[0,2], [1,0]]) oup = F.gather(inp, 0, index) print(oup.numpy()) Outputs: .. testoutput:: [[1 6] [3 2]] """ input_shape = inp.imm_shape index_shape = index.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) if input_dims != index_dims: raise ValueError( "The index tensor must have same dimensions as input tensor, " "But the input dims:{}, the index dims:{}".format(input_dims, index_dims) ) if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(input_dims): if i != axis and input_shape[i] != index_shape[i]: raise ValueError( "The input {} and index {} must have the same size apart from axis {}".format( input_shape, index_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.advanced_indexing(inp)[idx].reshape( index.shape ) # pylint: disable=no-member @wrap_io_tensor def concat( inps: Iterable[Tensor], axis: int = 0, device: Optional[CompNode] = None, comp_graph: Optional[CompGraph] = None, ) -> Tensor: r""" Concat some tensors :param inps: Input tensors to concat :param axis: the dimension over which the tensors are concatenated. Default: 0 :param device: The comp node output on. Default: None :param comp_graph: The graph in which output is. Default: None :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3))) data2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3))) out = F.concat([data1, data2]) print(out.numpy()) Outputs: .. testoutput:: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.] [ 9. 10. 11.]] """ # Output buffer not supported return mgb.opr.concat( *list(inps), axis=axis, comp_node=device, comp_graph=comp_graph ) @wrap_io_tensor def scatter(inp: Tensor, axis: int, index: Tensor, source: Tensor) -> Tensor: r""" Writes all values from the tensor :attr:`source` into :attr:`inp` at the indices specified in the :attr:`index` tensor. For each value in :attr:`source`, its output index is specified by its index in :attr:`source` for ``axis != dimension`` and by the corresponding value in :attr:`index` for ``axis = dimension``. For a 3-D tensor, :attr:`inp` is updated as:: inp[index[i][j][k]][j][k] = source[i][j][k] # if axis == 0 inp[i][index[i][j][k]][k] = source[i][j][k] # if axis == 1 inp[i][j][index[i][j][k]] = source[i][j][k] # if axis == 2 :attr:`inp`, :attr:`index` and :attr:`source` should have same number of dimensions. It is also required that ``source.shape(d) <= inp.shape(d)`` and ``index.shape(d) == source.shape(d)`` for all dimensions ``d``. Moreover, the values of :attr:`index` must be between ``0`` and ``inp.shape(axis) - 1`` inclusive. .. note:: Please notice that, due to performance issues, the result is uncertain on the GPU device if scatter difference positions from source to the same destination position regard to index tensor. Show the case using the following examples, the oup[0][2] is maybe from source[0][2] which value is 0.2256 or source[1][2] which value is 0.5339 if set the index[1][2] from 1 to 0. :param inp: the inp tensor which to be scattered :param axis: the axis along which to index :param index: the indices of elements to scatter :param source: the source element(s) to scatter Examples: .. testcode:: import numpy as np import megengine.functional as F from megengine.core import tensor inp = tensor(np.zeros(shape=(3,5),dtype=np.float32)) source = tensor([[0.9935,0.9465,0.2256,0.8926,0.4396],[0.7723,0.0718,0.5939,0.357,0.4576]]) index = tensor([[0,2,0,2,1],[2,0,1,1,2]]) oup = F.scatter(inp, 0, index,source) print(oup.numpy()) Outputs: .. testoutput:: [[0.9935 0.0718 0.2256 0. 0. ] [0. 0. 0.5939 0.357 0.4396] [0.7723 0.9465 0. 0.8926 0.4576]] """ input_shape = inp.imm_shape index_shape = index.imm_shape source_shape = source.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) source_dims = len(source_shape) if input_dims != index_dims or input_dims != source_dims: raise ValueError("The input, source and index tensor must have same dimensions") if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(source_dims): if source_shape[i] > input_shape[i]: raise ValueError( "The each shape size for source {} must be less than or equal to input {} ".format( source_shape, input_shape ) ) for i in range(index_dims): if index_shape[i] != source_shape[i]: raise ValueError( "The each shape size for index {} must be equal to source {} ".format( index_shape, source_shape ) ) for i in range(index_dims): if i != axis and index_shape[i] > input_shape[i]: raise ValueError( "The index {} must be less than or equal to input {} size apart from axis {}".format( index_shape, input_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.set_advanced_indexing(inp, source.flatten())[idx] @wrap_io_tensor def where(mask: Tensor, x: Tensor, y: Tensor) -> Tensor: r""" Select elements either from Tensor x or Tensor y, according to mask. .. math:: \textrm{out}_i = x_i \textrm{ if } \textrm{mask}_i \textrm{ is True else } y_i :param mask: a mask used for choosing x or y :param x: the first choice :param y: the second choice Examples: .. testcode:: from megengine import tensor import megengine.functional as F mask = tensor(np.array([[1, 0], [0, 1]], dtype=np.int32)) x = tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)) y = tensor(np.array([[5, 6], [7, 8]], dtype=np.float32)) out = F.where(mask, x, y) print(out.numpy()) Outputs: .. testoutput:: [[1. 6.] [7. 4.]] """ v0, index0 = mgb.opr.cond_take( x, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=1 ) v1, index1 = mgb.opr.cond_take( y, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=0 ) out = x.flatten() index = mgb.opr.concat(index0, index1, axis=0) v = mgb.opr.concat(v0, v1, axis=0) out = mgb.opr.set_advanced_indexing(out, v)[index] out = out.reshape(x.shape) return out @wrap_io_tensor def cond_take(mask: Tensor, x: Tensor, val=1) -> Tensor: r""" Take elements from data if specific condition is satisfied on mask. This operator has two outputs: the first is the elements taken, and the second is the indices corresponding to those elements; they are both 1-dimensional. High-dimension input would first be flattened. :param mask: condition param; must be the same shape with data :param x: input tensor from which to take elements :param val: value to be compared to by mode Examples: .. testcode:: from megengine import tensor import megengine.functional as F mask = tensor(np.array([[1, 0], [0, 1]], dtype=np.int32)) x = tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)) v, index = F.cond_take(mask, x, 1) print(v, index) Outputs: .. testoutput:: Tensor([1. 4.]) Tensor([0 3], dtype=int32) """ v, index = mgb.opr.cond_take( x, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=val ) return v, index def shapeof(x: Tensor, axis=None): r""" The shape of input tensor. """ return x.shapeof(axis=axis) @wrap_io_tensor def dimshuffle(inp: Tensor, pattern: Iterable[int]) -> Tensor: r""" Swap shapes and strides according to given pattern :param inp: Input tensor :param pattern: a list of integers including 0, 1, ... , ``ndim``-1, and any number of ``'x'`` char in dimensions where this tensor should be broadcasted. For examples: * (``'x'``) -> make a 0d (scalar) into a 1d vector * (0, 1) -> identity for 2d vectors * (1, 0) -> inverts the first and second dimensions * (``'x'``, 0) -> make a row out of a 1d vector (N to 1xN) * (0, ``'x'``) -> make a column out of a 1d vector (N to Nx1) * (2, 0, 1) -> AxBxC to CxAxB * (0, ``'x'``, 1) -> AxB to Ax1xB * (1, ``'x'``, 0) -> AxB to Bx1xA * (1,) -> This remove dimensions 0. It must be a broadcastable dimension (1xA to A) :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor(np.array([[1, 1], [0, 0]], dtype=np.int32)) out = F.dimshuffle(x, (1, 0)) print(out.numpy()) Outputs: .. testoutput:: [[1 0] [1 0]] """ return mgb.opr.dimshuffle(inp, pattern) @wrap_io_tensor def reshape(inp: Tensor, target_shape: Iterable[int]) -> Tensor: r""" Reshape a tensor to given target shape; total number of logical elements must remain unchanged :param inp: Input tensor :param target_shape: target shape, the components would be concatenated to form the target shape, and it can contain an element of -1 representing unspec_axis. Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor(np.arange(12, dtype=np.int32)) out = F.reshape(x, (3, 2, 2)) print(out.numpy()) Outputs: .. testoutput:: [[[ 0 1] [ 2 3]] [[ 4 5] [ 6 7]] [[ 8 9] [10 11]]] """ return mgb.opr.reshape(inp, target_shape) def transpose(inp: Tensor, pattern: Iterable[int]) -> Tensor: r"""Equivalent to :func:`dimshuffle` """ return dimshuffle(inp, pattern) @wrap_io_tensor def add_axis(inp: Tensor, axis: int) -> Tensor: r""" Add dimension before given axis. :param inp: Input tensor :param axis: Place of new axes :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor([1, 2]) out = F.add_axis(x, 0) print(out.shape) Outputs: .. testoutput:: (1, 2) """ if not isinstance(axis, int): raise ValueError("axis must be int, but got type:{}".format(type(axis))) return
mgb.opr.add_axis(inp, axis)
megengine._internal.opr.add_axis
# -*- 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 functools from typing import Iterable, List, Optional, Union import numpy as np import megengine._internal as mgb from megengine._internal import CompGraph, CompNode from ..core import zeros from ..core.graph import _use_default_if_none from ..core.tensor import Tensor, wrap_io_tensor from .elemwise import ceil from .utils import _decide_comp_node_and_comp_graph @wrap_io_tensor def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor: """ Broadcast a tensor to ``shape`` :param inp: The input tensor :param shape: The target shape :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3)) out = F.broadcast_to(data, (4, 2, 3)) print(out.numpy()) Outputs: .. testoutput:: [[[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]]] """ if isinstance(shape, int): shape = (shape,) return mgb.opr.broadcast(inp, shape) def _get_idx(index, axis): index_dims = len(index.imm_shape) idx = [] comp_node, comp_graph = _decide_comp_node_and_comp_graph(index) for i in range(index_dims): if i != axis: shape = [1] * index_dims shape[i] = index.axis_shape(i) arange = mgb.opr.linspace( 0, index.axis_shape(i) - 1, index.axis_shape(i), comp_node=comp_node, comp_graph=comp_graph, ) arange = ( arange.reshape(*shape) .broadcast(index.shape) .reshape(-1) .astype(np.int32) ) idx.append(arange) else: idx.append(index.reshape(-1)) return tuple(idx) @wrap_io_tensor def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor: r""" Gather data from :attr:`inp` on :attr:`axis` using :attr:`index`. For a 3-D tensor, the output is specified by:: out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0 out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1 out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2 if :attr:`inp` is an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i, then :attr:`index` must be an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and output will have the same size as :attr:`index`. :param inp: the source tensor :param axis: the axis along which to index :param index: the indices of elements to gather Examples: .. testcode:: import megengine.functional as F from megengine.core import tensor inp = tensor([ [1,2], [3,4], [5,6], ]) index = tensor([[0,2], [1,0]]) oup = F.gather(inp, 0, index) print(oup.numpy()) Outputs: .. testoutput:: [[1 6] [3 2]] """ input_shape = inp.imm_shape index_shape = index.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) if input_dims != index_dims: raise ValueError( "The index tensor must have same dimensions as input tensor, " "But the input dims:{}, the index dims:{}".format(input_dims, index_dims) ) if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(input_dims): if i != axis and input_shape[i] != index_shape[i]: raise ValueError( "The input {} and index {} must have the same size apart from axis {}".format( input_shape, index_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.advanced_indexing(inp)[idx].reshape( index.shape ) # pylint: disable=no-member @wrap_io_tensor def concat( inps: Iterable[Tensor], axis: int = 0, device: Optional[CompNode] = None, comp_graph: Optional[CompGraph] = None, ) -> Tensor: r""" Concat some tensors :param inps: Input tensors to concat :param axis: the dimension over which the tensors are concatenated. Default: 0 :param device: The comp node output on. Default: None :param comp_graph: The graph in which output is. Default: None :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3))) data2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3))) out = F.concat([data1, data2]) print(out.numpy()) Outputs: .. testoutput:: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.] [ 9. 10. 11.]] """ # Output buffer not supported return mgb.opr.concat( *list(inps), axis=axis, comp_node=device, comp_graph=comp_graph ) @wrap_io_tensor def scatter(inp: Tensor, axis: int, index: Tensor, source: Tensor) -> Tensor: r""" Writes all values from the tensor :attr:`source` into :attr:`inp` at the indices specified in the :attr:`index` tensor. For each value in :attr:`source`, its output index is specified by its index in :attr:`source` for ``axis != dimension`` and by the corresponding value in :attr:`index` for ``axis = dimension``. For a 3-D tensor, :attr:`inp` is updated as:: inp[index[i][j][k]][j][k] = source[i][j][k] # if axis == 0 inp[i][index[i][j][k]][k] = source[i][j][k] # if axis == 1 inp[i][j][index[i][j][k]] = source[i][j][k] # if axis == 2 :attr:`inp`, :attr:`index` and :attr:`source` should have same number of dimensions. It is also required that ``source.shape(d) <= inp.shape(d)`` and ``index.shape(d) == source.shape(d)`` for all dimensions ``d``. Moreover, the values of :attr:`index` must be between ``0`` and ``inp.shape(axis) - 1`` inclusive. .. note:: Please notice that, due to performance issues, the result is uncertain on the GPU device if scatter difference positions from source to the same destination position regard to index tensor. Show the case using the following examples, the oup[0][2] is maybe from source[0][2] which value is 0.2256 or source[1][2] which value is 0.5339 if set the index[1][2] from 1 to 0. :param inp: the inp tensor which to be scattered :param axis: the axis along which to index :param index: the indices of elements to scatter :param source: the source element(s) to scatter Examples: .. testcode:: import numpy as np import megengine.functional as F from megengine.core import tensor inp = tensor(np.zeros(shape=(3,5),dtype=np.float32)) source = tensor([[0.9935,0.9465,0.2256,0.8926,0.4396],[0.7723,0.0718,0.5939,0.357,0.4576]]) index = tensor([[0,2,0,2,1],[2,0,1,1,2]]) oup = F.scatter(inp, 0, index,source) print(oup.numpy()) Outputs: .. testoutput:: [[0.9935 0.0718 0.2256 0. 0. ] [0. 0. 0.5939 0.357 0.4396] [0.7723 0.9465 0. 0.8926 0.4576]] """ input_shape = inp.imm_shape index_shape = index.imm_shape source_shape = source.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) source_dims = len(source_shape) if input_dims != index_dims or input_dims != source_dims: raise ValueError("The input, source and index tensor must have same dimensions") if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(source_dims): if source_shape[i] > input_shape[i]: raise ValueError( "The each shape size for source {} must be less than or equal to input {} ".format( source_shape, input_shape ) ) for i in range(index_dims): if index_shape[i] != source_shape[i]: raise ValueError( "The each shape size for index {} must be equal to source {} ".format( index_shape, source_shape ) ) for i in range(index_dims): if i != axis and index_shape[i] > input_shape[i]: raise ValueError( "The index {} must be less than or equal to input {} size apart from axis {}".format( index_shape, input_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.set_advanced_indexing(inp, source.flatten())[idx] @wrap_io_tensor def where(mask: Tensor, x: Tensor, y: Tensor) -> Tensor: r""" Select elements either from Tensor x or Tensor y, according to mask. .. math:: \textrm{out}_i = x_i \textrm{ if } \textrm{mask}_i \textrm{ is True else } y_i :param mask: a mask used for choosing x or y :param x: the first choice :param y: the second choice Examples: .. testcode:: from megengine import tensor import megengine.functional as F mask = tensor(np.array([[1, 0], [0, 1]], dtype=np.int32)) x = tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)) y = tensor(np.array([[5, 6], [7, 8]], dtype=np.float32)) out = F.where(mask, x, y) print(out.numpy()) Outputs: .. testoutput:: [[1. 6.] [7. 4.]] """ v0, index0 = mgb.opr.cond_take( x, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=1 ) v1, index1 = mgb.opr.cond_take( y, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=0 ) out = x.flatten() index = mgb.opr.concat(index0, index1, axis=0) v = mgb.opr.concat(v0, v1, axis=0) out = mgb.opr.set_advanced_indexing(out, v)[index] out = out.reshape(x.shape) return out @wrap_io_tensor def cond_take(mask: Tensor, x: Tensor, val=1) -> Tensor: r""" Take elements from data if specific condition is satisfied on mask. This operator has two outputs: the first is the elements taken, and the second is the indices corresponding to those elements; they are both 1-dimensional. High-dimension input would first be flattened. :param mask: condition param; must be the same shape with data :param x: input tensor from which to take elements :param val: value to be compared to by mode Examples: .. testcode:: from megengine import tensor import megengine.functional as F mask = tensor(np.array([[1, 0], [0, 1]], dtype=np.int32)) x = tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)) v, index = F.cond_take(mask, x, 1) print(v, index) Outputs: .. testoutput:: Tensor([1. 4.]) Tensor([0 3], dtype=int32) """ v, index = mgb.opr.cond_take( x, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=val ) return v, index def shapeof(x: Tensor, axis=None): r""" The shape of input tensor. """ return x.shapeof(axis=axis) @wrap_io_tensor def dimshuffle(inp: Tensor, pattern: Iterable[int]) -> Tensor: r""" Swap shapes and strides according to given pattern :param inp: Input tensor :param pattern: a list of integers including 0, 1, ... , ``ndim``-1, and any number of ``'x'`` char in dimensions where this tensor should be broadcasted. For examples: * (``'x'``) -> make a 0d (scalar) into a 1d vector * (0, 1) -> identity for 2d vectors * (1, 0) -> inverts the first and second dimensions * (``'x'``, 0) -> make a row out of a 1d vector (N to 1xN) * (0, ``'x'``) -> make a column out of a 1d vector (N to Nx1) * (2, 0, 1) -> AxBxC to CxAxB * (0, ``'x'``, 1) -> AxB to Ax1xB * (1, ``'x'``, 0) -> AxB to Bx1xA * (1,) -> This remove dimensions 0. It must be a broadcastable dimension (1xA to A) :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor(np.array([[1, 1], [0, 0]], dtype=np.int32)) out = F.dimshuffle(x, (1, 0)) print(out.numpy()) Outputs: .. testoutput:: [[1 0] [1 0]] """ return mgb.opr.dimshuffle(inp, pattern) @wrap_io_tensor def reshape(inp: Tensor, target_shape: Iterable[int]) -> Tensor: r""" Reshape a tensor to given target shape; total number of logical elements must remain unchanged :param inp: Input tensor :param target_shape: target shape, the components would be concatenated to form the target shape, and it can contain an element of -1 representing unspec_axis. Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor(np.arange(12, dtype=np.int32)) out = F.reshape(x, (3, 2, 2)) print(out.numpy()) Outputs: .. testoutput:: [[[ 0 1] [ 2 3]] [[ 4 5] [ 6 7]] [[ 8 9] [10 11]]] """ return mgb.opr.reshape(inp, target_shape) def transpose(inp: Tensor, pattern: Iterable[int]) -> Tensor: r"""Equivalent to :func:`dimshuffle` """ return dimshuffle(inp, pattern) @wrap_io_tensor def add_axis(inp: Tensor, axis: int) -> Tensor: r""" Add dimension before given axis. :param inp: Input tensor :param axis: Place of new axes :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor([1, 2]) out = F.add_axis(x, 0) print(out.shape) Outputs: .. testoutput:: (1, 2) """ if not isinstance(axis, int): raise ValueError("axis must be int, but got type:{}".format(type(axis))) return mgb.opr.add_axis(inp, axis) @wrap_io_tensor def remove_axis(inp: Tensor, axis: int) -> Tensor: r""" Remove dimension of shape 1. :param inp: Input tensor :param axis: Place of axis to be removed :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor(np.array([1, 2], dtype=np.int32).reshape(1, 1, 2, 1)) out = F.remove_axis(x, 3) print(out.shape) Outputs: .. testoutput:: (1, 1, 2) """ if not isinstance(axis, int): raise ValueError("axis must be int, but got type:{}".format(type(axis))) return
mgb.opr.remove_axis(inp, axis)
megengine._internal.opr.remove_axis
# -*- 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 functools from typing import Iterable, List, Optional, Union import numpy as np import megengine._internal as mgb from megengine._internal import CompGraph, CompNode from ..core import zeros from ..core.graph import _use_default_if_none from ..core.tensor import Tensor, wrap_io_tensor from .elemwise import ceil from .utils import _decide_comp_node_and_comp_graph @wrap_io_tensor def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor: """ Broadcast a tensor to ``shape`` :param inp: The input tensor :param shape: The target shape :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3)) out = F.broadcast_to(data, (4, 2, 3)) print(out.numpy()) Outputs: .. testoutput:: [[[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]]] """ if isinstance(shape, int): shape = (shape,) return mgb.opr.broadcast(inp, shape) def _get_idx(index, axis): index_dims = len(index.imm_shape) idx = [] comp_node, comp_graph = _decide_comp_node_and_comp_graph(index) for i in range(index_dims): if i != axis: shape = [1] * index_dims shape[i] = index.axis_shape(i) arange = mgb.opr.linspace( 0, index.axis_shape(i) - 1, index.axis_shape(i), comp_node=comp_node, comp_graph=comp_graph, ) arange = ( arange.reshape(*shape) .broadcast(index.shape) .reshape(-1) .astype(np.int32) ) idx.append(arange) else: idx.append(index.reshape(-1)) return tuple(idx) @wrap_io_tensor def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor: r""" Gather data from :attr:`inp` on :attr:`axis` using :attr:`index`. For a 3-D tensor, the output is specified by:: out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0 out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1 out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2 if :attr:`inp` is an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i, then :attr:`index` must be an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and output will have the same size as :attr:`index`. :param inp: the source tensor :param axis: the axis along which to index :param index: the indices of elements to gather Examples: .. testcode:: import megengine.functional as F from megengine.core import tensor inp = tensor([ [1,2], [3,4], [5,6], ]) index = tensor([[0,2], [1,0]]) oup = F.gather(inp, 0, index) print(oup.numpy()) Outputs: .. testoutput:: [[1 6] [3 2]] """ input_shape = inp.imm_shape index_shape = index.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) if input_dims != index_dims: raise ValueError( "The index tensor must have same dimensions as input tensor, " "But the input dims:{}, the index dims:{}".format(input_dims, index_dims) ) if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(input_dims): if i != axis and input_shape[i] != index_shape[i]: raise ValueError( "The input {} and index {} must have the same size apart from axis {}".format( input_shape, index_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.advanced_indexing(inp)[idx].reshape( index.shape ) # pylint: disable=no-member @wrap_io_tensor def concat( inps: Iterable[Tensor], axis: int = 0, device: Optional[CompNode] = None, comp_graph: Optional[CompGraph] = None, ) -> Tensor: r""" Concat some tensors :param inps: Input tensors to concat :param axis: the dimension over which the tensors are concatenated. Default: 0 :param device: The comp node output on. Default: None :param comp_graph: The graph in which output is. Default: None :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3))) data2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3))) out = F.concat([data1, data2]) print(out.numpy()) Outputs: .. testoutput:: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.] [ 9. 10. 11.]] """ # Output buffer not supported return mgb.opr.concat( *list(inps), axis=axis, comp_node=device, comp_graph=comp_graph ) @wrap_io_tensor def scatter(inp: Tensor, axis: int, index: Tensor, source: Tensor) -> Tensor: r""" Writes all values from the tensor :attr:`source` into :attr:`inp` at the indices specified in the :attr:`index` tensor. For each value in :attr:`source`, its output index is specified by its index in :attr:`source` for ``axis != dimension`` and by the corresponding value in :attr:`index` for ``axis = dimension``. For a 3-D tensor, :attr:`inp` is updated as:: inp[index[i][j][k]][j][k] = source[i][j][k] # if axis == 0 inp[i][index[i][j][k]][k] = source[i][j][k] # if axis == 1 inp[i][j][index[i][j][k]] = source[i][j][k] # if axis == 2 :attr:`inp`, :attr:`index` and :attr:`source` should have same number of dimensions. It is also required that ``source.shape(d) <= inp.shape(d)`` and ``index.shape(d) == source.shape(d)`` for all dimensions ``d``. Moreover, the values of :attr:`index` must be between ``0`` and ``inp.shape(axis) - 1`` inclusive. .. note:: Please notice that, due to performance issues, the result is uncertain on the GPU device if scatter difference positions from source to the same destination position regard to index tensor. Show the case using the following examples, the oup[0][2] is maybe from source[0][2] which value is 0.2256 or source[1][2] which value is 0.5339 if set the index[1][2] from 1 to 0. :param inp: the inp tensor which to be scattered :param axis: the axis along which to index :param index: the indices of elements to scatter :param source: the source element(s) to scatter Examples: .. testcode:: import numpy as np import megengine.functional as F from megengine.core import tensor inp = tensor(np.zeros(shape=(3,5),dtype=np.float32)) source = tensor([[0.9935,0.9465,0.2256,0.8926,0.4396],[0.7723,0.0718,0.5939,0.357,0.4576]]) index = tensor([[0,2,0,2,1],[2,0,1,1,2]]) oup = F.scatter(inp, 0, index,source) print(oup.numpy()) Outputs: .. testoutput:: [[0.9935 0.0718 0.2256 0. 0. ] [0. 0. 0.5939 0.357 0.4396] [0.7723 0.9465 0. 0.8926 0.4576]] """ input_shape = inp.imm_shape index_shape = index.imm_shape source_shape = source.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) source_dims = len(source_shape) if input_dims != index_dims or input_dims != source_dims: raise ValueError("The input, source and index tensor must have same dimensions") if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(source_dims): if source_shape[i] > input_shape[i]: raise ValueError( "The each shape size for source {} must be less than or equal to input {} ".format( source_shape, input_shape ) ) for i in range(index_dims): if index_shape[i] != source_shape[i]: raise ValueError( "The each shape size for index {} must be equal to source {} ".format( index_shape, source_shape ) ) for i in range(index_dims): if i != axis and index_shape[i] > input_shape[i]: raise ValueError( "The index {} must be less than or equal to input {} size apart from axis {}".format( index_shape, input_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.set_advanced_indexing(inp, source.flatten())[idx] @wrap_io_tensor def where(mask: Tensor, x: Tensor, y: Tensor) -> Tensor: r""" Select elements either from Tensor x or Tensor y, according to mask. .. math:: \textrm{out}_i = x_i \textrm{ if } \textrm{mask}_i \textrm{ is True else } y_i :param mask: a mask used for choosing x or y :param x: the first choice :param y: the second choice Examples: .. testcode:: from megengine import tensor import megengine.functional as F mask = tensor(np.array([[1, 0], [0, 1]], dtype=np.int32)) x = tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)) y = tensor(np.array([[5, 6], [7, 8]], dtype=np.float32)) out = F.where(mask, x, y) print(out.numpy()) Outputs: .. testoutput:: [[1. 6.] [7. 4.]] """ v0, index0 = mgb.opr.cond_take( x, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=1 ) v1, index1 = mgb.opr.cond_take( y, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=0 ) out = x.flatten() index = mgb.opr.concat(index0, index1, axis=0) v = mgb.opr.concat(v0, v1, axis=0) out =
mgb.opr.set_advanced_indexing(out, v)
megengine._internal.opr.set_advanced_indexing
# -*- 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 functools from typing import Iterable, List, Optional, Union import numpy as np import megengine._internal as mgb from megengine._internal import CompGraph, CompNode from ..core import zeros from ..core.graph import _use_default_if_none from ..core.tensor import Tensor, wrap_io_tensor from .elemwise import ceil from .utils import _decide_comp_node_and_comp_graph @wrap_io_tensor def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor: """ Broadcast a tensor to ``shape`` :param inp: The input tensor :param shape: The target shape :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3)) out = F.broadcast_to(data, (4, 2, 3)) print(out.numpy()) Outputs: .. testoutput:: [[[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]]] """ if isinstance(shape, int): shape = (shape,) return mgb.opr.broadcast(inp, shape) def _get_idx(index, axis): index_dims = len(index.imm_shape) idx = [] comp_node, comp_graph = _decide_comp_node_and_comp_graph(index) for i in range(index_dims): if i != axis: shape = [1] * index_dims shape[i] = index.axis_shape(i) arange = mgb.opr.linspace( 0, index.axis_shape(i) - 1, index.axis_shape(i), comp_node=comp_node, comp_graph=comp_graph, ) arange = ( arange.reshape(*shape) .broadcast(index.shape) .reshape(-1) .astype(np.int32) ) idx.append(arange) else: idx.append(index.reshape(-1)) return tuple(idx) @wrap_io_tensor def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor: r""" Gather data from :attr:`inp` on :attr:`axis` using :attr:`index`. For a 3-D tensor, the output is specified by:: out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0 out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1 out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2 if :attr:`inp` is an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i, then :attr:`index` must be an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and output will have the same size as :attr:`index`. :param inp: the source tensor :param axis: the axis along which to index :param index: the indices of elements to gather Examples: .. testcode:: import megengine.functional as F from megengine.core import tensor inp = tensor([ [1,2], [3,4], [5,6], ]) index = tensor([[0,2], [1,0]]) oup = F.gather(inp, 0, index) print(oup.numpy()) Outputs: .. testoutput:: [[1 6] [3 2]] """ input_shape = inp.imm_shape index_shape = index.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) if input_dims != index_dims: raise ValueError( "The index tensor must have same dimensions as input tensor, " "But the input dims:{}, the index dims:{}".format(input_dims, index_dims) ) if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(input_dims): if i != axis and input_shape[i] != index_shape[i]: raise ValueError( "The input {} and index {} must have the same size apart from axis {}".format( input_shape, index_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.advanced_indexing(inp)[idx].reshape( index.shape ) # pylint: disable=no-member @wrap_io_tensor def concat( inps: Iterable[Tensor], axis: int = 0, device: Optional[CompNode] = None, comp_graph: Optional[CompGraph] = None, ) -> Tensor: r""" Concat some tensors :param inps: Input tensors to concat :param axis: the dimension over which the tensors are concatenated. Default: 0 :param device: The comp node output on. Default: None :param comp_graph: The graph in which output is. Default: None :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3))) data2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3))) out = F.concat([data1, data2]) print(out.numpy()) Outputs: .. testoutput:: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.] [ 9. 10. 11.]] """ # Output buffer not supported return mgb.opr.concat( *list(inps), axis=axis, comp_node=device, comp_graph=comp_graph ) @wrap_io_tensor def scatter(inp: Tensor, axis: int, index: Tensor, source: Tensor) -> Tensor: r""" Writes all values from the tensor :attr:`source` into :attr:`inp` at the indices specified in the :attr:`index` tensor. For each value in :attr:`source`, its output index is specified by its index in :attr:`source` for ``axis != dimension`` and by the corresponding value in :attr:`index` for ``axis = dimension``. For a 3-D tensor, :attr:`inp` is updated as:: inp[index[i][j][k]][j][k] = source[i][j][k] # if axis == 0 inp[i][index[i][j][k]][k] = source[i][j][k] # if axis == 1 inp[i][j][index[i][j][k]] = source[i][j][k] # if axis == 2 :attr:`inp`, :attr:`index` and :attr:`source` should have same number of dimensions. It is also required that ``source.shape(d) <= inp.shape(d)`` and ``index.shape(d) == source.shape(d)`` for all dimensions ``d``. Moreover, the values of :attr:`index` must be between ``0`` and ``inp.shape(axis) - 1`` inclusive. .. note:: Please notice that, due to performance issues, the result is uncertain on the GPU device if scatter difference positions from source to the same destination position regard to index tensor. Show the case using the following examples, the oup[0][2] is maybe from source[0][2] which value is 0.2256 or source[1][2] which value is 0.5339 if set the index[1][2] from 1 to 0. :param inp: the inp tensor which to be scattered :param axis: the axis along which to index :param index: the indices of elements to scatter :param source: the source element(s) to scatter Examples: .. testcode:: import numpy as np import megengine.functional as F from megengine.core import tensor inp = tensor(np.zeros(shape=(3,5),dtype=np.float32)) source = tensor([[0.9935,0.9465,0.2256,0.8926,0.4396],[0.7723,0.0718,0.5939,0.357,0.4576]]) index = tensor([[0,2,0,2,1],[2,0,1,1,2]]) oup = F.scatter(inp, 0, index,source) print(oup.numpy()) Outputs: .. testoutput:: [[0.9935 0.0718 0.2256 0. 0. ] [0. 0. 0.5939 0.357 0.4396] [0.7723 0.9465 0. 0.8926 0.4576]] """ input_shape = inp.imm_shape index_shape = index.imm_shape source_shape = source.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) source_dims = len(source_shape) if input_dims != index_dims or input_dims != source_dims: raise ValueError("The input, source and index tensor must have same dimensions") if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(source_dims): if source_shape[i] > input_shape[i]: raise ValueError( "The each shape size for source {} must be less than or equal to input {} ".format( source_shape, input_shape ) ) for i in range(index_dims): if index_shape[i] != source_shape[i]: raise ValueError( "The each shape size for index {} must be equal to source {} ".format( index_shape, source_shape ) ) for i in range(index_dims): if i != axis and index_shape[i] > input_shape[i]: raise ValueError( "The index {} must be less than or equal to input {} size apart from axis {}".format( index_shape, input_shape, axis ) ) idx = _get_idx(index, axis) return mgb.opr.set_advanced_indexing(inp, source.flatten())[idx] @wrap_io_tensor def where(mask: Tensor, x: Tensor, y: Tensor) -> Tensor: r""" Select elements either from Tensor x or Tensor y, according to mask. .. math:: \textrm{out}_i = x_i \textrm{ if } \textrm{mask}_i \textrm{ is True else } y_i :param mask: a mask used for choosing x or y :param x: the first choice :param y: the second choice Examples: .. testcode:: from megengine import tensor import megengine.functional as F mask = tensor(np.array([[1, 0], [0, 1]], dtype=np.int32)) x = tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)) y = tensor(np.array([[5, 6], [7, 8]], dtype=np.float32)) out = F.where(mask, x, y) print(out.numpy()) Outputs: .. testoutput:: [[1. 6.] [7. 4.]] """ v0, index0 = mgb.opr.cond_take( x, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=1 ) v1, index1 = mgb.opr.cond_take( y, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=0 ) out = x.flatten() index = mgb.opr.concat(index0, index1, axis=0) v = mgb.opr.concat(v0, v1, axis=0) out = mgb.opr.set_advanced_indexing(out, v)[index] out = out.reshape(x.shape) return out @wrap_io_tensor def cond_take(mask: Tensor, x: Tensor, val=1) -> Tensor: r""" Take elements from data if specific condition is satisfied on mask. This operator has two outputs: the first is the elements taken, and the second is the indices corresponding to those elements; they are both 1-dimensional. High-dimension input would first be flattened. :param mask: condition param; must be the same shape with data :param x: input tensor from which to take elements :param val: value to be compared to by mode Examples: .. testcode:: from megengine import tensor import megengine.functional as F mask = tensor(np.array([[1, 0], [0, 1]], dtype=np.int32)) x = tensor(np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)) v, index = F.cond_take(mask, x, 1) print(v, index) Outputs: .. testoutput:: Tensor([1. 4.]) Tensor([0 3], dtype=int32) """ v, index = mgb.opr.cond_take( x, mask, mode=mgb.opr_param_defs.CondTake.Mode.EQ, val=val ) return v, index def shapeof(x: Tensor, axis=None): r""" The shape of input tensor. """ return x.shapeof(axis=axis) @wrap_io_tensor def dimshuffle(inp: Tensor, pattern: Iterable[int]) -> Tensor: r""" Swap shapes and strides according to given pattern :param inp: Input tensor :param pattern: a list of integers including 0, 1, ... , ``ndim``-1, and any number of ``'x'`` char in dimensions where this tensor should be broadcasted. For examples: * (``'x'``) -> make a 0d (scalar) into a 1d vector * (0, 1) -> identity for 2d vectors * (1, 0) -> inverts the first and second dimensions * (``'x'``, 0) -> make a row out of a 1d vector (N to 1xN) * (0, ``'x'``) -> make a column out of a 1d vector (N to Nx1) * (2, 0, 1) -> AxBxC to CxAxB * (0, ``'x'``, 1) -> AxB to Ax1xB * (1, ``'x'``, 0) -> AxB to Bx1xA * (1,) -> This remove dimensions 0. It must be a broadcastable dimension (1xA to A) :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor(np.array([[1, 1], [0, 0]], dtype=np.int32)) out = F.dimshuffle(x, (1, 0)) print(out.numpy()) Outputs: .. testoutput:: [[1 0] [1 0]] """ return mgb.opr.dimshuffle(inp, pattern) @wrap_io_tensor def reshape(inp: Tensor, target_shape: Iterable[int]) -> Tensor: r""" Reshape a tensor to given target shape; total number of logical elements must remain unchanged :param inp: Input tensor :param target_shape: target shape, the components would be concatenated to form the target shape, and it can contain an element of -1 representing unspec_axis. Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor(np.arange(12, dtype=np.int32)) out = F.reshape(x, (3, 2, 2)) print(out.numpy()) Outputs: .. testoutput:: [[[ 0 1] [ 2 3]] [[ 4 5] [ 6 7]] [[ 8 9] [10 11]]] """ return mgb.opr.reshape(inp, target_shape) def transpose(inp: Tensor, pattern: Iterable[int]) -> Tensor: r"""Equivalent to :func:`dimshuffle` """ return dimshuffle(inp, pattern) @wrap_io_tensor def add_axis(inp: Tensor, axis: int) -> Tensor: r""" Add dimension before given axis. :param inp: Input tensor :param axis: Place of new axes :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor([1, 2]) out = F.add_axis(x, 0) print(out.shape) Outputs: .. testoutput:: (1, 2) """ if not isinstance(axis, int): raise ValueError("axis must be int, but got type:{}".format(type(axis))) return mgb.opr.add_axis(inp, axis) @wrap_io_tensor def remove_axis(inp: Tensor, axis: int) -> Tensor: r""" Remove dimension of shape 1. :param inp: Input tensor :param axis: Place of axis to be removed :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F x = tensor(np.array([1, 2], dtype=np.int32).reshape(1, 1, 2, 1)) out = F.remove_axis(x, 3) print(out.shape) Outputs: .. testoutput:: (1, 1, 2) """ if not isinstance(axis, int): raise ValueError("axis must be int, but got type:{}".format(type(axis))) return mgb.opr.remove_axis(inp, axis) def linspace( start: Union[int, float, Tensor], stop: Union[int, float, Tensor], num: Union[int, Tensor], dtype=np.float32, device: Optional[CompNode] = None, comp_graph: Optional[CompGraph] = None, ) -> Tensor: r""" Return equally spaced numbers over a specified interval :param start: Starting value of the squence, shoule be scalar :param stop: The last value of the squence, shoule be scalar :param num: number of values to generate :param dtype: result data type :return: The generated tensor Examples: .. testcode:: import numpy as np import megengine.functional as F a = F.linspace(3,10,5) print(a.numpy()) .. testoutput:: [ 3. 4.75 6.5 8.25 10. ] """ if dtype is not np.float32: raise ValueError("linspace is only implemented for float32") device, comp_graph = _use_default_if_none(device, comp_graph) ret = Tensor(
mgb.opr.linspace(start, stop, num, comp_node=device, comp_graph=comp_graph)
megengine._internal.opr.linspace
# -*- 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 functools from typing import Iterable, List, Optional, Union import numpy as np import megengine._internal as mgb from megengine._internal import CompGraph, CompNode from ..core import zeros from ..core.graph import _use_default_if_none from ..core.tensor import Tensor, wrap_io_tensor from .elemwise import ceil from .utils import _decide_comp_node_and_comp_graph @wrap_io_tensor def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor: """ Broadcast a tensor to ``shape`` :param inp: The input tensor :param shape: The target shape :return: The output tensor Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3)) out = F.broadcast_to(data, (4, 2, 3)) print(out.numpy()) Outputs: .. testoutput:: [[[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]] [[0. 1. 2.] [3. 4. 5.]]] """ if isinstance(shape, int): shape = (shape,) return mgb.opr.broadcast(inp, shape) def _get_idx(index, axis): index_dims = len(index.imm_shape) idx = [] comp_node, comp_graph = _decide_comp_node_and_comp_graph(index) for i in range(index_dims): if i != axis: shape = [1] * index_dims shape[i] = index.axis_shape(i) arange = mgb.opr.linspace( 0, index.axis_shape(i) - 1, index.axis_shape(i), comp_node=comp_node, comp_graph=comp_graph, ) arange = ( arange.reshape(*shape) .broadcast(index.shape) .reshape(-1) .astype(np.int32) ) idx.append(arange) else: idx.append(index.reshape(-1)) return tuple(idx) @wrap_io_tensor def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor: r""" Gather data from :attr:`inp` on :attr:`axis` using :attr:`index`. For a 3-D tensor, the output is specified by:: out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0 out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1 out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2 if :attr:`inp` is an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i, then :attr:`index` must be an n-dimensional tensor with size :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and output will have the same size as :attr:`index`. :param inp: the source tensor :param axis: the axis along which to index :param index: the indices of elements to gather Examples: .. testcode:: import megengine.functional as F from megengine.core import tensor inp = tensor([ [1,2], [3,4], [5,6], ]) index = tensor([[0,2], [1,0]]) oup = F.gather(inp, 0, index) print(oup.numpy()) Outputs: .. testoutput:: [[1 6] [3 2]] """ input_shape = inp.imm_shape index_shape = index.imm_shape input_dims = len(input_shape) index_dims = len(index_shape) if input_dims != index_dims: raise ValueError( "The index tensor must have same dimensions as input tensor, " "But the input dims:{}, the index dims:{}".format(input_dims, index_dims) ) if axis < 0 or axis >= input_dims: raise ValueError( "Index axis {} is output of bounds, should in range [0 {})".format( axis, input_dims ) ) for i in range(input_dims): if i != axis and input_shape[i] != index_shape[i]: raise ValueError( "The input {} and index {} must have the same size apart from axis {}".format( input_shape, index_shape, axis ) ) idx = _get_idx(index, axis) return
mgb.opr.advanced_indexing(inp)
megengine._internal.opr.advanced_indexing
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y = Tensor(x) y += 1 x = x + 2 return x, y class MyModule2(M.Module): def forward(self, x): y = Tensor([1, x, 1]) y += 1 x = x + 2 return x, y class MyModule3(M.Module): def __init__(self): super().__init__() self.modules = [ M.Elemwise("ADD"), M.Elemwise("ADD"), OrderedDict([("a", M.Elemwise("ADD")), ("b", M.Elemwise("ADD"))]), M.Elemwise("RELU"), M.Elemwise("RELU"), ] def forward(self, a, b): x = self.modules[0](a, b) y = self.modules[1](a, b) assert list(self.modules[2].keys()) == ["a", "b"] for _, m in self.modules[2].items(): y = m(x, y) for m in self.modules[3:]: y = m(y) return y class MyModule4(M.Module): def __init__(self): super().__init__() self.add = F.add def forward(self, x, y): return self.add(x, y) def test_trace_module():
enable_expr_checker()
megengine.traced_module.enable_expr_checker
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y = Tensor(x) y += 1 x = x + 2 return x, y class MyModule2(M.Module): def forward(self, x): y = Tensor([1, x, 1]) y += 1 x = x + 2 return x, y class MyModule3(M.Module): def __init__(self): super().__init__() self.modules = [ M.Elemwise("ADD"), M.Elemwise("ADD"), OrderedDict([("a", M.Elemwise("ADD")), ("b", M.Elemwise("ADD"))]), M.Elemwise("RELU"), M.Elemwise("RELU"), ] def forward(self, a, b): x = self.modules[0](a, b) y = self.modules[1](a, b) assert list(self.modules[2].keys()) == ["a", "b"] for _, m in self.modules[2].items(): y = m(x, y) for m in self.modules[3:]: y = m(y) return y class MyModule4(M.Module): def __init__(self): super().__init__() self.add = F.add def forward(self, x, y): return self.add(x, y) def test_trace_module(): enable_expr_checker() x =
Tensor(1)
megengine.Tensor
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y = Tensor(x) y += 1 x = x + 2 return x, y class MyModule2(M.Module): def forward(self, x): y = Tensor([1, x, 1]) y += 1 x = x + 2 return x, y class MyModule3(M.Module): def __init__(self): super().__init__() self.modules = [ M.Elemwise("ADD"), M.Elemwise("ADD"), OrderedDict([("a", M.Elemwise("ADD")), ("b", M.Elemwise("ADD"))]), M.Elemwise("RELU"), M.Elemwise("RELU"), ] def forward(self, a, b): x = self.modules[0](a, b) y = self.modules[1](a, b) assert list(self.modules[2].keys()) == ["a", "b"] for _, m in self.modules[2].items(): y = m(x, y) for m in self.modules[3:]: y = m(y) return y class MyModule4(M.Module): def __init__(self): super().__init__() self.add = F.add def forward(self, x, y): return self.add(x, y) def test_trace_module(): enable_expr_checker() x = Tensor(1) m1 = MyModule1() tm1 =
trace_module(m1, x)
megengine.traced_module.trace_module
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y = Tensor(x) y += 1 x = x + 2 return x, y class MyModule2(M.Module): def forward(self, x): y = Tensor([1, x, 1]) y += 1 x = x + 2 return x, y class MyModule3(M.Module): def __init__(self): super().__init__() self.modules = [ M.Elemwise("ADD"), M.Elemwise("ADD"), OrderedDict([("a", M.Elemwise("ADD")), ("b", M.Elemwise("ADD"))]), M.Elemwise("RELU"), M.Elemwise("RELU"), ] def forward(self, a, b): x = self.modules[0](a, b) y = self.modules[1](a, b) assert list(self.modules[2].keys()) == ["a", "b"] for _, m in self.modules[2].items(): y = m(x, y) for m in self.modules[3:]: y = m(y) return y class MyModule4(M.Module): def __init__(self): super().__init__() self.add = F.add def forward(self, x, y): return self.add(x, y) def test_trace_module(): enable_expr_checker() x = Tensor(1) m1 = MyModule1() tm1 = trace_module(m1, x) m2 = MyModule2() tm2 =
trace_module(m2, x)
megengine.traced_module.trace_module
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y = Tensor(x) y += 1 x = x + 2 return x, y class MyModule2(M.Module): def forward(self, x): y = Tensor([1, x, 1]) y += 1 x = x + 2 return x, y class MyModule3(M.Module): def __init__(self): super().__init__() self.modules = [ M.Elemwise("ADD"), M.Elemwise("ADD"), OrderedDict([("a", M.Elemwise("ADD")), ("b", M.Elemwise("ADD"))]), M.Elemwise("RELU"), M.Elemwise("RELU"), ] def forward(self, a, b): x = self.modules[0](a, b) y = self.modules[1](a, b) assert list(self.modules[2].keys()) == ["a", "b"] for _, m in self.modules[2].items(): y = m(x, y) for m in self.modules[3:]: y = m(y) return y class MyModule4(M.Module): def __init__(self): super().__init__() self.add = F.add def forward(self, x, y): return self.add(x, y) def test_trace_module(): enable_expr_checker() x = Tensor(1) m1 = MyModule1() tm1 = trace_module(m1, x) m2 = MyModule2() tm2 = trace_module(m2, x) inp =
Tensor(2)
megengine.Tensor
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y = Tensor(x) y += 1 x = x + 2 return x, y class MyModule2(M.Module): def forward(self, x): y = Tensor([1, x, 1]) y += 1 x = x + 2 return x, y class MyModule3(M.Module): def __init__(self): super().__init__() self.modules = [ M.Elemwise("ADD"), M.Elemwise("ADD"), OrderedDict([("a", M.Elemwise("ADD")), ("b", M.Elemwise("ADD"))]), M.Elemwise("RELU"), M.Elemwise("RELU"), ] def forward(self, a, b): x = self.modules[0](a, b) y = self.modules[1](a, b) assert list(self.modules[2].keys()) == ["a", "b"] for _, m in self.modules[2].items(): y = m(x, y) for m in self.modules[3:]: y = m(y) return y class MyModule4(M.Module): def __init__(self): super().__init__() self.add = F.add def forward(self, x, y): return self.add(x, y) def test_trace_module(): enable_expr_checker() x = Tensor(1) m1 = MyModule1() tm1 = trace_module(m1, x) m2 = MyModule2() tm2 = trace_module(m2, x) inp = Tensor(2) gt = m1(inp) output = tm1(inp) for a, b in zip(output, gt): np.testing.assert_equal(a.numpy(), b.numpy()) gt1 = m2(inp) output1 = tm2(inp) for a, b in zip(output1, gt1): np.testing.assert_equal(a.numpy(), b.numpy()) a, b = Tensor(1), Tensor(2) m3 = MyModule3() gt = m3(a, b) tm3 =
trace_module(m3, a, b)
megengine.traced_module.trace_module
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y = Tensor(x) y += 1 x = x + 2 return x, y class MyModule2(M.Module): def forward(self, x): y = Tensor([1, x, 1]) y += 1 x = x + 2 return x, y class MyModule3(M.Module): def __init__(self): super().__init__() self.modules = [ M.Elemwise("ADD"), M.Elemwise("ADD"), OrderedDict([("a", M.Elemwise("ADD")), ("b", M.Elemwise("ADD"))]), M.Elemwise("RELU"), M.Elemwise("RELU"), ] def forward(self, a, b): x = self.modules[0](a, b) y = self.modules[1](a, b) assert list(self.modules[2].keys()) == ["a", "b"] for _, m in self.modules[2].items(): y = m(x, y) for m in self.modules[3:]: y = m(y) return y class MyModule4(M.Module): def __init__(self): super().__init__() self.add = F.add def forward(self, x, y): return self.add(x, y) def test_trace_module(): enable_expr_checker() x = Tensor(1) m1 = MyModule1() tm1 = trace_module(m1, x) m2 = MyModule2() tm2 = trace_module(m2, x) inp = Tensor(2) gt = m1(inp) output = tm1(inp) for a, b in zip(output, gt): np.testing.assert_equal(a.numpy(), b.numpy()) gt1 = m2(inp) output1 = tm2(inp) for a, b in zip(output1, gt1): np.testing.assert_equal(a.numpy(), b.numpy()) a, b = Tensor(1), Tensor(2) m3 = MyModule3() gt = m3(a, b) tm3 = trace_module(m3, a, b) out = tm3(a, b) np.testing.assert_equal(out.numpy(), gt.numpy()) assert isinstance(tm3.modules.__dict__["0"], M.Elemwise) assert isinstance(tm3.modules.__dict__["2"], TracedModule) assert isinstance(tm3.modules.__dict__["2"].a, M.Elemwise) assert isinstance(tm3.modules.__dict__["3"], M.Elemwise) m4 = MyModule4() tm4 =
trace_module(m4, a, b)
megengine.traced_module.trace_module
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y = Tensor(x) y += 1 x = x + 2 return x, y class MyModule2(M.Module): def forward(self, x): y = Tensor([1, x, 1]) y += 1 x = x + 2 return x, y class MyModule3(M.Module): def __init__(self): super().__init__() self.modules = [ M.Elemwise("ADD"), M.Elemwise("ADD"), OrderedDict([("a", M.Elemwise("ADD")), ("b", M.Elemwise("ADD"))]), M.Elemwise("RELU"), M.Elemwise("RELU"), ] def forward(self, a, b): x = self.modules[0](a, b) y = self.modules[1](a, b) assert list(self.modules[2].keys()) == ["a", "b"] for _, m in self.modules[2].items(): y = m(x, y) for m in self.modules[3:]: y = m(y) return y class MyModule4(M.Module): def __init__(self): super().__init__() self.add = F.add def forward(self, x, y): return self.add(x, y) def test_trace_module(): enable_expr_checker() x = Tensor(1) m1 = MyModule1() tm1 = trace_module(m1, x) m2 = MyModule2() tm2 = trace_module(m2, x) inp = Tensor(2) gt = m1(inp) output = tm1(inp) for a, b in zip(output, gt): np.testing.assert_equal(a.numpy(), b.numpy()) gt1 = m2(inp) output1 = tm2(inp) for a, b in zip(output1, gt1): np.testing.assert_equal(a.numpy(), b.numpy()) a, b = Tensor(1), Tensor(2) m3 = MyModule3() gt = m3(a, b) tm3 = trace_module(m3, a, b) out = tm3(a, b) np.testing.assert_equal(out.numpy(), gt.numpy()) assert isinstance(tm3.modules.__dict__["0"], M.Elemwise) assert isinstance(tm3.modules.__dict__["2"], TracedModule) assert isinstance(tm3.modules.__dict__["2"].a, M.Elemwise) assert isinstance(tm3.modules.__dict__["3"], M.Elemwise) m4 = MyModule4() tm4 = trace_module(m4, a, b) np.testing.assert_equal(tm4(a, b).numpy(), 3) np.testing.assert_equal(tm4(a, y=b).numpy(), 3) np.testing.assert_equal(tm4(x=a, y=b).numpy(), 3) tm4 =
trace_module(m4, a, y=b)
megengine.traced_module.trace_module
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y = Tensor(x) y += 1 x = x + 2 return x, y class MyModule2(M.Module): def forward(self, x): y = Tensor([1, x, 1]) y += 1 x = x + 2 return x, y class MyModule3(M.Module): def __init__(self): super().__init__() self.modules = [ M.Elemwise("ADD"), M.Elemwise("ADD"), OrderedDict([("a", M.Elemwise("ADD")), ("b", M.Elemwise("ADD"))]), M.Elemwise("RELU"), M.Elemwise("RELU"), ] def forward(self, a, b): x = self.modules[0](a, b) y = self.modules[1](a, b) assert list(self.modules[2].keys()) == ["a", "b"] for _, m in self.modules[2].items(): y = m(x, y) for m in self.modules[3:]: y = m(y) return y class MyModule4(M.Module): def __init__(self): super().__init__() self.add = F.add def forward(self, x, y): return self.add(x, y) def test_trace_module(): enable_expr_checker() x = Tensor(1) m1 = MyModule1() tm1 = trace_module(m1, x) m2 = MyModule2() tm2 = trace_module(m2, x) inp = Tensor(2) gt = m1(inp) output = tm1(inp) for a, b in zip(output, gt): np.testing.assert_equal(a.numpy(), b.numpy()) gt1 = m2(inp) output1 = tm2(inp) for a, b in zip(output1, gt1): np.testing.assert_equal(a.numpy(), b.numpy()) a, b = Tensor(1), Tensor(2) m3 = MyModule3() gt = m3(a, b) tm3 = trace_module(m3, a, b) out = tm3(a, b) np.testing.assert_equal(out.numpy(), gt.numpy()) assert isinstance(tm3.modules.__dict__["0"], M.Elemwise) assert isinstance(tm3.modules.__dict__["2"], TracedModule) assert isinstance(tm3.modules.__dict__["2"].a, M.Elemwise) assert isinstance(tm3.modules.__dict__["3"], M.Elemwise) m4 = MyModule4() tm4 = trace_module(m4, a, b) np.testing.assert_equal(tm4(a, b).numpy(), 3) np.testing.assert_equal(tm4(a, y=b).numpy(), 3) np.testing.assert_equal(tm4(x=a, y=b).numpy(), 3) tm4 = trace_module(m4, a, y=b) np.testing.assert_equal(tm4(a, b).numpy(), 3) np.testing.assert_equal(tm4(a, y=b).numpy(), 3) np.testing.assert_equal(tm4(x=a, y=b).numpy(), 3) tm4 =
trace_module(m4, x=a, y=b)
megengine.traced_module.trace_module
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y = Tensor(x) y += 1 x = x + 2 return x, y class MyModule2(M.Module): def forward(self, x): y = Tensor([1, x, 1]) y += 1 x = x + 2 return x, y class MyModule3(M.Module): def __init__(self): super().__init__() self.modules = [ M.Elemwise("ADD"), M.Elemwise("ADD"), OrderedDict([("a", M.Elemwise("ADD")), ("b", M.Elemwise("ADD"))]), M.Elemwise("RELU"), M.Elemwise("RELU"), ] def forward(self, a, b): x = self.modules[0](a, b) y = self.modules[1](a, b) assert list(self.modules[2].keys()) == ["a", "b"] for _, m in self.modules[2].items(): y = m(x, y) for m in self.modules[3:]: y = m(y) return y class MyModule4(M.Module): def __init__(self): super().__init__() self.add = F.add def forward(self, x, y): return self.add(x, y) def test_trace_module(): enable_expr_checker() x = Tensor(1) m1 = MyModule1() tm1 = trace_module(m1, x) m2 = MyModule2() tm2 = trace_module(m2, x) inp = Tensor(2) gt = m1(inp) output = tm1(inp) for a, b in zip(output, gt): np.testing.assert_equal(a.numpy(), b.numpy()) gt1 = m2(inp) output1 = tm2(inp) for a, b in zip(output1, gt1): np.testing.assert_equal(a.numpy(), b.numpy()) a, b = Tensor(1), Tensor(2) m3 = MyModule3() gt = m3(a, b) tm3 = trace_module(m3, a, b) out = tm3(a, b) np.testing.assert_equal(out.numpy(), gt.numpy()) assert isinstance(tm3.modules.__dict__["0"], M.Elemwise) assert isinstance(tm3.modules.__dict__["2"], TracedModule) assert isinstance(tm3.modules.__dict__["2"].a, M.Elemwise) assert isinstance(tm3.modules.__dict__["3"], M.Elemwise) m4 = MyModule4() tm4 = trace_module(m4, a, b) np.testing.assert_equal(tm4(a, b).numpy(), 3) np.testing.assert_equal(tm4(a, y=b).numpy(), 3) np.testing.assert_equal(tm4(x=a, y=b).numpy(), 3) tm4 = trace_module(m4, a, y=b) np.testing.assert_equal(tm4(a, b).numpy(), 3) np.testing.assert_equal(tm4(a, y=b).numpy(), 3) np.testing.assert_equal(tm4(x=a, y=b).numpy(), 3) tm4 = trace_module(m4, x=a, y=b) np.testing.assert_equal(tm4(a, b).numpy(), 3) np.testing.assert_equal(tm4(a, y=b).numpy(), 3) np.testing.assert_equal(tm4(x=a, y=b).numpy(), 3) tm5 =
trace_module(tm4, a, b)
megengine.traced_module.trace_module
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y = Tensor(x) y += 1 x = x + 2 return x, y class MyModule2(M.Module): def forward(self, x): y = Tensor([1, x, 1]) y += 1 x = x + 2 return x, y class MyModule3(M.Module): def __init__(self): super().__init__() self.modules = [ M.Elemwise("ADD"), M.Elemwise("ADD"), OrderedDict([("a", M.Elemwise("ADD")), ("b", M.Elemwise("ADD"))]), M.Elemwise("RELU"), M.Elemwise("RELU"), ] def forward(self, a, b): x = self.modules[0](a, b) y = self.modules[1](a, b) assert list(self.modules[2].keys()) == ["a", "b"] for _, m in self.modules[2].items(): y = m(x, y) for m in self.modules[3:]: y = m(y) return y class MyModule4(M.Module): def __init__(self): super().__init__() self.add = F.add def forward(self, x, y): return self.add(x, y) def test_trace_module(): enable_expr_checker() x = Tensor(1) m1 = MyModule1() tm1 = trace_module(m1, x) m2 = MyModule2() tm2 = trace_module(m2, x) inp = Tensor(2) gt = m1(inp) output = tm1(inp) for a, b in zip(output, gt): np.testing.assert_equal(a.numpy(), b.numpy()) gt1 = m2(inp) output1 = tm2(inp) for a, b in zip(output1, gt1): np.testing.assert_equal(a.numpy(), b.numpy()) a, b = Tensor(1), Tensor(2) m3 = MyModule3() gt = m3(a, b) tm3 = trace_module(m3, a, b) out = tm3(a, b) np.testing.assert_equal(out.numpy(), gt.numpy()) assert isinstance(tm3.modules.__dict__["0"], M.Elemwise) assert isinstance(tm3.modules.__dict__["2"], TracedModule) assert isinstance(tm3.modules.__dict__["2"].a, M.Elemwise) assert isinstance(tm3.modules.__dict__["3"], M.Elemwise) m4 = MyModule4() tm4 = trace_module(m4, a, b) np.testing.assert_equal(tm4(a, b).numpy(), 3) np.testing.assert_equal(tm4(a, y=b).numpy(), 3) np.testing.assert_equal(tm4(x=a, y=b).numpy(), 3) tm4 = trace_module(m4, a, y=b) np.testing.assert_equal(tm4(a, b).numpy(), 3) np.testing.assert_equal(tm4(a, y=b).numpy(), 3) np.testing.assert_equal(tm4(x=a, y=b).numpy(), 3) tm4 = trace_module(m4, x=a, y=b) np.testing.assert_equal(tm4(a, b).numpy(), 3) np.testing.assert_equal(tm4(a, y=b).numpy(), 3) np.testing.assert_equal(tm4(x=a, y=b).numpy(), 3) tm5 = trace_module(tm4, a, b) np.testing.assert_equal(tm5(a, b).numpy(), 3) np.testing.assert_equal(tm5(a, y=b).numpy(), 3) np.testing.assert_equal(tm5(x=a, y=b).numpy(), 3) tm5 =
trace_module(tm4, a, y=b)
megengine.traced_module.trace_module
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y = Tensor(x) y += 1 x = x + 2 return x, y class MyModule2(M.Module): def forward(self, x): y = Tensor([1, x, 1]) y += 1 x = x + 2 return x, y class MyModule3(M.Module): def __init__(self): super().__init__() self.modules = [ M.Elemwise("ADD"), M.Elemwise("ADD"), OrderedDict([("a", M.Elemwise("ADD")), ("b", M.Elemwise("ADD"))]), M.Elemwise("RELU"), M.Elemwise("RELU"), ] def forward(self, a, b): x = self.modules[0](a, b) y = self.modules[1](a, b) assert list(self.modules[2].keys()) == ["a", "b"] for _, m in self.modules[2].items(): y = m(x, y) for m in self.modules[3:]: y = m(y) return y class MyModule4(M.Module): def __init__(self): super().__init__() self.add = F.add def forward(self, x, y): return self.add(x, y) def test_trace_module(): enable_expr_checker() x = Tensor(1) m1 = MyModule1() tm1 = trace_module(m1, x) m2 = MyModule2() tm2 = trace_module(m2, x) inp = Tensor(2) gt = m1(inp) output = tm1(inp) for a, b in zip(output, gt): np.testing.assert_equal(a.numpy(), b.numpy()) gt1 = m2(inp) output1 = tm2(inp) for a, b in zip(output1, gt1): np.testing.assert_equal(a.numpy(), b.numpy()) a, b = Tensor(1), Tensor(2) m3 = MyModule3() gt = m3(a, b) tm3 = trace_module(m3, a, b) out = tm3(a, b) np.testing.assert_equal(out.numpy(), gt.numpy()) assert isinstance(tm3.modules.__dict__["0"], M.Elemwise) assert isinstance(tm3.modules.__dict__["2"], TracedModule) assert isinstance(tm3.modules.__dict__["2"].a, M.Elemwise) assert isinstance(tm3.modules.__dict__["3"], M.Elemwise) m4 = MyModule4() tm4 = trace_module(m4, a, b) np.testing.assert_equal(tm4(a, b).numpy(), 3) np.testing.assert_equal(tm4(a, y=b).numpy(), 3) np.testing.assert_equal(tm4(x=a, y=b).numpy(), 3) tm4 = trace_module(m4, a, y=b) np.testing.assert_equal(tm4(a, b).numpy(), 3) np.testing.assert_equal(tm4(a, y=b).numpy(), 3) np.testing.assert_equal(tm4(x=a, y=b).numpy(), 3) tm4 = trace_module(m4, x=a, y=b) np.testing.assert_equal(tm4(a, b).numpy(), 3) np.testing.assert_equal(tm4(a, y=b).numpy(), 3) np.testing.assert_equal(tm4(x=a, y=b).numpy(), 3) tm5 = trace_module(tm4, a, b) np.testing.assert_equal(tm5(a, b).numpy(), 3) np.testing.assert_equal(tm5(a, y=b).numpy(), 3) np.testing.assert_equal(tm5(x=a, y=b).numpy(), 3) tm5 = trace_module(tm4, a, y=b) np.testing.assert_equal(tm5(a, b).numpy(), 3) np.testing.assert_equal(tm5(a, y=b).numpy(), 3) np.testing.assert_equal(tm5(x=a, y=b).numpy(), 3) tm5 =
trace_module(tm4, x=a, y=b)
megengine.traced_module.trace_module
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y =
Tensor(x)
megengine.Tensor
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedModule, enable_expr_checker, trace_module from megengine.traced_module.expr import Apply, CallFunction, Constant class MyModule1(M.Module): def forward(self, x): y = Tensor(x) y += 1 x = x + 2 return x, y class MyModule2(M.Module): def forward(self, x): y =
Tensor([1, x, 1])
megengine.Tensor