




import json
import os
import unittest

from transformers import DebertaTokenizer, DebertaTokenizerFast
from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES
from transformers.testing_utils import slow

from ...test_tokenization_common import TokenizerTesterMixin





class     lowerCamelCase__(					__lowerCamelCase ,     unittest.TestCase):
      UpperCAmelCase__      :	Optional[int]    		=   DebertaTokenizer
      UpperCAmelCase__      :	Tuple    		=   True
      UpperCAmelCase__      :	str    		=   DebertaTokenizerFast
      def 			lowerCAmelCase__						(				self: str   ):
             super().setUp()

             # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
             __lowerCamelCase   =						[
                 """l""",
                 """o""",
                 """w""",
                 """e""",
                 """r""",
                 """s""",
                 """t""",
                 """i""",
                 """d""",
                 """n""",
                 """\u0120""",
                 """\u0120l""",
                 """\u0120n""",
                 """\u0120lo""",
                 """\u0120low""",
                 """er""",
                 """\u0120lowest""",
                 """\u0120newer""",
                 """\u0120wider""",
                 """[UNK]""",
             ]
             __lowerCamelCase   =						dict(zip(UpperCamelCase_    ,       range(len(UpperCamelCase_   )   )   )   )
             __lowerCamelCase   =						["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
             __lowerCamelCase   =						{"""unk_token""": """[UNK]"""}

             __lowerCamelCase   =						os.path.join(self.tmpdirname    ,       VOCAB_FILES_NAMES["""vocab_file"""]   )
             __lowerCamelCase   =						os.path.join(self.tmpdirname    ,       VOCAB_FILES_NAMES["""merges_file"""]   )
             with open(self.vocab_file    ,       """w"""    ,       encoding="""utf-8"""   ) as fp:
                    fp.write(json.dumps(UpperCamelCase_   ) + """\n"""   )
             with open(self.merges_file    ,       """w"""    ,       encoding="""utf-8"""   ) as fp:
                    fp.write("""\n""".join(UpperCamelCase_   )   )
      def 			lowerCAmelCase__						(				self: List[Any]    ,       **UpperCamelCase_: List[Any]   ):
             kwargs.update(self.special_tokens_map   )
             return self.tokenizer_class.from_pretrained(self.tmpdirname    ,       **UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: Dict    ,       UpperCamelCase_: Dict   ):
             __lowerCamelCase   =						"""lower newer"""
             __lowerCamelCase   =						"""lower newer"""
             return input_text, output_text
      def 			lowerCAmelCase__						(				self: Optional[int]   ):
             __lowerCamelCase   =						self.get_tokenizer()
             __lowerCamelCase   =						"""lower newer"""
             __lowerCamelCase   =						["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""]
             __lowerCamelCase   =						tokenizer.tokenize(UpperCamelCase_   )
             self.assertListEqual(UpperCamelCase_    ,       UpperCamelCase_   )

             __lowerCamelCase   =						tokens + [tokenizer.unk_token]
             __lowerCamelCase   =						[0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
             self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase_   )    ,       UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: Union[str, Any]   ):
             __lowerCamelCase   =						self.get_tokenizer()
             __lowerCamelCase   =						tokenizer("""Hello"""    ,       """World"""   )
             __lowerCamelCase   =						[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
             self.assertListEqual(tokd["""token_type_ids"""]    ,       UpperCamelCase_   )
      @slow
      def 			lowerCAmelCase__						(				self: Dict   ):
             __lowerCamelCase   =						self.tokenizer_class.from_pretrained("""microsoft/deberta-base"""   )

             __lowerCamelCase   =						tokenizer.encode("""sequence builders"""    ,       add_special_tokens=UpperCamelCase_   )
             __lowerCamelCase   =						tokenizer.encode("""multi-sequence build"""    ,       add_special_tokens=UpperCamelCase_   )

             __lowerCamelCase   =						tokenizer.encode(
                 """sequence builders"""    ,       add_special_tokens=UpperCamelCase_    ,       add_prefix_space=UpperCamelCase_   )
             __lowerCamelCase   =						tokenizer.encode(
                 """sequence builders"""    ,       """multi-sequence build"""    ,       add_special_tokens=UpperCamelCase_    ,       add_prefix_space=UpperCamelCase_   )

             __lowerCamelCase   =						tokenizer.build_inputs_with_special_tokens(UpperCamelCase_   )
             __lowerCamelCase   =						tokenizer.build_inputs_with_special_tokens(UpperCamelCase_    ,       UpperCamelCase_   )

             assert encoded_sentence == encoded_text_from_decode
             assert encoded_pair == encoded_pair_from_decode




      @slow
      def 			lowerCAmelCase__						(				self: str   ):
             __lowerCamelCase   =						[self.tokenizer_class]
             if self.test_rust_tokenizer:
                    tokenizer_classes.append(self.rust_tokenizer_class   )

             for tokenizer_class in tokenizer_classes:
                    __lowerCamelCase   =						tokenizer_class.from_pretrained("""microsoft/deberta-base"""   )

                    __lowerCamelCase   =						[
                        """ALBERT: A Lite BERT for Self-supervised Learning of Language Representations""",
                        """ALBERT incorporates two parameter reduction techniques""",
                        """The first one is a factorized embedding parameterization. By decomposing the large vocabulary"""
                        """ embedding matrix into two small matrices, we separate the size of the hidden layers from the size of"""
                        """ vocabulary embedding.""",
                    ]

                    __lowerCamelCase   =						tokenizer(UpperCamelCase_    ,       padding=UpperCamelCase_   )
                    __lowerCamelCase   =						[tokenizer.decode(UpperCamelCase_    ,       skip_special_tokens=UpperCamelCase_   ) for seq in encoding["""input_ids"""]]

                    # fmt: off
                    __lowerCamelCase   =						{
                        """input_ids""": [
                            [1, 21_18, 1_11_26, 5_65, 35, 83, 2_51_91, 1_63, 1_88_54, 13, 1_21_56, 12, 1_61_01, 2_53_76, 1_38_07, 9, 2_22_05, 2_78_93, 16_35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                            [1, 21_18, 1_11_26, 5_65, 2_45_36, 80, 4_37_97, 48_78, 73_73, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                            [1, 1_33, 78, 65, 16, 10, 37_24, 15_38, 3_31_83, 1_13_03, 4_37_97, 19_38, 4, 8_70, 2_41_65, 2_91_05, 5, 7_39, 3_26_44, 3_31_83, 1_13_03, 3_61_73, 88, 80, 6_50, 78_21, 4_59_40, 6, 52, 25_59, 5, 18_36, 9, 5, 73_97, 1_31_71, 31, 5, 18_36, 9, 3_26_44, 3_31_83, 1_13_03, 4, 2]
                        ],
                        """token_type_ids""": [
                            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        ],
                        """attention_mask""": [
                            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
                        ]
                    }
                    # fmt: on

                    __lowerCamelCase   =						[
                        """ALBERT: A Lite BERT for Self-supervised Learning of Language Representations""",
                        """ALBERT incorporates two parameter reduction techniques""",
                        """The first one is a factorized embedding parameterization. By decomposing the large vocabulary"""
                        """ embedding matrix into two small matrices, we separate the size of the hidden layers from the size of"""
                        """ vocabulary embedding.""",
                    ]

                    self.assertDictEqual(encoding.data    ,       UpperCamelCase_   )

                    for expected, decoded in zip(UpperCamelCase_    ,       UpperCamelCase_   ):
                           self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )







import json
import os
from datetime import date
from pathlib import Path

from tabulate import DataRow, TableFormat, tabulate


UpperCAmelCase_									=	TableFormat(
    lineabove=None,
    linebelowheader=None,
    linebetweenrows=None,
    linebelow=None,
    headerrow=DataRow('', '|', '|'),
    datarow=DataRow('', '|', '|'),
    padding=1,
    with_header_hide=None,
)


UpperCAmelCase_									=	[]
UpperCAmelCase_									=	[]

UpperCAmelCase_									=	{'type': 'section', 'text': {'type': 'plain_text', 'text': 'No failed tests! 🤗', 'emoji': True}}

UpperCAmelCase_									=	[
    {
        'type': 'header',
        'text': {
            'type': 'plain_text',
            'text': f"""🤗 Accelerate nightly {os.environ.get("TEST_TYPE", "")} test results""",
            'emoji': True,
        },
    }
]

UpperCAmelCase_									=	0
for log in Path().glob('*.log'):
       UpperCAmelCase_									=	0
       with open(log, 'r') as f:
              for line in f:
                     UpperCAmelCase_									=	json.loads(line)
                     if line.get('nodeid', '') != "":
                            UpperCAmelCase_									=	line['nodeid']
                            if line.get('duration', None) is not None:
                                   UpperCAmelCase_									=	f"""{line["duration"]:.4f}"""
                                   if line.get('outcome', '') == "failed":
                                          section_num_failed += 1
                                          failed.append([test, duration, log.name.split('_')[0]])
                                          total_num_failed += 1
       group_info.append([str(log), section_num_failed, failed])
       UpperCAmelCase_									=	[]
       log.unlink()

UpperCAmelCase_									=	''
UpperCAmelCase_									=	[]
if total_num_failed > 0:
       for name, num_failed, failed_tests in group_info:
              if num_failed > 0:
                     if num_failed == 1:
                            message += f"*{name[1:]}: {num_failed} failed test*\n"
                     else:
                            message += f"*{name[1:]}: {num_failed} failed tests*\n"
                     UpperCAmelCase_									=	[]
                     UpperCAmelCase_									=	{}
                     for test in failed_tests:
                            UpperCAmelCase_									=	test[0].split('::')
                            UpperCAmelCase_									=	data[0].split('/')[-1]
                            if data[0] not in filesafailed:
                                   UpperCAmelCase_									=	[data[1:]]
                            else:
                                   filesafailed[data[0]] += [data[1:]]
                            failed_table.append(data)

                     UpperCAmelCase_									=	[test[0] for test in failed_table]
                     UpperCAmelCase_									=	list(set(files))
                     # Count number of instances in failed_tests
                     UpperCAmelCase_									=	[]
                     for file in individual_files:
                            table.append([file, len(filesafailed[file])])

                     UpperCAmelCase_									=	tabulate(
                         table,
                         headers=['Test Location', 'Num Failed'],
                         tablefmt=hf_table_format,
                         stralign='right',
                     )
                     message += f"\n```\n{failed_table}\n```"
                     all_filesafailed.append(filesafailed)
       if len(message) > 3_000:
              UpperCAmelCase_									=	'Too many failed tests, please see the full report in the Action results.'
              UpperCAmelCase_									=	len(err) + 10
              UpperCAmelCase_									=	message[: 3_000 - offset] + f"""\n...\n```\n{err}"""
       print(f"""### {message}""")
else:
       UpperCAmelCase_									=	'No failed tests! 🤗'
       print(f"""## {message}""")
       payload.append(no_error_payload)

if os.environ.get('TEST_TYPE', '') != "":
       from slack_sdk import WebClient

       UpperCAmelCase_									=	WebClient(token=os.environ['SLACK_API_TOKEN'])
       if message != "No failed tests! 🤗":
              UpperCAmelCase_									=	{
                  'type': 'section',
                  'text': {
                      'type': 'mrkdwn',
                      'text': message,
                  },
              }
              payload.append(md_report)
              UpperCAmelCase_									=	{
                  'type': 'section',
                  'text': {
                      'type': 'mrkdwn',
                      'text': '*For more details:*',
                  },
                  'accessory': {
                      'type': 'button',
                      'text': {
                          'type': 'plain_text',
                          'text': 'Check Action results',
                          'emoji': True,
                      },
                      'url': f"""https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}""",
                  },
              }
              payload.append(action_button)
              UpperCAmelCase_									=	{
                  'type': 'context',
                  'elements': [
                      {
                          'type': 'plain_text',
                          'text': f"""Nightly {os.environ.get("TEST_TYPE")} test results for {date.today()}""",
                      }
                  ],
              }
              payload.append(date_report)
       UpperCAmelCase_									=	client.chat_postMessage(channel='#accelerate-ci-daily', text=message, blocks=payload)
       UpperCAmelCase_									=	response.data['ts']
       for failed_file in all_filesafailed:
              for test_location, test_failures in failed_file.items():
                     # Keep only the first instance of the test name
                     UpperCAmelCase_									=	''
                     for i, row in enumerate(test_failures):
                            if row[0] != test_class:
                                   UpperCAmelCase_									=	row[0]
                            else:
                                   UpperCAmelCase_									=	''

                     UpperCAmelCase_									=	{
                         'type': 'section',
                         'text': {
                             'type': 'mrkdwn',
                             'text': f"""Test location: {test_location}\n```\n{tabulate(test_failures, headers=["Class", "Test"], tablefmt=hf_table_format, stralign="right")}\n```""",
                         },
                     }

                     client.chat_postMessage(
                         channel='#accelerate-ci-daily',
                         thread_ts=ts,
                         blocks=[payload],
                     )

