def test_static_api(self): train_program = paddle.static.Program() startup_program = paddle.static.Program() with paddle.static.program_guard(train_program, startup_program): x = paddle.static.data('x', [-1, self.feature_size]) labels = paddle.static.data('labels', [-1, 1], 'int64') weight = paddle.static.data('weight', [-1, self.feature_size]) bias = paddle.static.data('bias', [ -1, ]) path_table = None path_code = None if self.is_custom: path_table = paddle.static.data('path_table', [-1, -1], 'int64') path_code = paddle.static.data('path_code', [-1, -1], 'int64') out1 = F.hsigmoid_loss(x, labels, self.num_classes, weight, bias, path_table, path_code) weight_attr = paddle.framework.ParamAttr( initializer=I.NumpyArrayInitializer(self.weight_np)) bias_attr = paddle.framework.ParamAttr( initializer=I.NumpyArrayInitializer(self.bias_np)) m = paddle.nn.HSigmoidLoss(self.feature_size, self.num_classes, weight_attr, bias_attr, self.is_custom) out2 = m(x, labels, path_table, path_code) exe = paddle.static.Executor(self.place) exe.run(startup_program) feed_dict = { 'x': self.x_np, 'labels': self.labels_np, 'weight': self.weight_np, 'bias': self.bias_np } if self.is_custom: feed_dict["path_code"] = self.path_code_np feed_dict["path_table"] = self.path_table_np ret1, ret2 = exe.run(train_program, feed=feed_dict, fetch_list=[out1, out2]) for ret in [ret1, ret2]: self.assertTrue(np.allclose(self.out_np, ret))
def test_dygraph_api(self): paddle.disable_static(self.place) x = paddle.to_tensor(self.x_np) labels = paddle.to_tensor(self.labels_np) weight = paddle.to_tensor(self.weight_np) bias = paddle.to_tensor(self.bias_np) path_table = None path_code = None if self.is_custom: path_table = paddle.to_tensor(self.path_table_np) path_code = paddle.to_tensor(self.path_code_np) out1 = F.hsigmoid_loss(x, labels, self.num_classes, weight, bias, path_table, path_code) weight_attr = I.NumpyArrayInitializer(self.weight_np) bias_attr = I.NumpyArrayInitializer(self.bias_np) m = paddle.nn.HSigmoidLoss(self.feature_size, self.num_classes, weight_attr, bias_attr, self.is_custom) out2 = m(x, labels, path_table, path_code) for out in [out1, out2]: self.assertTrue(np.allclose(self.out_np, out.numpy())) paddle.enable_static()