You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mxnet.apache.org by zh...@apache.org on 2020/05/22 18:54:26 UTC
[incubator-mxnet] branch master updated: Fix reference leak in
Block._children and enable reference leak tests universally (#18376)
This is an automated email from the ASF dual-hosted git repository.
zhasheng pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-mxnet.git
The following commit(s) were added to refs/heads/master by this push:
new c3aff73 Fix reference leak in Block._children and enable reference leak tests universally (#18376)
c3aff73 is described below
commit c3aff732371d6177e5d522c052fb7258978d8ce4
Author: Leonard Lausen <la...@amazon.com>
AuthorDate: Fri May 22 11:53:44 2020 -0700
Fix reference leak in Block._children and enable reference leak tests universally (#18376)
* Fix reference leak in Block._children
* Activate everywhere
* Disable on CentOS
* Fix
---
conftest.py | 47 ---------------
pytest.ini | 1 +
python/mxnet/gluon/block.py | 20 +++----
python/mxnet/gluon/contrib/nn/basic_layers.py | 4 +-
python/mxnet/gluon/nn/basic_layers.py | 28 +++++----
python/mxnet/gluon/rnn/rnn_cell.py | 62 ++++++++++---------
tests/python/conftest.py | 79 +++++++++++++++++++++++++
tests/python/gpu/test_contrib_amp.py | 1 +
tests/python/train/test_bucketing.py | 3 +
tests/python/train/test_dtype.py | 7 ++-
tests/python/train/test_resnet_aug.py | 7 ++-
tests/python/unittest/onnx/mxnet_export_test.py | 2 +-
tests/python/unittest/test_autograd.py | 3 +
tests/python/unittest/test_gluon.py | 37 +++++++-----
tests/python/unittest/test_gluon_data.py | 3 +
tests/python/unittest/test_module.py | 2 +
16 files changed, 183 insertions(+), 123 deletions(-)
diff --git a/conftest.py b/conftest.py
index 7a0aa44..0500818 100644
--- a/conftest.py
+++ b/conftest.py
@@ -230,50 +230,3 @@ def doctest(doctest_namespace):
logging.warning('Unable to import numpy/mxnet. Skipping conftest.')
import doctest
doctest.ELLIPSIS_MARKER = '-etc-'
-
-
-@pytest.fixture(scope='session')
-def mxnet_module():
- import mxnet
- return mxnet
-
-
-@pytest.fixture()
-# @pytest.fixture(autouse=True) # Fix all the bugs and mark this autouse=True
-def check_leak_ndarray(mxnet_module):
- # Collect garbage prior to running the next test
- gc.collect()
- # Enable gc debug mode to check if the test leaks any arrays
- gc_flags = gc.get_debug()
- gc.set_debug(gc.DEBUG_SAVEALL)
-
- # Run the test
- yield
-
- # Check for leaked NDArrays
- gc.collect()
- gc.set_debug(gc_flags) # reset gc flags
-
- seen = set()
- def has_array(element):
- try:
- if element in seen:
- return False
- seen.add(element)
- except TypeError: # unhashable
- pass
-
- if isinstance(element, mxnet_module.nd._internal.NDArrayBase):
- return True
- elif hasattr(element, '__dict__'):
- return any(has_array(x) for x in vars(element))
- elif isinstance(element, dict):
- return any(has_array(x) for x in element.items())
- else:
- try:
- return any(has_array(x) for x in element)
- except (TypeError, KeyError):
- return False
-
- assert not any(has_array(x) for x in gc.garbage), 'Found leaked NDArrays due to reference cycles'
- del gc.garbage[:]
diff --git a/pytest.ini b/pytest.ini
index 6c299d1..a88e501 100644
--- a/pytest.ini
+++ b/pytest.ini
@@ -23,6 +23,7 @@ markers =
gpu: mark a test that requires GPU.
integration: mark an integration test
onnx_coverage: ONNX coverage test
+ garbage_expected: this test leaks ndarray references. The tested functionality is broken or there is a Python bug.
env =
MXNET_HOME=tests/data
diff --git a/python/mxnet/gluon/block.py b/python/mxnet/gluon/block.py
index ded66a7..78b5a72 100644
--- a/python/mxnet/gluon/block.py
+++ b/python/mxnet/gluon/block.py
@@ -348,7 +348,7 @@ class Block(object):
return True
return False
elif isinstance(data, Block):
- return not data in children
+ return not data in (c() for c in children)
else:
return False
for k, v in self.__dict__.items():
@@ -426,7 +426,7 @@ class Block(object):
pattern = re.compile(select)
ret.update({name:value for name, value in self.params.items() if pattern.match(name)})
for cld in self._children.values():
- ret.update(cld.collect_params(select=select))
+ ret.update(cld().collect_params(select=select))
return ret
def _collect_params_with_prefix(self, prefix=''):
@@ -434,7 +434,7 @@ class Block(object):
prefix += '.'
ret = {prefix + key : val for key, val in self._reg_params.items()}
for name, child in self._children.items():
- ret.update(child._collect_params_with_prefix(prefix + name))
+ ret.update(child()._collect_params_with_prefix(prefix + name))
return ret
def save_parameters(self, filename, deduplicate=False):
@@ -602,7 +602,7 @@ class Block(object):
attributes will be registered automatically."""
if name is None:
name = str(len(self._children))
- self._children[name] = block
+ self._children[name] = weakref.ref(block)
def register_forward_pre_hook(self, hook):
r"""Registers a forward pre-hook on the block.
@@ -655,7 +655,7 @@ class Block(object):
this block
"""
for cld in self._children.values():
- cld.apply(fn)
+ cld().apply(fn)
fn(self)
return self
@@ -682,7 +682,7 @@ class Block(object):
""" Please refer description of HybridBlock hybridize().
"""
for cld in self._children.values():
- cld.hybridize(active, **kwargs)
+ cld().hybridize(active, **kwargs)
def cast(self, dtype):
"""Cast this Block to use another data type.
@@ -693,7 +693,7 @@ class Block(object):
The new data type.
"""
for child in self._children.values():
- child.cast(dtype)
+ child().cast(dtype)
for _, param in self.params.items():
param.cast(dtype)
@@ -737,7 +737,7 @@ class Block(object):
If True, monitor both input and output, otherwise monitor output only.
"""
for cld in self._children.values():
- cld.register_op_hook(callback, monitor_all)
+ cld().register_op_hook(callback, monitor_all)
def summary(self, *inputs):
"""Print the summary of the model's output and parameters.
@@ -1315,8 +1315,8 @@ class HybridBlock(Block):
self._callback = c_callback
self._monitor_all = monitor_all
for cld in self._children.values():
- cld._callback = c_callback
- cld._monitor_all = monitor_all
+ cld()._callback = c_callback
+ cld()._monitor_all = monitor_all
def __call__(self, x, *args):
if self.hybrid_forward.__func__ is not HybridBlock.hybrid_forward:
diff --git a/python/mxnet/gluon/contrib/nn/basic_layers.py b/python/mxnet/gluon/contrib/nn/basic_layers.py
index 5df1a1e..9ba6490 100644
--- a/python/mxnet/gluon/contrib/nn/basic_layers.py
+++ b/python/mxnet/gluon/contrib/nn/basic_layers.py
@@ -56,7 +56,7 @@ class Concurrent(Sequential):
def forward(self, x):
out = []
for block in self._children.values():
- out.append(block(x))
+ out.append(block()(x))
out = nd.concat(*out, dim=self.axis)
return out
@@ -89,7 +89,7 @@ class HybridConcurrent(HybridSequential):
def hybrid_forward(self, F, x):
out = []
for block in self._children.values():
- out.append(block(x))
+ out.append(block()(x))
out = F.concat(*out, dim=self.axis)
return out
diff --git a/python/mxnet/gluon/nn/basic_layers.py b/python/mxnet/gluon/nn/basic_layers.py
index 016f523..6ab611b 100644
--- a/python/mxnet/gluon/nn/basic_layers.py
+++ b/python/mxnet/gluon/nn/basic_layers.py
@@ -44,15 +44,17 @@ class Sequential(Block):
"""
def __init__(self, prefix=None, params=None):
super(Sequential, self).__init__(prefix=prefix, params=params)
+ self._layers = []
def add(self, *blocks):
"""Adds block on top of the stack."""
for block in blocks:
+ self._layers.append(block)
self.register_child(block)
def forward(self, x, *args):
for block in self._children.values():
- x = block(x, *args)
+ x = block()(x, *args)
args = []
if isinstance(x, (tuple, list)):
args = x[1:]
@@ -64,20 +66,19 @@ class Sequential(Block):
def __repr__(self):
s = '{name}(\n{modstr}\n)'
modstr = '\n'.join([' ({key}): {block}'.format(key=key,
- block=_indent(block.__repr__(), 2))
+ block=_indent(block().__repr__(), 2))
for key, block in self._children.items()])
- return s.format(name=self.__class__.__name__,
- modstr=modstr)
+ return s.format(name=self.__class__.__name__, modstr=modstr)
def __getitem__(self, key):
layers = list(self._children.values())[key]
if isinstance(layers, list):
net = type(self)(prefix=self._prefix)
with net.name_scope():
- net.add(*layers)
+ net.add(*(l() for l in layers))
return net
else:
- return layers
+ return layers()
def __len__(self):
return len(self._children)
@@ -93,7 +94,7 @@ class Sequential(Block):
**kwargs : string
Additional flags for hybridized operator.
"""
- if self._children and all(isinstance(c, HybridBlock) for c in self._children.values()):
+ if self._children and all(isinstance(c(), HybridBlock) for c in self._children.values()):
warnings.warn(
"All children of this Sequential layer '%s' are HybridBlocks. Consider "
"using HybridSequential for the best performance."%self.prefix, stacklevel=2)
@@ -114,15 +115,17 @@ class HybridSequential(HybridBlock):
"""
def __init__(self, prefix=None, params=None):
super(HybridSequential, self).__init__(prefix=prefix, params=params)
+ self._layers = []
def add(self, *blocks):
"""Adds block on top of the stack."""
for block in blocks:
+ self._layers.append(block)
self.register_child(block)
def hybrid_forward(self, F, x, *args):
for block in self._children.values():
- x = block(x, *args)
+ x = block()(x, *args)
args = []
if isinstance(x, (tuple, list)):
args = x[1:]
@@ -134,20 +137,19 @@ class HybridSequential(HybridBlock):
def __repr__(self):
s = '{name}(\n{modstr}\n)'
modstr = '\n'.join([' ({key}): {block}'.format(key=key,
- block=_indent(block.__repr__(), 2))
+ block=_indent(block().__repr__(), 2))
for key, block in self._children.items()])
- return s.format(name=self.__class__.__name__,
- modstr=modstr)
+ return s.format(name=self.__class__.__name__, modstr=modstr)
def __getitem__(self, key):
layers = list(self._children.values())[key]
if isinstance(layers, list):
net = type(self)(prefix=self._prefix)
with net.name_scope():
- net.add(*layers)
+ net.add(*(l() for l in layers))
return net
else:
- return layers
+ return layers()
def __len__(self):
return len(self._children)
diff --git a/python/mxnet/gluon/rnn/rnn_cell.py b/python/mxnet/gluon/rnn/rnn_cell.py
index e81d8ac..fe72c6a 100644
--- a/python/mxnet/gluon/rnn/rnn_cell.py
+++ b/python/mxnet/gluon/rnn/rnn_cell.py
@@ -35,10 +35,10 @@ from ..nn import LeakyReLU
def _cells_state_info(cells, batch_size):
- return sum([c.state_info(batch_size) for c in cells], [])
+ return sum([c().state_info(batch_size) for c in cells], [])
def _cells_begin_state(cells, **kwargs):
- return sum([c.begin_state(**kwargs) for c in cells], [])
+ return sum([c().begin_state(**kwargs) for c in cells], [])
def _get_begin_state(cell, F, begin_state, inputs, batch_size):
if begin_state is None:
@@ -145,7 +145,7 @@ class RecurrentCell(Block):
self._init_counter = -1
self._counter = -1
for cell in self._children.values():
- cell.reset()
+ cell().reset()
def state_info(self, batch_size=0):
"""shape and layout information of states"""
@@ -704,11 +704,12 @@ class SequentialRNNCell(RecurrentCell):
"""Sequentially stacking multiple RNN cells."""
def __init__(self, prefix=None, params=None):
super(SequentialRNNCell, self).__init__(prefix=prefix, params=params)
+ self._layers = []
def __repr__(self):
s = '{name}(\n{modstr}\n)'
return s.format(name=self.__class__.__name__,
- modstr='\n'.join(['({i}): {m}'.format(i=i, m=_indent(m.__repr__(), 2))
+ modstr='\n'.join(['({i}): {m}'.format(i=i, m=_indent(m().__repr__(), 2))
for i, m in self._children.items()]))
def add(self, cell):
@@ -719,6 +720,7 @@ class SequentialRNNCell(RecurrentCell):
cell : RecurrentCell
The cell to add.
"""
+ self._layers.append(cell)
self.register_child(cell)
def state_info(self, batch_size=0):
@@ -734,13 +736,13 @@ class SequentialRNNCell(RecurrentCell):
self._counter += 1
next_states = []
p = 0
- assert all(not isinstance(cell, BidirectionalCell) for cell in self._children.values())
+ assert all(not isinstance(cell(), BidirectionalCell) for cell in self._children.values())
for cell in self._children.values():
- assert not isinstance(cell, BidirectionalCell)
- n = len(cell.state_info())
+ assert not isinstance(cell(), BidirectionalCell)
+ n = len(cell().state_info())
state = states[p:p+n]
p += n
- inputs, state = cell(inputs, state)
+ inputs, state = cell()(inputs, state)
next_states.append(state)
return inputs, sum(next_states, [])
@@ -756,19 +758,19 @@ class SequentialRNNCell(RecurrentCell):
p = 0
next_states = []
for i, cell in enumerate(self._children.values()):
- n = len(cell.state_info())
+ n = len(cell().state_info())
states = begin_state[p:p+n]
p += n
- inputs, states = cell.unroll(length, inputs=inputs, begin_state=states,
- layout=layout,
- merge_outputs=None if i < num_cells-1 else merge_outputs,
- valid_length=valid_length)
+ inputs, states = cell().unroll(length, inputs=inputs, begin_state=states,
+ layout=layout,
+ merge_outputs=None if i < num_cells-1 else merge_outputs,
+ valid_length=valid_length)
next_states.extend(states)
return inputs, next_states
def __getitem__(self, i):
- return self._children[str(i)]
+ return self._children[str(i)]()
def __len__(self):
return len(self._children)
@@ -782,11 +784,12 @@ class HybridSequentialRNNCell(HybridRecurrentCell):
"""Sequentially stacking multiple HybridRNN cells."""
def __init__(self, prefix=None, params=None):
super(HybridSequentialRNNCell, self).__init__(prefix=prefix, params=params)
+ self._layers = []
def __repr__(self):
s = '{name}(\n{modstr}\n)'
return s.format(name=self.__class__.__name__,
- modstr='\n'.join(['({i}): {m}'.format(i=i, m=_indent(m.__repr__(), 2))
+ modstr='\n'.join(['({i}): {m}'.format(i=i, m=_indent(m().__repr__(), 2))
for i, m in self._children.items()]))
def add(self, cell):
@@ -797,6 +800,7 @@ class HybridSequentialRNNCell(HybridRecurrentCell):
cell : RecurrentCell
The cell to add.
"""
+ self._layers.append(cell)
self.register_child(cell)
def state_info(self, batch_size=0):
@@ -812,12 +816,12 @@ class HybridSequentialRNNCell(HybridRecurrentCell):
self._counter += 1
next_states = []
p = 0
- assert all(not isinstance(cell, BidirectionalCell) for cell in self._children.values())
+ assert all(not isinstance(cell(), BidirectionalCell) for cell in self._children.values())
for cell in self._children.values():
- n = len(cell.state_info())
+ n = len(cell().state_info())
state = states[p:p+n]
p += n
- inputs, state = cell(inputs, state)
+ inputs, state = cell()(inputs, state)
next_states.append(state)
return inputs, sum(next_states, [])
@@ -832,19 +836,19 @@ class HybridSequentialRNNCell(HybridRecurrentCell):
p = 0
next_states = []
for i, cell in enumerate(self._children.values()):
- n = len(cell.state_info())
+ n = len(cell().state_info())
states = begin_state[p:p+n]
p += n
- inputs, states = cell.unroll(length, inputs=inputs, begin_state=states,
- layout=layout,
- merge_outputs=None if i < num_cells-1 else merge_outputs,
- valid_length=valid_length)
+ inputs, states = cell().unroll(length, inputs=inputs, begin_state=states,
+ layout=layout,
+ merge_outputs=None if i < num_cells-1 else merge_outputs,
+ valid_length=valid_length)
next_states.extend(states)
return inputs, next_states
def __getitem__(self, i):
- return self._children[str(i)]
+ return self._children[str(i)]()
def __len__(self):
return len(self._children)
@@ -1048,8 +1052,8 @@ class BidirectionalCell(HybridRecurrentCell):
"""
def __init__(self, l_cell, r_cell, output_prefix='bi_'):
super(BidirectionalCell, self).__init__(prefix='', params=None)
- self.register_child(l_cell, 'l_cell')
- self.register_child(r_cell, 'r_cell')
+ self.l_cell = l_cell
+ self.r_cell = r_cell
self._output_prefix = output_prefix
def __call__(self, inputs, states):
@@ -1058,8 +1062,8 @@ class BidirectionalCell(HybridRecurrentCell):
def __repr__(self):
s = '{name}(forward={l_cell}, backward={r_cell})'
return s.format(name=self.__class__.__name__,
- l_cell=self._children['l_cell'],
- r_cell=self._children['r_cell'])
+ l_cell=self._children['l_cell'](),
+ r_cell=self._children['r_cell']())
def state_info(self, batch_size=0):
return _cells_state_info(self._children.values(), batch_size)
@@ -1080,7 +1084,7 @@ class BidirectionalCell(HybridRecurrentCell):
begin_state = _get_begin_state(self, F, begin_state, inputs, batch_size)
states = begin_state
- l_cell, r_cell = self._children.values()
+ l_cell, r_cell = [c() for c in self._children.values()]
l_outputs, l_states = l_cell.unroll(length, inputs=inputs,
begin_state=states[:len(l_cell.state_info(batch_size))],
layout=layout, merge_outputs=merge_outputs,
diff --git a/tests/python/conftest.py b/tests/python/conftest.py
new file mode 100644
index 0000000..4dab81d
--- /dev/null
+++ b/tests/python/conftest.py
@@ -0,0 +1,79 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""conftest.py contains configuration for pytest."""
+
+import gc
+import platform
+
+import mxnet as mx
+import pytest
+
+
+@pytest.fixture(autouse=True)
+def check_leak_ndarray(request):
+ garbage_expected = request.node.get_closest_marker('garbage_expected')
+ if garbage_expected: # Some tests leak references. They should be fixed.
+ yield # run test
+ return
+
+ if 'centos' in platform.platform():
+ # Multiple tests are failing due to reference leaks on CentOS. It's not
+ # yet known why there are more memory leaks in the Python 3.6.9 version
+ # shipped on CentOS compared to the Python 3.6.9 version shipped in
+ # Ubuntu.
+ yield
+ return
+
+ del gc.garbage[:]
+ # Collect garbage prior to running the next test
+ gc.collect()
+ # Enable gc debug mode to check if the test leaks any arrays
+ gc_flags = gc.get_debug()
+ gc.set_debug(gc.DEBUG_SAVEALL)
+
+ # Run the test
+ yield
+
+ # Check for leaked NDArrays
+ gc.collect()
+ gc.set_debug(gc_flags) # reset gc flags
+
+ seen = set()
+ def has_array(element):
+ try:
+ if element in seen:
+ return False
+ seen.add(element)
+ except (TypeError, ValueError): # unhashable
+ pass
+
+ if isinstance(element, mx.nd._internal.NDArrayBase):
+ return True
+ elif isinstance(element, mx.sym._internal.SymbolBase):
+ return False
+ elif hasattr(element, '__dict__'):
+ return any(has_array(x) for x in vars(element))
+ elif isinstance(element, dict):
+ return any(has_array(x) for x in element.items())
+ else:
+ try:
+ return any(has_array(x) for x in element)
+ except (TypeError, KeyError, RecursionError):
+ return False
+
+ assert not any(has_array(x) for x in gc.garbage), 'Found leaked NDArrays due to reference cycles'
+ del gc.garbage[:]
diff --git a/tests/python/gpu/test_contrib_amp.py b/tests/python/gpu/test_contrib_amp.py
index 14a737b..4d943bd 100644
--- a/tests/python/gpu/test_contrib_amp.py
+++ b/tests/python/gpu/test_contrib_amp.py
@@ -105,6 +105,7 @@ def test_amp_coverage(amp_tests):
safest option""")
@with_seed()
+@pytest.mark.garbage_expected
def test_amp_conversion(amp_tests):
def check_amp_convert_symbol():
x = mx.sym.var("x")
diff --git a/tests/python/train/test_bucketing.py b/tests/python/train/test_bucketing.py
index f4b8f41..6734a5d 100644
--- a/tests/python/train/test_bucketing.py
+++ b/tests/python/train/test_bucketing.py
@@ -22,6 +22,8 @@ import random
from random import randint
from mxnet.contrib.amp import amp
+import pytest
+
def prepare_bucketing_data(buckets, len_vocab, batch_size, invalid_label, num_sentence):
train_sent = []
@@ -111,6 +113,7 @@ def train_model(context=mx.cpu()):
return model
+@pytest.mark.garbage_expected
def test_bucket_module():
# This test forecasts random sequence of words to check bucketing.
# We cannot guarantee the accuracy of such an impossible task, and comments out the following line.
diff --git a/tests/python/train/test_dtype.py b/tests/python/train/test_dtype.py
index 75a0f45..6e47d3c 100644
--- a/tests/python/train/test_dtype.py
+++ b/tests/python/train/test_dtype.py
@@ -15,15 +15,16 @@
# specific language governing permissions and limitations
# under the License.
-# pylint: skip-file
-import sys
-sys.path.insert(0, '../../python')
import mxnet as mx
import numpy as np
import os, pickle, gzip
import logging
from mxnet.test_utils import get_cifar10
+import pytest
+
+
+@pytest.mark.garbage_expected
def test_cifar10(tmpdir):
batch_size = 128
diff --git a/tests/python/train/test_resnet_aug.py b/tests/python/train/test_resnet_aug.py
index 14c2285..a148a67 100644
--- a/tests/python/train/test_resnet_aug.py
+++ b/tests/python/train/test_resnet_aug.py
@@ -15,15 +15,16 @@
# specific language governing permissions and limitations
# under the License.
-# pylint: skip-file
-import sys
-sys.path.insert(0, '../../python')
import mxnet as mx
import numpy as np
import os, pickle, gzip
import logging
from mxnet.test_utils import get_cifar10
+import pytest
+
+
+@pytest.mark.garbage_expected
def test_cifar10(tmpdir):
batch_size = 128
diff --git a/tests/python/unittest/onnx/mxnet_export_test.py b/tests/python/unittest/onnx/mxnet_export_test.py
index 117a2cf..40d7d4e 100644
--- a/tests/python/unittest/onnx/mxnet_export_test.py
+++ b/tests/python/unittest/onnx/mxnet_export_test.py
@@ -105,7 +105,7 @@ class TestExport(unittest.TestCase):
self.net.add(nn.Dense(100 + i * 10, activation='relu'))
def hybrid_forward(self, F, x):
- out = tuple(block(x) for block in self.net._children.values())
+ out = tuple(block()(x) for block in self.net._children.values())
return out
net = MultiOutputBlock()
diff --git a/tests/python/unittest/test_autograd.py b/tests/python/unittest/test_autograd.py
index 148325c..ee80d29 100644
--- a/tests/python/unittest/test_autograd.py
+++ b/tests/python/unittest/test_autograd.py
@@ -23,6 +23,8 @@ from mxnet.test_utils import *
from common import setup_module, with_seed, teardown_module, xfail_when_nonstandard_decimal_separator
from mxnet.test_utils import EnvManager
+import pytest
+
def grad_and_loss(func, argnum=None):
"""Return function that computes both gradient of arguments and loss value.
@@ -344,6 +346,7 @@ def test_is_train():
assert y.asnumpy().max() == 2 and y.asnumpy().min() == 0
@with_seed()
+@pytest.mark.garbage_expected
def test_function():
class func(Function):
def forward(self, x, y):
diff --git a/tests/python/unittest/test_gluon.py b/tests/python/unittest/test_gluon.py
index da13aff..0cc5d68 100644
--- a/tests/python/unittest/test_gluon.py
+++ b/tests/python/unittest/test_gluon.py
@@ -1040,11 +1040,11 @@ def test_block_attr_param():
def test_block_attr_regular():
b = gluon.Block()
- # set block attribute also sets _children
+ # set block attribute also sets a weakref in _children
b.c = gluon.Block()
c2 = gluon.Block()
b.c = c2
- assert b.c is c2 and list(b._children.values())[0] is c2
+ assert b.c is c2 and list(b._children.values())[0]() is c2
@with_seed()
@@ -1420,18 +1420,21 @@ def test_activations():
prelu_multichannel.initialize()
assert_almost_equal(prelu_multichannel(x).asnumpy(), np.array([[-0.01, 0.1], [-0.025, 0.1], [-0.05, 0.1]]))
- gelu = mx.gluon.nn.GELU()
- def gelu_test(x):
- CUBE_CONSTANT = 0.044715
- ROOT_TWO_OVER_PI = 0.7978845608028654
- def g(x):
- return ROOT_TWO_OVER_PI * (x + CUBE_CONSTANT * x * x * x)
- def f(x):
- return 1.0 + mx.nd.tanh(g(x))
- def gelu(x):
- return 0.5 * x * f(x)
- for test_point, ref_point in zip(gelu_test(point_to_validate), gelu(point_to_validate)):
- assert test_point == ref_point
+ # https://github.com/apache/incubator-mxnet/issues/18381
+ # gelu = mx.gluon.nn.GELU()
+ # def gelu_test(x):
+ # CUBE_CONSTANT = 0.044715
+ # ROOT_TWO_OVER_PI = 0.7978845608028654
+ # def g(x):
+ # return ROOT_TWO_OVER_PI * (x + CUBE_CONSTANT * x * x * x)
+ # def f(x):
+ # return 1.0 + mx.nd.tanh(g(x))
+ # def gelu(x):
+ # return 0.5 * x * f(x)
+ # return [gelu(x_i) for x_i in x]
+
+ # for test_point, ref_point in zip(gelu_test(point_to_validate), gelu(point_to_validate)):
+ # assert test_point == ref_point
@with_seed()
@@ -3230,5 +3233,9 @@ def test_reqs_switching_training_inference():
@pytest.mark.usefixtures("check_leak_ndarray")
def test_no_memory_leak_in_gluon():
- net = mx.gluon.nn.Dense(10, in_units=10)
+ class MyNet(mx.gluon.Block):
+ def __init__(self):
+ super().__init__()
+ self.net = mx.gluon.nn.Dense(10, in_units=10)
+ net = MyNet()
net.initialize()
diff --git a/tests/python/unittest/test_gluon_data.py b/tests/python/unittest/test_gluon_data.py
index 9d24f7b..b1571cc 100644
--- a/tests/python/unittest/test_gluon_data.py
+++ b/tests/python/unittest/test_gluon_data.py
@@ -225,6 +225,7 @@ def test_image_list_dataset_handle(prepare_record):
assert label == 0
@with_seed()
+@pytest.mark.garbage_expected
def test_list_dataset():
for num_worker in range(0, 3):
data = mx.gluon.data.DataLoader([([1,2], 0), ([3, 4], 1)], batch_size=1, num_workers=num_worker)
@@ -239,6 +240,7 @@ class _Dataset(gluon.data.Dataset):
return mx.nd.full((10,), key)
@with_seed()
+@pytest.mark.garbage_expected
def test_multi_worker():
data = _Dataset()
for thread_pool in [True, False]:
@@ -502,6 +504,7 @@ def test_dataset_take_handle():
total += sample
assert total == expected_total
+@pytest.mark.garbage_expected
def test_dataloader_scope():
"""
Bug: Gluon DataLoader terminates the process pool early while
diff --git a/tests/python/unittest/test_module.py b/tests/python/unittest/test_module.py
index d8fb02e..bfb72a4 100644
--- a/tests/python/unittest/test_module.py
+++ b/tests/python/unittest/test_module.py
@@ -212,6 +212,7 @@ def test_save_load(ctx, get_updater, tmpdir):
@with_seed()
+@pytest.mark.garbage_expected
def test_bucketing_save_load(tmpdir):
previous_update_on_kvstore = os.getenv('MXNET_UPDATE_ON_KVSTORE', "1")
os.putenv('MXNET_UPDATE_ON_KVSTORE', '1')
@@ -462,6 +463,7 @@ def test_module_set_params():
@with_seed()
+@pytest.mark.garbage_expected
def test_monitor():
# data iter
data = mx.nd.array([[0.05, .10]]);