Skip to content

Commit 51b7bbe

Browse files
authored
[cherry-pick] Update hapi predict interface (#28186)
* update hapi predict interface
1 parent f27d1be commit 51b7bbe

File tree

7 files changed

+52
-29
lines changed

7 files changed

+52
-29
lines changed

python/paddle/fluid/tests/unittests/test_rnn_decode_api.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -628,7 +628,7 @@ def _calc_output(self, place, mode="test", dygraph=True):
628628
model.prepare()
629629
if self.param_states:
630630
model.load(self.param_states, optim_state=None)
631-
return model.test_batch(self.inputs)
631+
return model.predict_batch(self.inputs)
632632

633633
def check_output_with_place(self, place, mode="test"):
634634
dygraph_output = self._calc_output(place, mode, dygraph=True)

python/paddle/hapi/model.py

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ def eval_batch(self, inputs, labels=None):
261261
self.mode = 'eval'
262262
return self._run(inputs, labels)
263263

264-
def test_batch(self, inputs):
264+
def predict_batch(self, inputs):
265265
self.mode = 'test'
266266
return self._run(inputs, None)
267267

@@ -723,7 +723,7 @@ def eval_batch(self, inputs, labels=None):
723723
else:
724724
return metrics
725725

726-
def test_batch(self, inputs):
726+
def predict_batch(self, inputs):
727727
self.model.network.eval()
728728
self.mode = 'test'
729729
inputs = [to_variable(x) for x in to_list(inputs)]
@@ -894,10 +894,13 @@ def train_batch(self, inputs, labels=None):
894894
Run one training step on a batch of data.
895895
896896
Args:
897-
inputs (list): A list of numpy.ndarray, each is a batch of
898-
input data.
899-
labels (list): A list of numpy.ndarray, each is a batch of
900-
input label. If has no labels, set None. Default is None.
897+
inputs (numpy.ndarray|Tensor|list): Batch of input data. It could
898+
be a numpy array or paddle.Tensor, or a list of arrays or
899+
tensors (in case the model has multiple inputs).
900+
labels (numpy.ndarray|Tensor|list): Batch of labels. It could be
901+
a numpy array or paddle.Tensor, or a list of arrays or tensors
902+
(in case the model has multiple labels). If has no labels,
903+
set None. Default is None.
901904
902905
Returns:
903906
A list of scalar training loss if the model has no metrics,
@@ -941,10 +944,13 @@ def eval_batch(self, inputs, labels=None):
941944
Run one evaluating step on a batch of data.
942945
943946
Args:
944-
inputs (list): A list of numpy.ndarray, each is a batch of
945-
input data.
946-
labels (list): A list of numpy.ndarray, each is a batch of
947-
input label. If has no labels, set None. Default is None.
947+
inputs (numpy.ndarray|Tensor|list): Batch of input data. It could
948+
be a numpy array or paddle.Tensor, or a list of arrays or
949+
tensors (in case the model has multiple inputs).
950+
labels (numpy.ndarray|Tensor|list): Batch of labels. It could be
951+
a numpy array or paddle.Tensor, or a list of arrays or tensors
952+
(in case the model has multiple labels). If has no labels,
953+
set None. Default is None.
948954
949955
Returns:
950956
A list of scalar testing loss if the model has no metrics,
@@ -984,13 +990,14 @@ def eval_batch(self, inputs, labels=None):
984990
self._update_inputs()
985991
return loss
986992

987-
def test_batch(self, inputs):
993+
def predict_batch(self, inputs):
988994
"""
989-
Run one testing step on a batch of data.
995+
Run one predicting step on a batch of data.
990996
991997
Args:
992-
inputs (list): A list of numpy.ndarray, each is a batch of
993-
input data.
998+
inputs (numpy.ndarray|Tensor|list): Batch of input data. It could
999+
be a numpy array or paddle.Tensor, or a list of arrays or
1000+
tensors (in case the model has multiple inputs).
9941001
9951002
Returns:
9961003
A list of numpy.ndarray of predictions, that is the outputs
@@ -1019,10 +1026,10 @@ def test_batch(self, inputs):
10191026
model = paddle.Model(net, input, label)
10201027
model.prepare()
10211028
data = np.random.random(size=(4,784)).astype(np.float32)
1022-
out = model.test_batch([data])
1029+
out = model.predict_batch([data])
10231030
print(out)
10241031
"""
1025-
loss = self._adapter.test_batch(inputs)
1032+
loss = self._adapter.predict_batch(inputs)
10261033
if fluid.in_dygraph_mode() and self._input_shapes is None:
10271034
self._update_inputs()
10281035
return loss
@@ -1847,10 +1854,9 @@ def _run_one_epoch(self, data_loader, callbacks, mode, logs={}):
18471854
logs[k] = v
18481855
else:
18491856
if self._inputs is not None:
1850-
outs = getattr(self,
1851-
mode + '_batch')(data[:len(self._inputs)])
1857+
outs = self.predict_batch(data[:len(self._inputs)])
18521858
else:
1853-
outs = getattr(self, mode + '_batch')(data)
1859+
outs = self.predict_batch(data)
18541860

18551861
outputs.append(outs)
18561862

python/paddle/tests/test_model.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,17 @@ def predict(self, dynamic):
284284

285285
fluid.disable_dygraph() if dynamic else None
286286

287+
def test_predict_without_inputs(self):
288+
fluid.enable_dygraph(self.device)
289+
model = Model(LeNet())
290+
model.prepare()
291+
model.load(self.weight_path)
292+
model._inputs = None
293+
output = model.predict(
294+
self.test_dataset, batch_size=64, stack_outputs=True)
295+
np.testing.assert_equal(output[0].shape[0], len(self.test_dataset))
296+
fluid.disable_dygraph()
297+
287298

288299
class MyModel(paddle.nn.Layer):
289300
def __init__(self):
@@ -370,7 +381,7 @@ def get_expect():
370381
inputs = [InputSpec([None, dim], 'float32', 'x')]
371382
model = Model(net, inputs)
372383
model.prepare()
373-
out, = model.test_batch([data])
384+
out, = model.predict_batch([data])
374385

375386
np.testing.assert_allclose(out, ref, rtol=1e-6)
376387
fluid.disable_dygraph() if dynamic else None
@@ -546,7 +557,7 @@ def test_export_deploy_model(self):
546557
np.random.random((1, 1, 28, 28)), dtype=np.float32)
547558

548559
model.save(save_dir, training=False)
549-
ori_results = model.test_batch(tensor_img)
560+
ori_results = model.predict_batch(tensor_img)
550561
fluid.disable_dygraph() if dynamic else None
551562

552563
place = fluid.CPUPlace() if not fluid.is_compiled_with_cuda(
@@ -569,7 +580,7 @@ def test_dygraph_export_deploy_model_about_inputs(self):
569580
mnist_data = MnistDataset(mode='train')
570581
paddle.disable_static()
571582
# without inputs
572-
for initial in ["fit", "train_batch", "eval_batch", "test_batch"]:
583+
for initial in ["fit", "train_batch", "eval_batch", "predict_batch"]:
573584
save_dir = tempfile.mkdtemp()
574585
if not os.path.exists(save_dir):
575586
os.makedirs(save_dir)
@@ -590,7 +601,7 @@ def test_dygraph_export_deploy_model_about_inputs(self):
590601
elif initial == "eval_batch":
591602
model.eval_batch([img], [label])
592603
else:
593-
model.test_batch([img])
604+
model.predict_batch([img])
594605

595606
model.save(save_dir, training=False)
596607
shutil.rmtree(save_dir)

python/paddle/tests/test_pretrained_model.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,10 @@ def infer(self, arch):
4040

4141
if dygraph:
4242
model.save(path)
43-
res['dygraph'] = model.test_batch(x)
43+
res['dygraph'] = model.predict_batch(x)
4444
else:
4545
model.load(path)
46-
res['static'] = model.test_batch(x)
46+
res['static'] = model.predict_batch(x)
4747

4848
if not dygraph:
4949
paddle.disable_static()

python/paddle/tests/test_transforms.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,12 @@ def test_to_tensor(self):
205205
assert isinstance(tensor, paddle.Tensor)
206206
np.testing.assert_equal(tensor.shape, (3, 50, 100))
207207

208+
def test_keys(self):
209+
fake_img1 = self.create_image((200, 150, 3))
210+
fake_img2 = self.create_image((200, 150, 3))
211+
trans_pad = transforms.Pad(10, keys=("image", ))
212+
fake_img_padded = trans_pad((fake_img1, fake_img2))
213+
208214
def test_exception(self):
209215
trans = transforms.Compose([transforms.Resize(-1)])
210216

python/paddle/tests/test_vision_models.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def models_infer(self, arch, pretrained=False, batch_norm=False):
3333
model = paddle.Model(net, input)
3434
model.prepare()
3535

36-
model.test_batch(x)
36+
model.predict_batch(x)
3737

3838
def test_mobilenetv2_pretrained(self):
3939
self.models_infer('mobilenet_v2', pretrained=False)
@@ -77,7 +77,7 @@ def test_lenet(self):
7777
lenet.prepare()
7878

7979
x = np.array(np.random.random((2, 1, 28, 28)), dtype=np.float32)
80-
lenet.test_batch(x)
80+
lenet.predict_batch(x)
8181

8282

8383
if __name__ == '__main__':

python/paddle/vision/transforms/transforms.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,7 @@ def __call__(self, inputs):
272272
else:
273273
outputs.append(apply_func(inputs[i]))
274274
if len(inputs) > len(self.keys):
275-
outputs.extend(input[len(self.keys):])
275+
outputs.extend(inputs[len(self.keys):])
276276

277277
if len(outputs) == 1:
278278
outputs = outputs[0]

0 commit comments

Comments
 (0)