|
| 1 | +# Copyright (c) 2025 Intel Corporation |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# Unless required by applicable law or agreed to in writing, software |
| 7 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +# See the License for the specific language governing permissions and |
| 10 | +# limitations under the License. |
| 11 | + |
| 12 | +import torch |
| 13 | +from torch import nn |
| 14 | +from torch.overrides import _get_current_function_mode_stack |
| 15 | + |
| 16 | +from nncf.experimental.torch2.function_hook.graph.build_graph_mode import build_graph |
| 17 | +from nncf.experimental.torch2.function_hook.graph.graph_visualization import to_pydot |
| 18 | +from nncf.experimental.torch2.function_hook.hook_executor_mode import FunctionHookMode |
| 19 | +from nncf.experimental.torch2.function_hook.hook_executor_mode import disable_function_hook_mode |
| 20 | +from nncf.experimental.torch2.function_hook.wrapper import get_hook_storage |
| 21 | +from nncf.experimental.torch2.function_hook.wrapper import wrap_model |
| 22 | +from nncf.torch import disable_tracing |
| 23 | +from tests.cross_fw.shared.paths import TEST_ROOT |
| 24 | +from tests.torch2.utils import compare_with_reference_file |
| 25 | + |
| 26 | +REF_DIR = TEST_ROOT / "torch2" / "data" / "function_hook" / "disable_tracing" |
| 27 | + |
| 28 | + |
| 29 | +def test_disable_function_hook_mode(): |
| 30 | + model = wrap_model(nn.Conv2d(1, 1, 1)) |
| 31 | + with FunctionHookMode(model=model, hook_storage=get_hook_storage(model)) as ctx: |
| 32 | + assert ctx.enabled |
| 33 | + with disable_function_hook_mode(): |
| 34 | + assert not ctx.enabled |
| 35 | + assert ctx.enabled |
| 36 | + |
| 37 | + |
| 38 | +class ModelNoTrace(nn.Module): |
| 39 | + def __init__(self): |
| 40 | + super().__init__() |
| 41 | + |
| 42 | + def forward(self, x): |
| 43 | + x = x + 1 |
| 44 | + x = self.foo(x) |
| 45 | + x = x - 1 |
| 46 | + return x |
| 47 | + |
| 48 | + def foo(self, x): |
| 49 | + mode = _get_current_function_mode_stack() |
| 50 | + assert len(mode) == 1 |
| 51 | + assert isinstance(mode[0], FunctionHookMode) |
| 52 | + assert not mode[0].enabled |
| 53 | + return x - 1 |
| 54 | + |
| 55 | + |
| 56 | +disable_tracing(ModelNoTrace.foo) |
| 57 | + |
| 58 | + |
| 59 | +def test_build_graph_with_disable_tracing(regen_ref_data): |
| 60 | + model = wrap_model(ModelNoTrace()) |
| 61 | + graph = build_graph(model, torch.randn(1, 1)) |
| 62 | + dot_graph = to_pydot(graph) |
| 63 | + compare_with_reference_file(str(dot_graph), REF_DIR / "graph.dot", regen_ref_data) |
0 commit comments