Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

Paddle: Validate LSTM WeightList size (#34576)

Mang Guodcfdc0ada4aa
diff --git a/src/frontends/paddle/src/op/lstm.cpp b/src/frontends/paddle/src/op/lstm.cpp
index 0e64932ba9e..78c326019ed 100644
--- a/src/frontends/paddle/src/op/lstm.cpp
+++ b/src/frontends/paddle/src/op/lstm.cpp
@@ -31,9 +31,10 @@ struct LSTMNgInputMap {
//[begin. end)
auto weight_list = node.get_ng_inputs("WeightList");
auto weight_begin = weight_list.begin();
- auto weight_end = std::next(weight_begin, weight_list.size() / 2);
- auto bias_begin = weight_end;
+ const size_t half_size = weight_list.size() / 2;
int bidirect_len = node.get_attribute<bool>("is_bidirec") ? 4 : 2;
+ auto weight_end = std::next(weight_begin, half_size);
+ auto bias_begin = weight_end;
int layer_weight_start = layer * bidirect_len;
int layer_weight_end = bidirect_len + layer * bidirect_len;
int layer_bias_start = layer * bidirect_len;
@@ -155,6 +156,29 @@ NamedOutputs lstm(const NodeContext& node) {
auto prev_inputs = node.get_ng_inputs("Input");
Output<Node> prev_output = prev_inputs[0];
LSTMAttributes attrs(node);
+ PADDLE_OP_CHECK(node, attrs.m_layers > 0, "num_layers must be positive for LSTM.");
+ auto weight_list = node.get_ng_inputs("WeightList");
+ PADDLE_OP_CHECK(node,
+ (weight_list.size() % 2) == 0,
+ "WeightList size must be even (weights + biases).",
+ " Got ",
+ weight_list.size(),
+ ".");
+ const size_t half_size = weight_list.size() / 2;
+ const int bidirect_len_weights = node.get_attribute<bool>("is_bidirec") ? 4 : 2;
+ const size_t required_per_half = static_cast<size_t>(attrs.m_layers) * static_cast<size_t>(bidirect_len_weights);
+ PADDLE_OP_CHECK(node,
+ half_size >= required_per_half,
+ "WeightList size is insufficient for num_layers and is_bidirec. ",
+ "half_size=",
+ half_size,
+ ", required_per_half=",
+ required_per_half,
+ ", num_layers=",
+ attrs.m_layers,
+ ", is_bidirec=",
+ node.get_attribute<bool>("is_bidirec"),
+ ".");
OutputVector final_h;
OutputVector final_c;
auto axis_const = std::make_shared<opset6::Constant>(element::i64, Shape{}, 0);
diff --git a/src/frontends/paddle/tests/test_models/gen_scripts/generate_rnn_lstm.py b/src/frontends/paddle/tests/test_models/gen_scripts/generate_rnn_lstm.py
index 5eaa1b9e4be..c02957cdc99 100644
--- a/src/frontends/paddle/tests/test_models/gen_scripts/generate_rnn_lstm.py
+++ b/src/frontends/paddle/tests/test_models/gen_scripts/generate_rnn_lstm.py
@@ -2,11 +2,50 @@
# SPDX-License-Identifier: Apache-2.0
import numpy as np
+import os
from save_model import saveModel
import sys
-def paddle_rnn_lstm(input_size, hidden_size, layers, direction, seq_len):
+def _get_framework_pb2():
+ try:
+ from paddle.fluid.proto import framework_pb2
+ return framework_pb2
+ except Exception:
+ pass
+ try:
+ from paddle.base.proto import framework_pb2
+ return framework_pb2
+ except Exception:
+ from paddle.framework.proto import framework_pb2
+ return framework_pb2
+
+
+def _corrupt_weightlist_inputs(model_path: str):
+ framework_pb2 = _get_framework_pb2()
+ prog = framework_pb2.ProgramDesc()
+ with open(model_path, "rb") as f:
+ prog.ParseFromString(f.read())
+
+ modified = False
+ for block in prog.blocks:
+ for op in block.ops:
+ for inp in op.inputs:
+ if inp.parameter == "WeightList" and len(inp.arguments) > 0:
+ if len(inp.arguments) >= 2:
+ del inp.arguments[-2:]
+ else:
+ del inp.arguments[:]
+ modified = True
+
+ if not modified:
+ raise RuntimeError("Failed to modify WeightList inputs in model")
+
+ with open(model_path, "wb") as f:
+ f.write(prog.SerializeToString())
+
+
+def paddle_rnn_lstm(input_size, hidden_size, layers, direction, seq_len, name_override=None):
import paddle
paddle.enable_static()
main_program = paddle.static.Program()
@@ -40,7 +79,8 @@ def paddle_rnn_lstm(input_size, hidden_size, layers, direction, seq_len):
np.float32), 'sl': np.array(seq_len).astype(np.int32)},
fetch_list=[y, h, c],
program=main_program)
- saveModel("rnn_lstm_layer_" + str(layers) + '_' + str(direction) + '_seq_len_' + str(len(seq_len)), exe, feed_vars=[data, seq_lengths],
+ model_name = name_override or ("rnn_lstm_layer_" + str(layers) + '_' + str(direction) + '_seq_len_' + str(len(seq_len)))
+ saveModel(model_name, exe, feed_vars=[data, seq_lengths],
fetchlist=[y, h, c], inputs=[np.ones([4, 3, input_size]).astype(np.float32), np.array(seq_len).astype(np.int32)], outputs=outs, target_dir=sys.argv[1])
else:
outs = exe.run(
@@ -48,7 +88,8 @@ def paddle_rnn_lstm(input_size, hidden_size, layers, direction, seq_len):
np.float32)},
fetch_list=[y, h, c],
program=main_program)
- saveModel("rnn_lstm_layer_" + str(layers) + '_' + str(direction), exe, feed_vars=[data],
+ model_name = name_override or ("rnn_lstm_layer_" + str(layers) + '_' + str(direction))
+ saveModel(model_name, exe, feed_vars=[data],
fetchlist=[y, h, c], inputs=[np.ones([4, 3, input_size]).astype(np.float32)], outputs=outs, target_dir=sys.argv[1])
return outs[0]
@@ -104,3 +145,7 @@ if __name__ == "__main__":
for test in testCases:
paddle_rnn_lstm(test['input_size'], test['hidden_size'],
test['layers'], test['direction'], test['seq_len'])
+
+ paddle_rnn_lstm(2, 2, 1, 'forward', [], name_override='rnn_lstm_weightlist_oob')
+ model_path = os.path.join(sys.argv[1], 'rnn_lstm_weightlist_oob', 'rnn_lstm_weightlist_oob.pdmodel')
+ _corrupt_weightlist_inputs(model_path)
diff --git a/src/frontends/paddle/tests/throw_in_conversion.cpp b/src/frontends/paddle/tests/throw_in_conversion.cpp
index edcfc8f8b04..46318d5dcab 100644
--- a/src/frontends/paddle/tests/throw_in_conversion.cpp
+++ b/src/frontends/paddle/tests/throw_in_conversion.cpp
@@ -59,3 +59,28 @@ TEST(FrontEndConvertModelTest, set_value_invalid_attr_sizes) {
FAIL() << "Unexpected exception type: " << typeid(ex).name() << ": " << ex.what();
}
}
+
+TEST(FrontEndConvertModelTest, lstm_weightlist_size_mismatch) {
+ FrontEndManager fem;
+ FrontEnd::Ptr frontEnd;
+ InputModel::Ptr inputModel;
+ OV_ASSERT_NO_THROW(frontEnd = fem.load_by_framework(PADDLE_FE));
+ ASSERT_NE(frontEnd, nullptr);
+ auto model_filename =
+ FrontEndTestUtils::make_model_path(std::string(TEST_PADDLE_MODELS_DIRNAME) +
+ std::string("rnn_lstm_weightlist_oob/rnn_lstm_weightlist_oob.pdmodel"));
+ OV_ASSERT_NO_THROW(inputModel = frontEnd->load(model_filename));
+ ASSERT_NE(inputModel, nullptr);
+ try {
+ std::shared_ptr<ov::Model> model = frontEnd->convert(inputModel);
+ FAIL() << "Expected conversion failure for LSTM WeightList size mismatch";
+ } catch (const OpValidationFailure&) {
+ SUCCEED();
+ } catch (const OpConversionFailure&) {
+ SUCCEED();
+ } catch (const GeneralFailure&) {
+ SUCCEED();
+ } catch (const std::exception& ex) {
+ FAIL() << "Unexpected exception type: " << typeid(ex).name() << ": " << ex.what();
+ }
+}