CoolFace
Apppublic

chendl/compositional_test

sourceHugging Faceupdated 3y agoView on Hugging Face
1likes
test_check_copies.py210 linesDownload Raw Back to repo_utils
1# Copyright 2020 The HuggingFace Team. All rights reserved.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 at6#7#     http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# 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 and13# limitations under the License.14 15import os16import re17import shutil18import sys19import tempfile20import unittest21 22import black23 24 25git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))26sys.path.append(os.path.join(git_repo_path, "utils"))27 28import check_copies  # noqa: E40229 30 31# This is the reference code that will be used in the tests.32# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.33REFERENCE_CODE = """    def __init__(self, config):34        super().__init__()35        self.transform = BertPredictionHeadTransform(config)36 37        # The output weights are the same as the input embeddings, but there is38        # an output-only bias for each token.39        self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)40 41        self.bias = nn.Parameter(torch.zeros(config.vocab_size))42 43        # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`44        self.decoder.bias = self.bias45 46    def forward(self, hidden_states):47        hidden_states = self.transform(hidden_states)48        hidden_states = self.decoder(hidden_states)49        return hidden_states50"""51 52 53class CopyCheckTester(unittest.TestCase):54    def setUp(self):55        self.transformer_dir = tempfile.mkdtemp()56        os.makedirs(os.path.join(self.transformer_dir, "models/bert/"))57        check_copies.TRANSFORMER_PATH = self.transformer_dir58        shutil.copy(59            os.path.join(git_repo_path, "src/transformers/models/bert/modeling_bert.py"),60            os.path.join(self.transformer_dir, "models/bert/modeling_bert.py"),61        )62 63    def tearDown(self):64        check_copies.TRANSFORMER_PATH = "src/transformers"65        shutil.rmtree(self.transformer_dir)66 67    def check_copy_consistency(self, comment, class_name, class_code, overwrite_result=None):68        code = comment + f"\nclass {class_name}(nn.Module):\n" + class_code69        if overwrite_result is not None:70            expected = comment + f"\nclass {class_name}(nn.Module):\n" + overwrite_result71        mode = black.Mode(target_versions={black.TargetVersion.PY35}, line_length=119)72        code = black.format_str(code, mode=mode)73        fname = os.path.join(self.transformer_dir, "new_code.py")74        with open(fname, "w", newline="\n") as f:75            f.write(code)76        if overwrite_result is None:77            self.assertTrue(len(check_copies.is_copy_consistent(fname)) == 0)78        else:79            check_copies.is_copy_consistent(f.name, overwrite=True)80            with open(fname, "r") as f:81                self.assertTrue(f.read(), expected)82 83    def test_find_code_in_transformers(self):84        code = check_copies.find_code_in_transformers("models.bert.modeling_bert.BertLMPredictionHead")85        self.assertEqual(code, REFERENCE_CODE)86 87    def test_is_copy_consistent(self):88        # Base copy consistency89        self.check_copy_consistency(90            "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead",91            "BertLMPredictionHead",92            REFERENCE_CODE + "\n",93        )94 95        # With no empty line at the end96        self.check_copy_consistency(97            "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead",98            "BertLMPredictionHead",99            REFERENCE_CODE,100        )101 102        # Copy consistency with rename103        self.check_copy_consistency(104            "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel",105            "TestModelLMPredictionHead",106            re.sub("Bert", "TestModel", REFERENCE_CODE),107        )108 109        # Copy consistency with a really long name110        long_class_name = "TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason"111        self.check_copy_consistency(112            f"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}",113            f"{long_class_name}LMPredictionHead",114            re.sub("Bert", long_class_name, REFERENCE_CODE),115        )116 117        # Copy consistency with overwrite118        self.check_copy_consistency(119            "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel",120            "TestModelLMPredictionHead",121            REFERENCE_CODE,122            overwrite_result=re.sub("Bert", "TestModel", REFERENCE_CODE),123        )124 125    def test_convert_to_localized_md(self):126        localized_readme = check_copies.LOCALIZED_READMES["README_zh-hans.md"]127 128        md_list = (129            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"130            " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"131            " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"132            " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1."133            " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),"134            " released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"135            " lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same"136            " method has been applied to compress GPT2 into"137            " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"138            " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"139            " Multilingual BERT into"140            " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"141            " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**"142            " (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders"143            " as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang"144            " Luong, Quoc V. Le, Christopher D. Manning."145        )146        localized_md_list = (147            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"148            " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"149            " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"150            " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"151        )152        converted_md_list_sample = (153            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"154            " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"155            " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"156            " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1."157            " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文"158            " [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"159            " lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same"160            " method has been applied to compress GPT2 into"161            " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"162            " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"163            " Multilingual BERT into"164            " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"165            " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自"166            " Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather"167            " than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,"168            " Christopher D. Manning 发布。\n"169        )170 171        num_models_equal, converted_md_list = check_copies.convert_to_localized_md(172            md_list, localized_md_list, localized_readme["format_model_list"]173        )174 175        self.assertFalse(num_models_equal)176        self.assertEqual(converted_md_list, converted_md_list_sample)177 178        num_models_equal, converted_md_list = check_copies.convert_to_localized_md(179            md_list, converted_md_list, localized_readme["format_model_list"]180        )181 182        # Check whether the number of models is equal to README.md after conversion.183        self.assertTrue(num_models_equal)184 185        link_changed_md_list = (186            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"187            " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"188            " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"189            " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut."190        )191        link_unchanged_md_list = (192            "1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and"193            " the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"194            " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"195            " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"196        )197        converted_md_list_sample = (198            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"199            " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"200            " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"201            " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"202        )203 204        num_models_equal, converted_md_list = check_copies.convert_to_localized_md(205            link_changed_md_list, link_unchanged_md_list, localized_readme["format_model_list"]206        )207 208        # Check if the model link is synchronized.209        self.assertEqual(converted_md_list, converted_md_list_sample)210