"""The reference implementation must stay unmodified outside ONNX tracing.""" import importlib import unittest import transformers.models.gemma4.modeling_gemma4 as audio import transformers.models.embedding_gemma2.modeling_embedding_gemma2 as embedding def functions(): return ( audio.create_bidirectional_mask, audio.Gemma4AudioAttention._extract_block_context, embedding.create_bidirectional_mask, embedding.create_bidirectional_sliding_window_mask, ) class ExportIsolation(unittest.TestCase): def test_imports_do_not_patch_upstream(self): before = functions() for name in ("export_common", "export_tower", "export_embedding"): importlib.import_module(name) self.assertEqual(before, functions()) def test_patches_restore_on_success_and_failure(self): from export_common import export_patches before = functions() for include_text in (False, True): with export_patches(include_text=include_text): patched = functions() self.assertIsNot(patched[0], before[0]) self.assertIsNot(patched[1], before[1]) if not include_text: self.assertEqual(patched[2:], before[2:]) else: self.assertIsNot(patched[2], before[2]) self.assertIsNot(patched[3], before[3]) self.assertEqual(before, functions()) with self.assertRaisesRegex(RuntimeError, "trace failure"): with export_patches(include_text=include_text): raise RuntimeError("trace failure") self.assertEqual(before, functions()) if __name__ == "__main__": unittest.main()