OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[PyTorch FE] instance_norm: honor use_input_stats (#37978)
siyiweige48059cb8e317
diff --git a/src/frontends/pytorch/src/op/instance_norm.cpp b/src/frontends/pytorch/src/op/instance_norm.cppindex c7715438e00..06e11211eae 100644--- a/src/frontends/pytorch/src/op/instance_norm.cpp+++ b/src/frontends/pytorch/src/op/instance_norm.cpp@@ -86,18 +86,34 @@ OutputVector translate_instance_norm_train(const NodeContext& context,} // namespaceOutputVector translate_instance_norm(const NodeContext& context) {+ // aten::instance_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean,+ // Tensor? running_var, bool use_input_stats, float momentum, float eps,+ // bool cudnn_enabled) -> Tensornum_inputs_check(context, 8, 9);auto input = context.get_input(0);auto eps = context.const_input<float>(7);+ // input 5 is "use_input_stats": when True, normalization uses the per-instance (input)+ // statistics and any provided running_mean/running_var (inputs 3,4) are ignored; when False,+ // normalization uses the running statistics, which torch requires to be defined.+ bool use_input_stats = true;+ if (context.get_input_size() > 5 && !context.input_is_none(5)) {+ use_input_stats = context.const_input<bool>(5);+ }+ const bool have_running_stats = !context.input_is_none(3) && !context.input_is_none(4);Output<Node> rank;std::tie(std::ignore, rank) = get_shape_rank(context, input, true, element::i32);auto one = context.mark_node(v0::Constant::create(element::i32, Shape{}, {1}));auto two = context.mark_node(v0::Constant::create(element::i32, Shape{}, {2}));auto reduction_axes = context.mark_node(std::make_shared<v4::Range>(two, rank, one, element::i32));- if (context.input_is_none(3) && context.input_is_none(4)) {- return translate_instance_norm_inference(context, input, reduction_axes, eps);+ if (!use_input_stats) {+ // aten::instance_norm raises when the running statistics are missing, so reject the model+ // instead of silently normalizing with the input statistics.+ PYTORCH_OP_CONVERSION_CHECK(have_running_stats,+ "aten::instance_norm expects running_mean and running_var to be defined "+ "when use_input_stats is false");+ return translate_instance_norm_train(context, input, reduction_axes, eps);}- return translate_instance_norm_train(context, input, reduction_axes, eps);+ return translate_instance_norm_inference(context, input, reduction_axes, eps);};} // namespace ov::frontend::pytorch::opdiff --git a/tests/layer_tests/pytorch_tests/test_instance_norm.py b/tests/layer_tests/pytorch_tests/test_instance_norm.pyindex 5533590b09f..adc22268d2f 100644--- a/tests/layer_tests/pytorch_tests/test_instance_norm.py+++ b/tests/layer_tests/pytorch_tests/test_instance_norm.py@@ -14,16 +14,18 @@ class TestInstanceNorm(PytorchLayerTest):shape = shape5d[:ndim]return (self.random.randn(*shape),)- def create_model(self, weights=False, bias=False, mean_var=False, eps=1e-05):+ def create_model(self, weights=False, bias=False, mean_var=False, use_input_stats=None, eps=1e-05):import torchclass aten_instance_norm(torch.nn.Module):- def __init__(self, rng, weights=False, bias=False, mean_var=False, eps=1e-05):+ def __init__(self, rng, weights=False, bias=False, mean_var=False, use_input_stats=None, eps=1e-05):super().__init__()weights_shape = (6, )self.weight = rng.torch_randn(*weights_shape) if weights else Noneself.bias = None- self.use_input_stats = not mean_var+ # By default normalize with running statistics only when they are provided;+ # use_input_stats can be forced independently to exercise the corners below.+ self.use_input_stats = (not mean_var) if use_input_stats is None else use_input_statsif bias:self.bias = rng.torch_randn(*weights_shape)self.mean = None@@ -38,7 +40,7 @@ class TestInstanceNorm(PytorchLayerTest):return torch.instance_norm(x, self.weight, self.bias, self.mean, self.var, self.use_input_stats, 0.1, self.eps, False)- return aten_instance_norm(self.random, weights, bias, mean_var, eps), "aten::instance_norm"+ return aten_instance_norm(self.random, weights, bias, mean_var, use_input_stats, eps), "aten::instance_norm"@pytest.mark.parametrize("params",[@@ -51,7 +53,12 @@ class TestInstanceNorm(PytorchLayerTest):{"weights": False, 'bias': True, "mean_var": True},{"weights": False, 'bias': False, "mean_var": True},{"weights": False, 'bias': False,- "mean_var": True, "eps": 1.5}+ "mean_var": True, "eps": 1.5},+ # use_input_stats=True WITH running stats provided -> running stats must be IGNORED+ {"weights": True, 'bias': True, "mean_var": True, "use_input_stats": True},+ # use_input_stats=False WITH running stats provided -> running stats used+ {"weights": True, 'bias': True, "mean_var": True, "use_input_stats": False},+ {"weights": True, 'bias': False, "mean_var": True, "use_input_stats": True}])@pytest.mark.parametrize("kwargs_to_prepare_input", [{"ndim": 3},@@ -66,3 +73,56 @@ class TestInstanceNorm(PytorchLayerTest):self._test(*self.create_model(**params),ie_device, precision, ir_version, kwargs_to_prepare_input=kwargs_to_prepare_input,dynamic_shapes=not params.get("mean_var", False), use_mo_convert=False)+++class TestInstanceNormEvalMode(PytorchLayerTest):+ """use_input_stats=False requires running statistics, as in torch.++ torch raises "Expected running_mean and running_var to be defined when use_input_stats is+ false", so a model asking for the running statistics without providing them must be rejected+ instead of silently normalizing with the input statistics.+ """++ def create_model(self, stats):+ import torch++ class aten_instance_norm(torch.nn.Module):+ def __init__(self, mean, var):+ super().__init__()+ self.mean = mean+ self.var = var++ def forward(self, x):+ return torch.instance_norm(x, None, None, self.mean, self.var, False, 0.1, 1e-05, False)++ weights_shape = (6, )+ mean = self.random.torch_randn(*weights_shape) if stats in ("mean", "both") else None+ var = self.random.torch_randn(*weights_shape) if stats in ("var", "both") else None+ return aten_instance_norm(mean, var), "aten::instance_norm"++ @pytest.mark.parametrize("stats", ["none", "mean", "var"])+ @pytest.mark.precommit+ @pytest.mark.nightly+ def test_missing_running_stats_fails(self, stats, ie_device, precision, ir_version):+ import torch+ import openvino as ov++ model, _ = self.create_model(stats)+ example = torch.randn(3, 6, 10, 5)+ # tracing runs forward and torch itself rejects the missing statistics, so script the model+ # to hand the graph to the converter as is.+ scripted = torch.jit.script(model)+ with pytest.raises(ov.frontend.OpConversionFailure):+ ov.convert_model(scripted, example_input=(example, ))++ @pytest.mark.precommit+ @pytest.mark.nightly+ def test_running_stats_used(self, ie_device, precision, ir_version):+ import torch+ import openvino as ov++ model, _ = self.create_model("both")+ example = torch.randn(3, 6, 10, 5)+ # control case: with both statistics provided the same scripted model must still convert+ ov_model = ov.convert_model(torch.jit.script(model), example_input=(example, ))+ assert ov_model is not None