|
| 1 | +# Copyright The PyTorch Lightning team. |
| 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 | +# http://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 | +import pytest |
| 15 | +from torch.utils.data import DataLoader |
| 16 | + |
| 17 | +from pytorch_lightning import Trainer |
| 18 | +from pytorch_lightning.tuner.tuning import Tuner |
| 19 | +from tests.helpers import BoringDataModule, BoringModel |
| 20 | + |
| 21 | + |
| 22 | +class BatchSizeDataModule(BoringDataModule): |
| 23 | + |
| 24 | + def __init__(self, batch_size=None): |
| 25 | + super().__init__() |
| 26 | + if batch_size is not None: |
| 27 | + self.batch_size = batch_size |
| 28 | + |
| 29 | + def train_dataloader(self): |
| 30 | + return DataLoader(self.random_train, batch_size=getattr(self, "batch_size", 1)) |
| 31 | + |
| 32 | + |
| 33 | +class BatchSizeModel(BoringModel): |
| 34 | + |
| 35 | + def __init__(self, batch_size=None): |
| 36 | + super().__init__() |
| 37 | + if batch_size is not None: |
| 38 | + self.batch_size = batch_size |
| 39 | + |
| 40 | + |
| 41 | +@pytest.mark.parametrize( |
| 42 | + "model,datamodule", [ |
| 43 | + (BatchSizeModel(2), None), |
| 44 | + (BatchSizeModel(2), BatchSizeDataModule(2)), |
| 45 | + (BatchSizeModel(2), BatchSizeDataModule(None)), |
| 46 | + (BatchSizeModel(None), BatchSizeDataModule(2)), |
| 47 | + ] |
| 48 | +) |
| 49 | +def test_scale_batch_size_method_with_model_or_datamodule(tmpdir, model, datamodule): |
| 50 | + """ Test the tuner method `Tuner.scale_batch_size` with a datamodule. """ |
| 51 | + trainer = Trainer( |
| 52 | + default_root_dir=tmpdir, |
| 53 | + limit_train_batches=1, |
| 54 | + limit_val_batches=0, |
| 55 | + max_epochs=1, |
| 56 | + ) |
| 57 | + tuner = Tuner(trainer) |
| 58 | + new_batch_size = tuner.scale_batch_size( |
| 59 | + model=model, mode="binsearch", init_val=4, max_trials=2, datamodule=datamodule |
| 60 | + ) |
| 61 | + assert new_batch_size == 16 |
| 62 | + if hasattr(model, "batch_size"): |
| 63 | + assert model.batch_size == 16 |
| 64 | + if datamodule is not None and hasattr(datamodule, "batch_size"): |
| 65 | + assert datamodule.batch_size == 16 |
0 commit comments