|
| 1 | +import argparse |
| 2 | +import os |
| 3 | +import sys |
| 4 | +import tempfile |
| 5 | +from pathlib import Path |
| 6 | +from unittest.mock import patch |
| 7 | + |
| 8 | +import pytest |
| 9 | +import pytorch_lightning as pl |
| 10 | +import timeout_decorator |
| 11 | +import torch |
| 12 | + |
| 13 | +from transformers import BartForConditionalGeneration |
| 14 | +from transformers.testing_utils import slow |
| 15 | + |
| 16 | +from .finetune import SummarizationModule, main |
| 17 | +from .test_seq2seq_examples import CUDA_AVAILABLE, MBART_TINY |
| 18 | +from .utils import load_json |
| 19 | + |
| 20 | + |
| 21 | +MODEL_NAME = MBART_TINY |
| 22 | +# TODO(SS): MODEL_NAME = "sshleifer/student_mbart_en_ro_1_1" |
| 23 | + |
| 24 | + |
| 25 | +@slow |
| 26 | +@pytest.mark.skipif(not CUDA_AVAILABLE, reason="too slow to run on CPU") |
| 27 | +def test_model_download(): |
| 28 | + """This warms up the cache so that we can time the next test without including download time, which varies between machines.""" |
| 29 | + BartForConditionalGeneration.from_pretrained(MODEL_NAME) |
| 30 | + |
| 31 | + |
| 32 | +@timeout_decorator.timeout(120) |
| 33 | +@slow |
| 34 | +@pytest.mark.skipif(not CUDA_AVAILABLE, reason="too slow to run on CPU") |
| 35 | +def test_train_mbart_cc25_enro_script(): |
| 36 | + data_dir = "examples/seq2seq/test_data/wmt_en_ro" |
| 37 | + env_vars_to_replace = { |
| 38 | + "$MAX_LEN": 200, |
| 39 | + "$BS": 4, |
| 40 | + "$GAS": 1, |
| 41 | + "$ENRO_DIR": data_dir, |
| 42 | + "facebook/mbart-large-cc25": MODEL_NAME, |
| 43 | + # 1 encoder and 1 decoder layer from finetuned mbart en-ro. Should be able to start >0 and improve quickly. |
| 44 | + # Download is 600MB in previous test. |
| 45 | + "val_check_interval=0.25": "val_check_interval=1.0", |
| 46 | + } |
| 47 | + |
| 48 | + # Clean up bash script |
| 49 | + bash_script = Path("examples/seq2seq/train_mbart_cc25_enro.sh").open().read().split("finetune.py")[1].strip() |
| 50 | + bash_script = bash_script.replace("\\\n", "").strip().replace("$@", "") |
| 51 | + for k, v in env_vars_to_replace.items(): |
| 52 | + bash_script = bash_script.replace(k, str(v)) |
| 53 | + output_dir = tempfile.mkdtemp(prefix="output") |
| 54 | + |
| 55 | + if CUDA_AVAILABLE: |
| 56 | + gpus = 1 # torch.cuda.device_count() |
| 57 | + else: |
| 58 | + bash_script = bash_script.replace("--fp16", "") |
| 59 | + gpus = 0 |
| 60 | + |
| 61 | + testargs = ( |
| 62 | + ["finetune.py"] |
| 63 | + + bash_script.split() |
| 64 | + + [ |
| 65 | + f"--output_dir={output_dir}", |
| 66 | + f"--gpus={gpus}", |
| 67 | + "--learning_rate=3e-1", |
| 68 | + "--warmup_steps=0", |
| 69 | + "--val_check_interval=1.0", |
| 70 | + "--tokenizer_name=facebook/mbart-large-en-ro", |
| 71 | + ] |
| 72 | + ) |
| 73 | + with patch.object(sys, "argv", testargs): |
| 74 | + parser = argparse.ArgumentParser() |
| 75 | + parser = pl.Trainer.add_argparse_args(parser) |
| 76 | + parser = SummarizationModule.add_model_specific_args(parser, os.getcwd()) |
| 77 | + args = parser.parse_args() |
| 78 | + args.do_predict = False |
| 79 | + # assert args.gpus == gpus THIS BREAKS for multigpu |
| 80 | + model = main(args) |
| 81 | + |
| 82 | + # Check metrics |
| 83 | + metrics = load_json(model.metrics_save_path) |
| 84 | + first_step_stats = metrics["val"][0] |
| 85 | + last_step_stats = metrics["val"][-1] |
| 86 | + assert len(metrics["val"]) == (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check |
| 87 | + |
| 88 | + assert last_step_stats["val_avg_gen_time"] >= 0.01 |
| 89 | + |
| 90 | + assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing |
| 91 | + assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. |
| 92 | + assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"], float) |
| 93 | + |
| 94 | + # check lightning ckpt can be loaded and has a reasonable statedict |
| 95 | + contents = os.listdir(output_dir) |
| 96 | + ckpt_path = [x for x in contents if x.endswith(".ckpt")][0] |
| 97 | + full_path = os.path.join(args.output_dir, ckpt_path) |
| 98 | + ckpt = torch.load(full_path, map_location="cpu") |
| 99 | + expected_key = "model.model.decoder.layers.0.encoder_attn_layer_norm.weight" |
| 100 | + assert expected_key in ckpt["state_dict"] |
| 101 | + assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.float32 |
| 102 | + |
| 103 | + # TODO(SS): turn on args.do_predict when PL bug fixed. |
| 104 | + if args.do_predict: |
| 105 | + contents = {os.path.basename(p) for p in contents} |
| 106 | + assert "test_generations.txt" in contents |
| 107 | + assert "test_results.txt" in contents |
| 108 | + # assert len(metrics["val"]) == desired_n_evals |
| 109 | + assert len(metrics["test"]) == 1 |
0 commit comments