|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +import os |
| 8 | +import runpy |
| 9 | +import sys |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +import pytest |
| 13 | +import torch |
| 14 | +from omegaconf import OmegaConf |
| 15 | +from tests.common import TUNE_PATH |
| 16 | +from tests.recipes.utils import ( |
| 17 | + dummy_stack_exchange_dataset_config, |
| 18 | + MODEL_TEST_CONFIGS, |
| 19 | + write_hf_ckpt_config, |
| 20 | +) |
| 21 | +from tests.test_utils import ( |
| 22 | + CKPT_MODEL_PATHS, |
| 23 | + gen_log_file_name, |
| 24 | + get_loss_values_from_metric_logger, |
| 25 | +) |
| 26 | +from torchtune import config |
| 27 | + |
| 28 | + |
| 29 | +class TestLoRADPOSingleDeviceRecipe: |
| 30 | + def _get_test_config_overrides(self, dtype_str: str = "fp32", epochs: int = 2): |
| 31 | + return [ |
| 32 | + "batch_size=8", |
| 33 | + "device=cpu", |
| 34 | + f"dtype={dtype_str}", |
| 35 | + "enable_activation_checkpointing=False", |
| 36 | + "dataset.train_on_input=False", |
| 37 | + "seed=9", |
| 38 | + f"epochs={epochs}", |
| 39 | + "max_steps_per_epoch=2", |
| 40 | + "optimizer.lr=2e-5", |
| 41 | + "log_every_n_steps=1", |
| 42 | + "gradient_accumulation_steps=1", |
| 43 | + "clip_grad_norm=100", |
| 44 | + "tokenizer.max_seq_len=512", |
| 45 | + ] + dummy_stack_exchange_dataset_config() |
| 46 | + |
| 47 | + @pytest.mark.parametrize("save_adapter_weights_only", [False, True]) |
| 48 | + @pytest.mark.integration_test |
| 49 | + def test_training_state_on_resume( |
| 50 | + self, tmpdir, monkeypatch, save_adapter_weights_only |
| 51 | + ): |
| 52 | + """Test whether the recipe state is correctly updated on resume. Since this |
| 53 | + is model agnostic, we should run this on the small model only. The test |
| 54 | + consists of three stages: |
| 55 | + - Train a model for 2 epochs |
| 56 | + - Resume training after epoch 1 |
| 57 | + - Make sure final loss matches the expected value of a model successfully resumed from a ckpt |
| 58 | + Unlike `tests.recipes.test_lora_finetune_single_device`, this test does not use pre-computed loss |
| 59 | + values to benchmark against. This test just ensures the loss values are identical when resuming. |
| 60 | + """ |
| 61 | + |
| 62 | + ckpt = "llama2_hf" |
| 63 | + ckpt_path = Path(CKPT_MODEL_PATHS[ckpt]) |
| 64 | + ckpt_dir = ckpt_path.parent |
| 65 | + log_file = gen_log_file_name(tmpdir) |
| 66 | + |
| 67 | + # Config file needed for model conversion. |
| 68 | + # Create a second copy for training resume |
| 69 | + write_hf_ckpt_config(ckpt_dir) |
| 70 | + write_hf_ckpt_config(tmpdir) |
| 71 | + |
| 72 | + # Train for two epochs |
| 73 | + cmd_1 = f""" |
| 74 | + tune run lora_dpo_single_device \ |
| 75 | + --config llama2/7B_lora_dpo_single_device \ |
| 76 | + output_dir={tmpdir} \ |
| 77 | + checkpointer=torchtune.training.FullModelHFCheckpointer \ |
| 78 | + checkpointer.checkpoint_dir='{ckpt_dir}' \ |
| 79 | + checkpointer.checkpoint_files=[{ckpt_path}]\ |
| 80 | + checkpointer.output_dir={tmpdir} \ |
| 81 | + checkpointer.model_type=LLAMA2 \ |
| 82 | + tokenizer.path=/tmp/test-artifacts/tokenizer.model \ |
| 83 | + tokenizer.prompt_template=null \ |
| 84 | + save_adapter_weights_only={save_adapter_weights_only} \ |
| 85 | + metric_logger.filename={log_file} \ |
| 86 | + """.split() |
| 87 | + |
| 88 | + model_config = MODEL_TEST_CONFIGS["llama2_lora"] |
| 89 | + |
| 90 | + cmd_1 = cmd_1 + self._get_test_config_overrides() + model_config |
| 91 | + monkeypatch.setattr(sys, "argv", cmd_1) |
| 92 | + with pytest.raises(SystemExit, match=""): |
| 93 | + runpy.run_path(TUNE_PATH, run_name="__main__") |
| 94 | + |
| 95 | + expected_loss_values = get_loss_values_from_metric_logger(log_file) |
| 96 | + |
| 97 | + resumed_log_dir = (tmpdir / "resumed/").mkdir() |
| 98 | + resumed_log_file = gen_log_file_name(resumed_log_dir) |
| 99 | + # Resume training |
| 100 | + cmd_2 = f""" |
| 101 | + tune run lora_dpo_single_device \ |
| 102 | + --config llama2/7B_lora_dpo_single_device \ |
| 103 | + output_dir={tmpdir} \ |
| 104 | + checkpointer=torchtune.training.FullModelHFCheckpointer \ |
| 105 | + checkpointer.checkpoint_dir={tmpdir} \ |
| 106 | + checkpointer.checkpoint_files=[{ckpt_path}]\ |
| 107 | + checkpointer.adapter_checkpoint={os.path.join(tmpdir, "adapter_0.pt")} |
| 108 | + checkpointer.recipe_checkpoint={os.path.join(tmpdir, "recipe_state.pt")} |
| 109 | + checkpointer.output_dir={tmpdir} \ |
| 110 | + checkpointer.model_type=LLAMA2 \ |
| 111 | + resume_from_checkpoint=True \ |
| 112 | + metric_logger.filename={resumed_log_file} \ |
| 113 | + tokenizer.path=/tmp/test-artifacts/tokenizer.model \ |
| 114 | + tokenizer.prompt_template=null \ |
| 115 | + """.split() |
| 116 | + cmd_2 = cmd_2 + self._get_test_config_overrides(epochs=3) + model_config |
| 117 | + monkeypatch.setattr(sys, "argv", cmd_2) |
| 118 | + with pytest.raises(SystemExit, match=""): |
| 119 | + runpy.run_path(TUNE_PATH, run_name="__main__") |
| 120 | + |
| 121 | + # Second epoch only |
| 122 | + resumed_loss_values = get_loss_values_from_metric_logger(resumed_log_file) |
| 123 | + |
| 124 | + torch.testing.assert_close( |
| 125 | + resumed_loss_values[:2], expected_loss_values[2:], rtol=1e-5, atol=1e-5 |
| 126 | + ) |
| 127 | + |
| 128 | + @pytest.mark.integration_test |
| 129 | + def test_save_and_load_merged_weights(self, tmpdir, monkeypatch): |
| 130 | + ckpt = "llama2_tune" |
| 131 | + ckpt_path = Path(CKPT_MODEL_PATHS[ckpt]) |
| 132 | + ckpt_dir = ckpt_path.parent |
| 133 | + |
| 134 | + cmd = f""" |
| 135 | + tune run lora_dpo_single_device \ |
| 136 | + --config llama2/7B_lora_dpo_single_device \ |
| 137 | + output_dir={tmpdir} \ |
| 138 | + checkpointer=torchtune.training.FullModelTorchTuneCheckpointer \ |
| 139 | + checkpointer.checkpoint_dir='{ckpt_dir}' \ |
| 140 | + checkpointer.checkpoint_files=[{ckpt_path}]\ |
| 141 | + checkpointer.output_dir={tmpdir} \ |
| 142 | + checkpointer.model_type=LLAMA2 \ |
| 143 | + tokenizer.path=/tmp/test-artifacts/tokenizer.model \ |
| 144 | + tokenizer.prompt_template=null \ |
| 145 | + """.split() |
| 146 | + |
| 147 | + model_config = MODEL_TEST_CONFIGS["llama2_lora"] |
| 148 | + |
| 149 | + cmd = cmd + self._get_test_config_overrides() + model_config |
| 150 | + monkeypatch.setattr(sys, "argv", cmd) |
| 151 | + with pytest.raises(SystemExit, match=""): |
| 152 | + runpy.run_path(TUNE_PATH, run_name="__main__") |
| 153 | + |
| 154 | + # Next load both the merged weights in a Llama2 base model |
| 155 | + # and the base model weights + trained adapter weights in the LoRA Llama 2 model |
| 156 | + # The results of calling forward on dummy inputs should be the same. |
| 157 | + inputs = torch.randint(low=0, high=32_000, size=(2, 100)) |
| 158 | + |
| 159 | + # Build LoRA model for loading base + adapter weights separately |
| 160 | + lora_model = config.instantiate(OmegaConf.from_dotlist(model_config).model) |
| 161 | + |
| 162 | + # Build base llama2 model for loading merged weights |
| 163 | + base_llama2_config = MODEL_TEST_CONFIGS["llama2"] |
| 164 | + llama2_model = config.instantiate( |
| 165 | + OmegaConf.from_dotlist(base_llama2_config).model |
| 166 | + ) |
| 167 | + |
| 168 | + # Load base model and trained adapter weights into LoRA model and call fwd |
| 169 | + with open(f"{tmpdir}/adapter_1.pt", "rb") as f: |
| 170 | + lora_sd = torch.load(f, weights_only=True) |
| 171 | + with open(ckpt_path, "rb") as f: |
| 172 | + base_model_sd = torch.load(f, weights_only=True) |
| 173 | + lora_model.load_state_dict(lora_sd, strict=False) |
| 174 | + lora_model.load_state_dict(base_model_sd, strict=False) |
| 175 | + baseline_out = lora_model(inputs) |
| 176 | + |
| 177 | + # Load merged final ckpt directly into llama2 and call fwd |
| 178 | + with open(f"{tmpdir}/torchtune_model_1.pt", "rb") as f: |
| 179 | + sd = torch.load(f, weights_only=True) |
| 180 | + llama2_model.load_state_dict(sd) |
| 181 | + merged_ckpt_out = llama2_model(inputs) |
| 182 | + torch.testing.assert_close(baseline_out, merged_ckpt_out, rtol=1e-5, atol=1e-5) |
0 commit comments