|
1 | | -# Copyright 2023–2025 Google LLC |
| 1 | +# Copyright 2023–2026 Google LLC |
2 | 2 | # |
3 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
4 | 4 | # you may not use this file except in compliance with the License. |
|
12 | 12 | # See the License for the specific language governing permissions and |
13 | 13 | # limitations under the License. |
14 | 14 |
|
15 | | -# pylint: disable=missing-module-docstring, missing-function-docstring |
| 15 | +# pylint: disable=missing-module-docstring, missing-function-docstring, line-too-long, g-generic-assert |
16 | 16 | import itertools |
| 17 | +import json |
| 18 | + |
| 19 | +import pathlib |
17 | 20 | import sys |
18 | | -import unittest |
| 21 | +import tempfile |
19 | 22 |
|
20 | | -import pytest |
21 | 23 |
|
22 | | -import numpy as np |
| 24 | +from unittest import mock |
23 | 25 |
|
| 26 | +from absl.testing import absltest |
| 27 | +from absl.testing import parameterized |
24 | 28 | import jax |
25 | | -from jax.sharding import Mesh |
26 | 29 | from jax.experimental import mesh_utils |
27 | | - |
| 30 | +import jax.experimental.colocated_python |
| 31 | +from jax.sharding import Mesh |
28 | 32 | from maxtext.configs import pyconfig |
29 | 33 | from maxtext.input_pipeline import multihost_dataloading |
30 | | -from tests.utils.test_helpers import get_test_config_path, get_test_dataset_path, get_test_base_output_directory |
| 34 | +from tests.utils.test_helpers import get_test_base_output_directory |
| 35 | +from tests.utils.test_helpers import get_test_config_path |
| 36 | +from tests.utils.test_helpers import get_test_dataset_path |
| 37 | +import numpy as np |
| 38 | +import pytest |
| 39 | + |
| 40 | +# Mock jax.experimental.colocated_python before it is imported by |
| 41 | +# multihost_dataloading |
| 42 | +mock.patch.object( |
| 43 | + jax.experimental.colocated_python, |
| 44 | + "colocated_python_class", |
| 45 | + lambda cls: cls, |
| 46 | +).start() |
| 47 | +mock.patch.object( |
| 48 | + jax.experimental.colocated_python, |
| 49 | + "colocated_cpu_devices", |
| 50 | + lambda x: x, |
| 51 | +).start() |
| 52 | + |
| 53 | + |
| 54 | +class MockIterator: |
| 55 | + """Mock iterator for testing dataloading state saving/restoring.""" |
| 56 | + |
| 57 | + def __init__(self, mesh_size): |
| 58 | + self.state = 0 |
| 59 | + self.mesh_size = mesh_size |
| 60 | + |
| 61 | + def __next__(self): |
| 62 | + self.state += 1 |
| 63 | + return np.full((self.mesh_size, 1), self.state, dtype=np.int32) |
| 64 | + |
| 65 | + def get_state(self) -> dict[str, int]: |
| 66 | + return {"state": self.state} |
| 67 | + |
| 68 | + def set_state(self, state: dict[str, int]): |
| 69 | + self.state = state["state"] |
| 70 | + |
| 71 | + |
| 72 | +class MockDataloader: |
| 73 | + """Mock dataloader for testing.""" |
| 74 | + |
| 75 | + def __init__(self, mesh_size): |
| 76 | + self.mesh_size = mesh_size |
| 77 | + |
| 78 | + def __iter__(self) -> MockIterator: |
| 79 | + return MockIterator(self.mesh_size) |
31 | 80 |
|
32 | 81 |
|
33 | | -class MultihostDataloadingTest(unittest.TestCase): |
| 82 | +def _get_test_mesh_shapes_named(): |
| 83 | + return [ |
| 84 | + ("1_device", (1, 1)), |
| 85 | + ("2_devices", (2, 1)), |
| 86 | + ("4_devices", (2, 2)), |
| 87 | + ] |
| 88 | + |
| 89 | + |
| 90 | +class MultihostDataloadingTest(parameterized.TestCase): |
34 | 91 |
|
35 | 92 | def setUp(self): |
36 | 93 | super().setUp() |
37 | | - # Note: this test uses gs://max-experiments/ (not gs://runner-maxtext-logs) in cloud mode |
| 94 | + # Note: this test uses gs://max-experiments/ (not runner logs) in cloud mode |
38 | 95 | base_output_directory = get_test_base_output_directory(cloud_path="gs://max-experiments/") |
39 | 96 | dataset_path = get_test_dataset_path(cloud_path="gs://maxtext-dataset/") |
40 | 97 | batch_size = len(jax.devices()) |
@@ -62,8 +119,98 @@ def setUp(self): |
62 | 119 | def test_batch_sharded_data_pipeline(self): |
63 | 120 | first_batch = next(self.multihost_gen) |
64 | 121 | sec_batch = next(self.multihost_gen) |
65 | | - self.assertTrue(not np.array_equal(first_batch, sec_batch, equal_nan=True)) |
| 122 | + self.assertFalse(np.array_equal(first_batch, sec_batch, equal_nan=True)) |
| 123 | + |
| 124 | + @parameterized.named_parameters(*_get_test_mesh_shapes_named()) |
| 125 | + def test_remote_iterator_wrapper_save_state(self, mesh_shape): |
| 126 | + if jax.default_backend() == "gpu": |
| 127 | + self.skipTest("Skipping colocated python tests on GPU") |
| 128 | + mesh_size = mesh_shape[0] * mesh_shape[1] |
| 129 | + if mesh_size > len(jax.devices()): |
| 130 | + self.skipTest( |
| 131 | + f"Skipping test because available devices ({len(jax.devices())}) is" |
| 132 | + f" less than required mesh size ({mesh_size}) for shape {mesh_shape}." |
| 133 | + ) |
| 134 | + |
| 135 | + devs = jax.devices()[:mesh_size] |
| 136 | + devices = mesh_utils.create_device_mesh(mesh_shape, devs) |
| 137 | + mesh = Mesh(devices, ("x", "y")) |
| 138 | + |
| 139 | + def get_ds_fn(dataloading_host_index, dataloading_host_count): |
| 140 | + del dataloading_host_index, dataloading_host_count |
| 141 | + return MockDataloader(mesh_size) |
| 142 | + |
| 143 | + def preprocessing_fn(dataset): |
| 144 | + return dataset |
| 145 | + |
| 146 | + global_shape = (mesh_size, 1) |
| 147 | + |
| 148 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 149 | + wrapper = multihost_dataloading.RemoteIteratorWrapper( |
| 150 | + get_ds_fn=get_ds_fn, |
| 151 | + preprocessing_fn=preprocessing_fn, |
| 152 | + global_mesh=mesh, |
| 153 | + global_shape=global_shape, |
| 154 | + checkpoint_path=tmpdir, |
| 155 | + elastic=False, |
| 156 | + ) |
| 157 | + # Advance state once so the value is 1 |
| 158 | + next(wrapper) |
| 159 | + |
| 160 | + wrapper.save_state(step=5) |
| 161 | + |
| 162 | + # Verify that a file was written in the tempdir containing {"state": 1} |
| 163 | + json_files = list(pathlib.Path(tmpdir).glob("**/*.json")) |
| 164 | + self.assertEqual(len(json_files), 1, f"Expected 1 JSON file, found: {json_files}") |
| 165 | + written_content = json_files[0].read_text() |
| 166 | + self.assertEqual(json.loads(written_content), {"state": 1}) |
| 167 | + |
| 168 | + @parameterized.named_parameters(*_get_test_mesh_shapes_named()) |
| 169 | + def test_remote_iterator_wrapper_restore_state(self, mesh_shape): |
| 170 | + if jax.default_backend() == "gpu": |
| 171 | + self.skipTest("Skipping colocated python tests on GPU") |
| 172 | + mesh_size = mesh_shape[0] * mesh_shape[1] |
| 173 | + if mesh_size > len(jax.devices()): |
| 174 | + self.skipTest( |
| 175 | + f"Skipping test because available devices ({len(jax.devices())}) is" |
| 176 | + f" less than required mesh size ({mesh_size}) for shape {mesh_shape}." |
| 177 | + ) |
| 178 | + |
| 179 | + devs = jax.devices()[:mesh_size] |
| 180 | + devices = mesh_utils.create_device_mesh(mesh_shape, devs) |
| 181 | + mesh = Mesh(devices, ("x", "y")) |
| 182 | + |
| 183 | + def get_ds_fn(dataloading_host_index, dataloading_host_count): |
| 184 | + del dataloading_host_index, dataloading_host_count |
| 185 | + return MockDataloader(mesh_size) |
| 186 | + |
| 187 | + def preprocessing_fn(dataset): |
| 188 | + return dataset |
| 189 | + |
| 190 | + global_shape = (mesh_size, 1) |
| 191 | + |
| 192 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 193 | + step = 5 |
| 194 | + state_dir = pathlib.Path(tmpdir) / str(step) / "iter" |
| 195 | + state_dir.mkdir(parents=True, exist_ok=True) |
| 196 | + state_file = state_dir / "process_0-of-1.json" |
| 197 | + state_file.write_text('{"state": 10}') |
| 198 | + |
| 199 | + wrapper = multihost_dataloading.RemoteIteratorWrapper( |
| 200 | + get_ds_fn=get_ds_fn, |
| 201 | + preprocessing_fn=preprocessing_fn, |
| 202 | + global_mesh=mesh, |
| 203 | + global_shape=global_shape, |
| 204 | + checkpoint_path=tmpdir, |
| 205 | + elastic=False, |
| 206 | + ) |
| 207 | + |
| 208 | + wrapper.restore_state(step=5) |
| 209 | + val = next(wrapper) |
| 210 | + |
| 211 | + # Next value should be 11 (state 10 + 1) |
| 212 | + self.assertEqual(val.addressable_data(0)[0], 11) |
66 | 213 |
|
67 | 214 |
|
68 | 215 | if __name__ == "__main__": |
69 | | - unittest.main() |
| 216 | + absltest.main() |
0 commit comments