Skip to content
This repository was archived by the owner on Nov 17, 2023. It is now read-only.

Commit 7875b91

Browse files
author
Lai Wei
committed
update with nosetest and fixed seed
1 parent 5b01a63 commit 7875b91

File tree

3 files changed

+56
-55
lines changed

3 files changed

+56
-55
lines changed

ci/docker/runtime_functions.sh

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1403,10 +1403,8 @@ nightly_estimator() {
14031403
set -ex
14041404
cd /work/mxnet/tests/nightly/estimator
14051405
export PYTHONPATH=/work/mxnet/python/
1406-
python test_estimator_cnn.py --type gpu
1407-
python test_sentiment_rnn.py --type gpu
1408-
python test_estimator_cnn.py --type cpu
1409-
python test_sentiment_rnn.py --type cpu
1406+
nosetests test_estimator_cnn.py
1407+
nosetests test_sentiment_rnn.py
14101408
}
14111409

14121410
# Deploy

tests/nightly/estimator/test_estimator_cnn.py

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,22 @@
1717

1818
# Test gluon estimator on CNN models
1919

20-
import argparse
21-
import numpy as np
20+
import os
21+
import sys
22+
2223
import mxnet as mx
24+
import numpy as np
2325
from mxnet import gluon, init, nd
2426
from mxnet.gluon import data
2527
from mxnet.gluon.contrib.estimator import estimator
2628
from mxnet.gluon.model_zoo import vision
2729

30+
# use with_seed decorator in python/unittest/common.py
31+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'python', 'unittest'))
32+
from common import with_seed
33+
import unittest
34+
35+
2836
def load_data_mnist(batch_size, resize=None, num_workers=4):
2937
'''
3038
Load MNIST dataset
@@ -44,6 +52,7 @@ def load_data_mnist(batch_size, resize=None, num_workers=4):
4452
num_workers=num_workers)
4553
return train_iter, test_iter
4654

55+
4756
def bilinear_kernel(in_channels, out_channels, kernel_size):
4857
'''
4958
Bilinear interpolation using transposed convolution
@@ -60,6 +69,7 @@ def bilinear_kernel(in_channels, out_channels, kernel_size):
6069
weight[range(in_channels), range(out_channels), :, :] = filt
6170
return nd.array(weight)
6271

72+
6373
def get_net(model_name, context):
6474
if model_name == 'FCN':
6575
num_classes = 21
@@ -82,6 +92,8 @@ def get_net(model_name, context):
8292
loss_axis = -1
8393
return net, input_shape, label_shape, loss_axis
8494

95+
96+
@with_seed()
8597
def test_estimator_cpu():
8698
'''
8799
Test estimator by doing one pass over each model with synthetic data
@@ -112,6 +124,10 @@ def test_estimator_cpu():
112124
val_data=val_data,
113125
epochs=1)
114126

127+
128+
# using fixed seed to reduce flakiness in accuracy assertion
129+
@with_seed(7)
130+
@unittest.skipIf(mx.context.num_gpus() < 1, "skip if no GPU")
115131
def test_estimator_gpu():
116132
'''
117133
Test estimator by training resnet18_v1 for 5 epochs on MNIST and verify accuracy
@@ -139,13 +155,8 @@ def test_estimator_gpu():
139155

140156
assert acc.get()[1] > 0.80
141157

158+
142159
if __name__ == '__main__':
143-
parser = argparse.ArgumentParser(description='test gluon estimator')
144-
parser.add_argument('--type', type=str, default='cpu')
145-
opt = parser.parse_args()
146-
if opt.type == 'cpu':
147-
test_estimator_cpu()
148-
elif opt.type == 'gpu':
149-
test_estimator_gpu()
150-
else:
151-
raise RuntimeError("Unknown test type")
160+
import nose
161+
162+
nose.runmodule()

tests/nightly/estimator/test_sentiment_rnn.py

Lines changed: 32 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,23 @@
2020
https://github.com/d2l-ai/d2l-en/blob/master/chapter_natural-language-processing/sentiment-analysis-rnn.md
2121
https://github.com/d2l-ai/d2l-en/blob/master/chapter_natural-language-processing/sentiment-analysis-cnn.md"""
2222

23-
import argparse
23+
import collections
2424
import os
25-
import tarfile
2625
import random
27-
import collections
26+
import sys
27+
import tarfile
28+
2829
import mxnet as mx
2930
from mxnet import nd, gluon
3031
from mxnet.contrib import text
3132
from mxnet.gluon import nn, rnn
3233
from mxnet.gluon.contrib.estimator import estimator
3334

35+
# use with_seed decorator in python/unittest/common.py
36+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'python', 'unittest'))
37+
from common import with_seed
38+
import unittest
39+
3440

3541
class TextCNN(nn.Block):
3642
def __init__(self, vocab, embed_size, kernel_sizes, num_channels,
@@ -175,14 +181,10 @@ def pad(x):
175181
return features, labels
176182

177183

178-
def run(net, train_dataloader, test_dataloader, **kwargs):
184+
def run(net, train_dataloader, test_dataloader, num_epochs, ctx, lr):
179185
'''
180186
Train a test sentiment model
181187
'''
182-
num_epochs = kwargs['epochs']
183-
ctx = kwargs['ctx']
184-
batch_size = kwargs['batch_size']
185-
lr = kwargs['lr']
186188

187189
# Define trainer
188190
trainer = mx.gluon.Trainer(net.collect_params(), 'adam', {'learning_rate': lr})
@@ -199,14 +201,17 @@ def run(net, train_dataloader, test_dataloader, **kwargs):
199201
return acc
200202

201203

202-
def test_estimator_cpu(**kwargs):
204+
@with_seed()
205+
def test_estimator_cpu():
203206
'''
204207
Test estimator by doing one pass over each model with synthetic data
205208
'''
206209
models = ['TextCNN', 'BiRNN']
207-
ctx = kwargs['ctx']
208-
batch_size = kwargs['batch_size']
209-
embed_size = kwargs['embed_size']
210+
ctx = mx.cpu()
211+
batch_size = 64
212+
embed_size = 100
213+
lr = 1
214+
num_epochs = 1
210215

211216
train_data = mx.nd.random.randint(low=0, high=100, shape=(2 * batch_size, 500))
212217
train_label = mx.nd.random.randint(low=0, high=2, shape=(2 * batch_size,))
@@ -229,18 +234,22 @@ def test_estimator_cpu(**kwargs):
229234
net = BiRNN(vocab_list, embed_size, num_hiddens, num_layers)
230235
net.initialize(mx.init.Xavier(), ctx=ctx)
231236

232-
run(net, train_dataloader, val_dataloader, **kwargs)
237+
run(net, train_dataloader, val_dataloader, num_epochs=num_epochs, ctx=ctx, lr=lr)
233238

234239

235-
def test_estimator_gpu(**kwargs):
240+
# using fixed seed to reduce flakiness in accuracy assertion
241+
@with_seed(7)
242+
@unittest.skipIf(mx.context.num_gpus() < 1, "skip if no GPU")
243+
def test_estimator_gpu():
236244
'''
237245
Test estimator by training Bidirectional RNN for 5 epochs on the IMDB dataset
238246
and verify accuracy
239247
'''
240-
ctx = kwargs['ctx']
241-
batch_size = kwargs['batch_size']
242-
num_epochs = kwargs['epochs']
243-
embed_size = kwargs['embed_size']
248+
ctx = mx.gpu(0)
249+
batch_size = 64
250+
num_epochs = 5
251+
embed_size = 100
252+
lr = 0.01
244253

245254
# data
246255
download_imdb()
@@ -253,8 +262,6 @@ def test_estimator_gpu(**kwargs):
253262
test_dataloader = gluon.data.DataLoader(test_set, batch_size)
254263

255264
# Model
256-
# using fixed seed to reduce flakiness in accuracy assertion
257-
mx.random.seed(7)
258265
num_hiddens, num_layers = 100, 2
259266
net = BiRNN(vocab, embed_size, num_hiddens, num_layers)
260267
net.initialize(mx.init.Xavier(), ctx=ctx)
@@ -265,27 +272,12 @@ def test_estimator_gpu(**kwargs):
265272
net.embedding.weight.set_data(glove_embedding.idx_to_vec)
266273
net.embedding.collect_params().setattr('grad_req', 'null')
267274

268-
acc = run(net, train_dataloader, test_dataloader, **kwargs)
275+
acc = run(net, train_dataloader, test_dataloader, num_epochs=num_epochs, ctx=ctx, lr=lr)
269276

270277
assert acc.get()[1] > 0.70
271278

272279

273-
parser = argparse.ArgumentParser(description='test gluon estimator')
274-
parser.add_argument('--type', type=str, default='cpu')
275-
opt = parser.parse_args()
276-
kwargs = {
277-
'batch_size': 64,
278-
'lr': 0.01,
279-
'embed_size': 100
280-
}
281-
282-
if opt.type == 'cpu':
283-
kwargs['ctx'] = mx.cpu()
284-
kwargs['epochs'] = 1
285-
test_estimator_cpu(**kwargs)
286-
elif opt.type == 'gpu':
287-
kwargs['ctx'] = mx.gpu()
288-
kwargs['epochs'] = 5
289-
test_estimator_gpu(**kwargs)
290-
else:
291-
raise RuntimeError("Unknown test type")
280+
if __name__ == '__main__':
281+
import nose
282+
283+
nose.runmodule()

0 commit comments

Comments
 (0)