|
| 1 | +# Copyright 2023–2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Tests for load_custom_callable (used by dataset_processor_path knob).""" |
| 16 | + |
| 17 | +import os |
| 18 | +import sys |
| 19 | +import tempfile |
| 20 | +import textwrap |
| 21 | +import unittest |
| 22 | + |
| 23 | +import pytest |
| 24 | + |
| 25 | +from maxtext.trainers.post_train.rl.utils_rl import load_custom_callable |
| 26 | + |
| 27 | + |
| 28 | +pytestmark = [pytest.mark.post_training] |
| 29 | + |
| 30 | + |
| 31 | +_USER_PROCESS_DATA_SOURCE = textwrap.dedent( |
| 32 | + """ |
| 33 | + # Simulated user-provided dataset processor file. |
| 34 | + def process_data(dataset_name, model_tokenizer, template_config, tmvp_config, x): |
| 35 | + # Minimal stand-in for utils_rl.process_data: returns a dict shaped like |
| 36 | + # what the RL data pipeline expects, with a marker so the test can verify |
| 37 | + # that THIS function (not the built-in) was actually invoked. |
| 38 | + return { |
| 39 | + "prompts": f"USER_PROCESSOR<{x.get('question', '')}>", |
| 40 | + "question": x.get("question", ""), |
| 41 | + "answer": x.get("answer", ""), |
| 42 | + "_marker": "loaded_from_user_file", |
| 43 | + } |
| 44 | +
|
| 45 | +
|
| 46 | + def another_helper(x): |
| 47 | + return x * 2 |
| 48 | + """ |
| 49 | +).strip() |
| 50 | + |
| 51 | + |
| 52 | +def _write_user_file(tmpdir): |
| 53 | + """Write the user processor file inside tmpdir and return its absolute path.""" |
| 54 | + path = os.path.join(tmpdir, "user_processor.py") |
| 55 | + with open(path, "w", encoding="utf-8") as f: |
| 56 | + f.write(_USER_PROCESS_DATA_SOURCE) |
| 57 | + return path |
| 58 | + |
| 59 | + |
| 60 | +class LoadCustomCallableTest(unittest.TestCase): |
| 61 | + """Verify load_custom_callable loads a function from a user .py file.""" |
| 62 | + |
| 63 | + @pytest.mark.cpu_only |
| 64 | + def test_loads_function_from_user_file(self): |
| 65 | + """Returns a callable that behaves like the function in the user file.""" |
| 66 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 67 | + user_file = _write_user_file(tmpdir) |
| 68 | + fn = load_custom_callable(user_file, "process_data") |
| 69 | + |
| 70 | + self.assertTrue(callable(fn)) |
| 71 | + # pylint: disable-next=not-callable |
| 72 | + result = fn( |
| 73 | + "dataset_name", |
| 74 | + model_tokenizer=None, |
| 75 | + template_config=None, |
| 76 | + tmvp_config=None, |
| 77 | + x={"question": "2+2?", "answer": "4"}, |
| 78 | + ) |
| 79 | + self.assertEqual(result["_marker"], "loaded_from_user_file") |
| 80 | + self.assertEqual(result["prompts"], "USER_PROCESSOR<2+2?>") |
| 81 | + self.assertEqual(result["question"], "2+2?") |
| 82 | + self.assertEqual(result["answer"], "4") |
| 83 | + |
| 84 | + @pytest.mark.cpu_only |
| 85 | + def test_loads_any_named_function(self): |
| 86 | + """function_name argument selects which symbol to return.""" |
| 87 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 88 | + user_file = _write_user_file(tmpdir) |
| 89 | + fn = load_custom_callable(user_file, "another_helper") |
| 90 | + self.assertEqual(fn(5), 10) # pylint: disable=not-callable |
| 91 | + |
| 92 | + @pytest.mark.cpu_only |
| 93 | + def test_raises_when_file_does_not_exist(self): |
| 94 | + """Nonexistent path -> ValueError, not a cryptic ImportError.""" |
| 95 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 96 | + bogus = os.path.join(tmpdir, "does_not_exist.py") |
| 97 | + with self.assertRaises(ValueError): |
| 98 | + load_custom_callable(bogus, "process_data") |
| 99 | + |
| 100 | + @pytest.mark.cpu_only |
| 101 | + def test_raises_when_function_not_defined(self): |
| 102 | + """File exists but doesn't define the named function -> ValueError.""" |
| 103 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 104 | + user_file = _write_user_file(tmpdir) |
| 105 | + with self.assertRaises(ValueError): |
| 106 | + load_custom_callable(user_file, "no_such_function") |
| 107 | + |
| 108 | + @pytest.mark.cpu_only |
| 109 | + def test_does_not_pollute_sys_path(self): |
| 110 | + """Loading the file must not append its directory to sys.path.""" |
| 111 | + sys_path_before = list(sys.path) |
| 112 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 113 | + user_file = _write_user_file(tmpdir) |
| 114 | + load_custom_callable(user_file, "process_data") |
| 115 | + self.assertEqual(sys.path, sys_path_before) |
| 116 | + |
| 117 | + @pytest.mark.cpu_only |
| 118 | + def test_does_not_pollute_sys_modules_globally(self): |
| 119 | + """The loaded module gets a unique synthetic name; it should not shadow |
| 120 | + other modules with a generic name like 'user_processor'.""" |
| 121 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 122 | + user_file = _write_user_file(tmpdir) |
| 123 | + load_custom_callable(user_file, "process_data") |
| 124 | + # The helper uses '_user_module_<function_name>' as the synthetic module |
| 125 | + # name, not the file's basename - so 'user_processor' should NOT exist. |
| 126 | + self.assertNotIn("user_processor", sys.modules) |
| 127 | + |
| 128 | + |
| 129 | +if __name__ == "__main__": |
| 130 | + unittest.main() |
0 commit comments