

"""simple docstring"""





import json
import os
import unittest
from typing import Tuple

from transformers import WavaVecaPhonemeCTCTokenizer
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.models.wavaveca_phoneme.tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizerOutput
from transformers.testing_utils import require_phonemizer

from ...test_tokenization_common import TokenizerTesterMixin







@require_phonemizer
class 							SCREAMING_SNAKE_CASE   (						a_       ,				unittest.TestCase			):






					"""simple docstring"""



					lowercase__												=			WavaVecaPhonemeCTCTokenizer
					lowercase__												=			False







					def 			__lowerCAmelCase					(			self     :							List[str]						):
						super().setUp()

						lowerCAmelCase__      :		Tuple    							=      (
						    '''<s> <pad> </s> <unk> n s t ə l a i k d m ɛ ɾ e ɪ p o ɐ z ð f j v b ɹ ʁ ʊ iː r w ʌ u ɡ æ aɪ ʃ h ɔ ɑː '''
						    '''ŋ ɚ eɪ β uː y ɑ̃ oʊ ᵻ eː θ aʊ ts oː ɔ̃ ɣ ɜ ɑ dʒ əl x ɜː ç ʒ tʃ ɔː ɑːɹ ɛ̃ ʎ ɔːɹ ʋ aː ɕ œ ø oːɹ ɲ yː '''
						    '''ʔ iə i5 s. tɕ ?? nʲ ɛː œ̃ ɭ ɔø ʑ tʲ ɨ ɛɹ ts. rʲ ɪɹ ɭʲ i.5 ɔɪ q sʲ u5 ʊɹ iɜ a5 iɛ5 øː ʕ ja əɜ th ɑ5 '''
						    '''oɪ dʲ ə5 tɕh ts.h mʲ ɯ dʑ vʲ e̞ tʃʲ ei5 o5 onɡ5 ɑu5 iɑ5 ai5 aɪɚ kh ə1 ʐ i2 ʉ ħ t[ aɪə ʲ ju ə2 u2 oɜ '''
						    '''pː iɛɜ ou5 y5 uɜ tː uo5 d[ uoɜ tsh ɑɜ ɵ i̪5 uei5 ɟ aɜ ɑɨ i.ɜ eʊ o2 ɐ̃ ä pʲ kʲ n̩ ɒ ph ɑu2 uɨ əɪ ɫ ɬ '''
						    '''yɜ bʲ ɑ2 s̪ aiɜ χ ɐ̃ʊ̃ 1 ə4 yæɜ a2 ɨː t̪ iouɜ ũ onɡɜ aɨ iɛ2 ɔɨ ɑuɜ o̞ ei2 iou2 c kː y2 ɖ oe dˤ yɛɜ '''
						    '''əʊ S ɡʲ onɡ2 u" eiɜ ʈ ɯᵝ iou5 dZ r̝̊ i.2 tS s^ ʝ yə5 iɑɜ uə5 pf ɨu iɑ2 ou2 ər2 fʲ ai2 r̝ uəɜ ɳ əɨ '''
						    '''ua5 uɪ ɽ bː yu5 uo2 yɛ5 l̩ ɻ ərɜ ʂ i̪2 ouɜ uaɜ a. a.ː yæ5 dː r̩ ee ɪu ər5 i̪ ɜ æi u: i.ː t^ o1 ɪ^ '''
						    '''ai ueiɜ æː ɛɪ eə i. ɴ ie ua2 ɑ1 o4 tʃː o: ɑ: u1 N i̪1 au yæ2 u. qː yəɜ y: kʰ tʃʰ iʊ sx õ uo tʰ '''
						    '''uai5 bʰ u.ː uə2 ʊə d^ s̪ː yiɜ dʰ r. oe: i1 ɟː yu2 nʲʲ i̪4 uei2 tsʲ ɸ ĩ ɑ4 t̪ː eɑ u4 e: tsː ʈʰ ɡʰ '''
						    '''ɯɯ dʒʲ ʂʲ X ɵː uaiɜ tɕʲ ã t^ː ẽː yɛ2 cː i.1 ɛʊ dˤdˤ dʒː i4 ɡː yi ɕʲ ɟʰ pʰ dʑʲ yuɜ ua1 ua4 æiː ɐɐ '''
						    '''ui iou1 ʊː a1 iou4 cʰ iɛ1 yə2 ɖʰ ẽ ʒʲ ää ər4 iːː ɪː iɑ1 ər1 œː øi ɪuː cʰcʰ əː1 iː1 ũ kʰː o̞o̞ xʲ '''
						    '''ou1 iɛ4 e̞e̞ y1 dzː dʲʲ dʰː ɯᵝɯᵝ lː uo1 i.4 i: yɛ5ʲ a4'''
						).split(''' '''						)
						lowerCAmelCase__      :		str    							=      dict(zip(lowercase_  ,range(len(lowercase_						)						)						)						)

						lowerCAmelCase__      :		Dict    							=      {'''pad_token''': '''<pad>''', '''unk_token''': '''<unk>''', '''bos_token''': '''<s>''', '''eos_token''': '''</s>'''}

						lowerCAmelCase__      :		Union[str, Any]    							=      os.path.join(self.tmpdirname  ,VOCAB_FILES_NAMES['''vocab_file''']						)
						with open(self.vocab_file  ,'''w'''  ,encoding='''utf-8'''						) as fp:
							fp.write(json.dumps(lowercase_						) + '''\n'''						)







					def 			__lowerCAmelCase					(			self     :							Optional[int]  ,lowercase_     :							int  ,lowercase_     :							List[str]=False  ,lowercase_     :							Any=2_0  ,lowercase_     :							int=5						):
						lowerCAmelCase__      :		Union[str, Any]    							=      [(i, tokenizer.decode([i]  ,clean_up_tokenization_spaces=lowercase_						)) for i in range(len(lowercase_						)						)]
						lowerCAmelCase__      :		int    							=      list(filter(lambda lowercase_						: [t[0]] == tokenizer.encode(t[1]  ,do_phonemize=lowercase_						)  ,lowercase_						)						)
						if max_length is not None and len(lowercase_						) > max_length:
							lowerCAmelCase__      :		int    							=      toks[:max_length]
						if min_length is not None and len(lowercase_						) < min_length and len(lowercase_						) > 0:
							while len(lowercase_						) < min_length:
								lowerCAmelCase__      :		List[str]    							=      toks + toks
        # toks_str = [t[1] for t in toks]
						lowerCAmelCase__      :		List[Any]    							=      [t[0] for t in toks]

						# Ensure consistency
						lowerCAmelCase__      :		Dict    							=      tokenizer.decode(lowercase_  ,clean_up_tokenization_spaces=lowercase_						)
						if " " not in output_txt and len(lowercase_						) > 1:
							lowerCAmelCase__      :		Tuple    							=      (
							    tokenizer.decode([toks_ids[0]]  ,clean_up_tokenization_spaces=lowercase_						)
							    + ''' '''
							    + tokenizer.decode(toks_ids[1:]  ,clean_up_tokenization_spaces=lowercase_						)
							)
						if with_prefix_space:
							lowerCAmelCase__      :		List[Any]    							=      ''' ''' + output_txt
						lowerCAmelCase__      :		Tuple    							=      tokenizer.encode(lowercase_  ,add_special_tokens=lowercase_						)
						return output_txt, output_ids







					def 			__lowerCAmelCase					(			self     :							Any  ,**lowercase_     :							Union[str, Any]						):
						kwargs.update(self.special_tokens_map						)
						return WavaVecaPhonemeCTCTokenizer.from_pretrained(self.tmpdirname  ,**lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Optional[int]						):
						lowerCAmelCase__      :		int    							=      self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft'''						)

						# check adding a single token
						tokenizer.add_tokens('''xxx'''						)
						lowerCAmelCase__      :		Any    							=      tokenizer('''m xxx ɪ'''  ,do_phonemize=lowercase_						).input_ids
						self.assertEqual(lowercase_  ,[1_3, 3_9_2, 1_7]						)  # xxx should be last token

						tokenizer.add_tokens(['''aaa''', '''bbb''', '''ccc''']						)
						lowerCAmelCase__      :		Tuple    							=      tokenizer('''m aaa ɪ ccc'''  ,do_phonemize=lowercase_						).input_ids
						self.assertEqual(lowercase_  ,[1_3, 3_9_3, 1_7, 3_9_5]						)  # aaa and ccc should be after xxx and 2 after aaa

						lowerCAmelCase__      :		List[Any]    							=      tokenizer('''maɪ c'''  ,do_phonemize=lowercase_						).input_ids
						self.assertEqual(lowercase_  ,[3, 2_0_0]						)  # mai should be <unk> (=3)







					def 			__lowerCAmelCase					(			self     :							int						):
						lowerCAmelCase__      :		Any    							=      self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft'''						)

						lowerCAmelCase__      :		int    							=      '''Hello how are you'''
						lowerCAmelCase__      :		List[Any]    							=      tokenizer.phonemize(lowercase_  ,phonemizer_lang='''en-us'''						)
						self.assertEqual(lowercase_  ,'''h ə l oʊ h aʊ ɑːɹ j uː'''						)







					def 			__lowerCAmelCase					(			self     :							List[Any]						):
						lowerCAmelCase__      :		str    							=      self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft'''						)

						lowerCAmelCase__      :		List[Any]    							=      '''Hello how are you'''
						lowerCAmelCase__      :		str    							=      tokenizer.phonemize(lowercase_  ,phonemizer_lang='''en-us'''						)
						self.assertEqual(tokenizer(lowercase_						).input_ids  ,tokenizer(lowercase_  ,do_phonemize=lowercase_						).input_ids						)







					def 			__lowerCAmelCase					(			self     :							Any						):
						lowerCAmelCase__      :		str    							=      self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft'''						)
						lowerCAmelCase__      :		str    							=      '''Hello how are you'''
						lowerCAmelCase__      :		Any    							=      tokenizer.phonemize(lowercase_  ,phonemizer_lang='''en-us'''						)

						lowerCAmelCase__      :		List[Any]    							=      tokenizer.decode(tokenizer(lowercase_						).input_ids						)

						self.assertEqual(lowercase_  ,lowercase_						)







					def 			__lowerCAmelCase					(			self     :							List[Any]						):
						lowerCAmelCase__      :		Tuple    							=      self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft'''						)

						lowerCAmelCase__      :		int    							=      [
						    [1_1, 5, 1_5, tokenizer.pad_token_id, 1_5, 8, 9_8],
						    [2_4, 2_2, 5, 2_4, 2_2, 5, 7_7],
						]
						lowerCAmelCase__      :		List[str]    							=      tokenizer.decode(sample_ids[0]						)
						lowerCAmelCase__      :		List[str]    							=      tokenizer.batch_decode(lowercase_						)
						self.assertEqual(lowercase_  ,batch_tokens[0]						)
						self.assertEqual(lowercase_  ,['''k s ɾ ɾ l ɭʲ''', '''j ð s j ð s oːɹ''']						)







					def 			__lowerCAmelCase					(			self     :							str						):
						lowerCAmelCase__      :		int    							=      self.tokenizer_class.from_pretrained(
						    '''facebook/wav2vec2-lv-60-espeak-cv-ft'''  ,word_delimiter_token='''|'''						)
						tokenizer.add_tokens('''|'''						)

						lowerCAmelCase__      :		Optional[Any]    							=      '''Hello how are you'''
						lowerCAmelCase__      :		Union[str, Any]    							=      tokenizer.phonemize(lowercase_  ,phonemizer_lang='''en-us'''						)
						self.assertEqual(lowercase_  ,'''h ə l oʊ | h aʊ | ɑːɹ | j uː |'''						)







					def 			__lowerCAmelCase					(			self     :							Optional[int]						):
						lowerCAmelCase__      :		List[str]    							=      self.tokenizer_class.from_pretrained(
						    '''facebook/wav2vec2-lv-60-espeak-cv-ft'''  ,word_delimiter_token='''|'''						)
						tokenizer.add_tokens('''|'''						)

						lowerCAmelCase__      :		Dict    							=      '''Hello how are you'''
						lowerCAmelCase__      :		Union[str, Any]    							=      tokenizer.phonemize(lowercase_  ,phonemizer_lang='''en-us'''						)
						self.assertEqual(tokenizer(lowercase_						).input_ids  ,tokenizer(lowercase_  ,do_phonemize=lowercase_						).input_ids						)







					def 			__lowerCAmelCase					(			self     :							Optional[int]						):
						lowerCAmelCase__      :		Optional[int]    							=      self.tokenizer_class.from_pretrained(
						    '''facebook/wav2vec2-lv-60-espeak-cv-ft'''  ,word_delimiter_token='''|'''						)
						tokenizer.add_tokens('''|'''						)

						# fmt: off
						lowerCAmelCase__      :		Union[str, Any]    							=      [
						    [1_1, 5, 1_5, tokenizer.pad_token_id, tokenizer.word_delimiter_token_id, 1_5, 8, tokenizer.word_delimiter_token_id, 9_8],
						    [tokenizer.word_delimiter_token_id, 2_4, 2_2, tokenizer.word_delimiter_token_id, 5, 2_4, 2_2, 5, 7_7],
						]
						# fmt: on

						# decode with word_del_token filter
						lowerCAmelCase__      :		Any    							=      tokenizer.decode(sample_ids[0]						)
						lowerCAmelCase__      :		Optional[int]    							=      tokenizer.batch_decode(lowercase_						)
						self.assertEqual(lowercase_  ,batch_tokens[0]						)
						self.assertEqual(lowercase_  ,['''k s ɾ ɾ l ɭʲ''', '''j ð s j ð s oːɹ''']						)

						# decode with no word_del_token filter
						lowerCAmelCase__      :		Optional[Any]    							=      tokenizer.decode(sample_ids[0]  ,filter_word_delimiter_token=lowercase_						)
						lowerCAmelCase__      :		Any    							=      tokenizer.batch_decode(lowercase_  ,filter_word_delimiter_token=lowercase_						)
						self.assertEqual(lowercase_  ,batch_tokens[0]						)
						self.assertEqual(lowercase_  ,['''k s ɾ | ɾ l | ɭʲ''', '''| j ð | s j ð s oːɹ''']						)







					def 			__lowerCAmelCase					(			self     :							Optional[Any]						):
						lowerCAmelCase__      :		List[Any]    							=      self.tokenizer_class.from_pretrained(
						    '''facebook/wav2vec2-lv-60-espeak-cv-ft'''  ,word_delimiter_token='''|'''						)
						tokenizer.add_tokens('''|'''						)

						lowerCAmelCase__      :		Optional[int]    							=      '''Hello how are you'''
						lowerCAmelCase__      :		Dict    							=      tokenizer.phonemize(lowercase_  ,phonemizer_lang='''en-us'''						)

						lowerCAmelCase__      :		Tuple    							=      tokenizer.decode(tokenizer(lowercase_						).input_ids  ,filter_word_delimiter_token=lowercase_						)

						self.assertEqual(lowercase_  ,lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Union[str, Any]						):
						lowerCAmelCase__      :		str    							=      self.tokenizer_class.from_pretrained(
						    '''facebook/wav2vec2-lv-60-espeak-cv-ft'''  ,word_delimiter_token='''|'''						)
						tokenizer.add_tokens('''|'''						)

						lowerCAmelCase__      :		Optional[int]    							=      '''Hello how are you'''
						lowerCAmelCase__      :		List[Any]    							=      tokenizer.phonemize(lowercase_  ,phonemizer_lang='''en-us'''						)

						lowerCAmelCase__      :		int    							=      tokenizer.decode(tokenizer(lowercase_						).input_ids  ,filter_word_delimiter_token=lowercase_						)

						self.assertEqual(''' '''.join([p.strip() for p in phonemes.split(''' |'''						)]						).strip()  ,lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Optional[Any]						):
						lowerCAmelCase__      :		int    							=      self.tokenizer_class.from_pretrained(
						    '''facebook/wav2vec2-lv-60-espeak-cv-ft'''  ,word_delimiter_token=lowercase_						)
						lowerCAmelCase__      :		int    							=      '''Hello how are you'''

						lowerCAmelCase__      :		Union[str, Any]    							=      tokenizer(lowercase_  ,phonemizer_lang='''en-us'''						).input_ids
						lowerCAmelCase__      :		List[Any]    							=      tokenizer(lowercase_  ,phonemizer_lang='''fr-fr'''						).input_ids

						self.assertNotEqual(lowercase_  ,lowercase_						)

						lowerCAmelCase__      :		str    							=      tokenizer.decode(lowercase_						)
						lowerCAmelCase__      :		Optional[Any]    							=      tokenizer.decode(lowercase_						)

						self.assertEqual(lowercase_  ,'''h ə l oʊ h aʊ ɑːɹ j uː'''						)
						self.assertEqual(lowercase_  ,'''ɛ l o h aʊ a ʁ j u'''						)







					def 			__lowerCAmelCase					(			self     :							int						):
						lowerCAmelCase__      :		Dict    							=      self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft'''						)
						lowerCAmelCase__      :		List[str]    							=      '''Hello how Are you'''
						lowerCAmelCase__      :		Union[str, Any]    							=      '''hello how are you'''

						lowerCAmelCase__      :		List[Any]    							=      tokenizer(lowercase_						).input_ids
						lowerCAmelCase__      :		List[str]    							=      tokenizer(lowercase_						).input_ids

						self.assertEqual(lowercase_  ,lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Union[str, Any]						):
						lowerCAmelCase__      :		Any    							=      self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft'''						)
						tokenizer.add_tokens(['''!''', '''?''']						)
						tokenizer.add_special_tokens({'''cls_token''': '''$$$'''}						)

						# fmt: off
						lowerCAmelCase__      :		Dict    							=      [
						    [1_1, 5, 1_5, tokenizer.pad_token_id, 1_5, 8, 9_8, 3_9_2, 3_9_2, 3_9_3, 3_9_2, 3_9_2, 3_9_3, 3_9_4, 3_9_4],
						    [2_4, 2_2, 5, 2_4, 2_2, 5, 7_7, tokenizer.pad_token_id, 3_9_4, 3_9_4],
						]
						# fmt: on

						lowerCAmelCase__      :		Tuple    							=      tokenizer.batch_decode(lowercase_						)
						self.assertEqual(lowercase_  ,['''k s ɾ ɾ l ɭʲ!?!? $$$''', '''j ð s j ð s oːɹ $$$''']						)







					@staticmethod
					def 			__lowerCAmelCase					(			lowercase_     :							Optional[int]  ,lowercase_     :							Union[str, Any]						):
						lowerCAmelCase__      :		Union[str, Any]    							=      [d[key] for d in offsets]
						return retrieved_list







					def 			__lowerCAmelCase					(			self     :							str						):
						lowerCAmelCase__      :		List[str]    							=      self.get_tokenizer(word_delimiter_token='''|'''						)
						tokenizer.add_tokens('''|'''						)

						# fmt: off
						# ksssɾɾ|ɾɾ<pad>ɾɾ|<pad>ɾlll|ɭʲ -> k s ɾ ɾ | ɾ l | ɭʲ"
						lowerCAmelCase__      :		Optional[int]    							=      [1_1, 5, 5, 5, 1_5, 1_5, tokenizer.pad_token_id, 1_5, 1_5, tokenizer.word_delimiter_token_id, tokenizer.pad_token_id, 1_5, 8, 8, 8, tokenizer.word_delimiter_token_id, 9_8]
						# fmt: on

						lowerCAmelCase__      :		Union[str, Any]    							=      tokenizer.decode(lowercase_  ,output_char_offsets=lowercase_  ,filter_word_delimiter_token=lowercase_						)
						# check Wav2Vec2CTCTokenizerOutput keys for char
						self.assertEqual(len(outputs.keys()						)  ,2						)
						self.assertTrue('''text''' in outputs						)
						self.assertTrue('''char_offsets''' in outputs						)
						self.assertTrue(isinstance(lowercase_  ,lowercase_						)						)

						# check that order of chars is correct and identical for both outputs
						self.assertEqual(''' '''.join(self.get_from_offsets(outputs['''char_offsets''']  ,'''char'''						)						)  ,outputs.text						)
						self.assertListEqual(
						    self.get_from_offsets(outputs['''char_offsets''']  ,'''char'''						)  ,['''k''', '''s''', '''ɾ''', '''ɾ''', '''|''', '''ɾ''', '''l''', '''|''', '''ɭʲ''']						)

						# check that offsets are actually correct for char
						# 0-1 is 11, 1-4 is 5, 4-6 is first 15, 6-7 is <pad> (thus not shown), 7-9 is second 15, 9-10 is word_delimiter_token,
						# 10-11 is <pad> (thus not shown), 11-12 is third 15, 12-15 is 8, 15-16 is word_delimiter_token, 16-17 is 98
						self.assertListEqual(
						    self.get_from_offsets(outputs['''char_offsets''']  ,'''start_offset'''						)  ,[0, 1, 4, 7, 9, 1_1, 1_2, 1_5, 1_6]						)
						self.assertListEqual(
						    self.get_from_offsets(outputs['''char_offsets''']  ,'''end_offset'''						)  ,[1, 4, 6, 9, 1_0, 1_2, 1_5, 1_6, 1_7]						)







					def 			__lowerCAmelCase					(			self     :							Optional[Any]						):
						lowerCAmelCase__      :		List[str]    							=      self.get_tokenizer(word_delimiter_token='''|'''						)

						def check_list_tuples_equal(lowercase_     :							str  ,lowercase_     :							Any						):
							self.assertTrue(isinstance(lowercase_  ,lowercase_						)						)
							self.assertTrue(isinstance(outputs_list[0]  ,lowercase_						)						)

							# transform list to ModelOutput
							lowerCAmelCase__      :		int    							=      WavaVecaPhonemeCTCTokenizerOutput(
							    {k: [d[k] for d in outputs_list] for k in outputs_list[0]}						)

							self.assertListEqual(outputs_batch['''text''']  ,outputs_batch_a['''text''']						)

							def recursive_check(lowercase_     :							int  ,lowercase_     :							str						):
								if isinstance(lowercase_  ,lowercase_						):
									[recursive_check(lowercase_  ,lowercase_						) for la, la in zip(lowercase_  ,lowercase_						)]
								self.assertEqual(lowercase_  ,lowercase_						)

							if "char_offsets" in outputs_batch:
								recursive_check(outputs_batch['''char_offsets''']  ,outputs_batch_a['''char_offsets''']						)

        # fmt: off
						lowerCAmelCase__      :		int    							=      [
						    [1_1, 5, 1_5, tokenizer.pad_token_id, 1_5, 4, 8, 9_8, 3_2, 3_2, 3_2, 3_2, 4, 3_3, tokenizer.word_delimiter_token_id, 3_2, 3_2, 3_3, 3_4, 3_4],
						    [2_4, 2_2, 5, tokenizer.word_delimiter_token_id, tokenizer.word_delimiter_token_id, 2_4, 2_2, 2_2, 2_2, 4, 5, 7_7, tokenizer.pad_token_id, 2_2, 2_2, 4, 3_4, 3_4, 3_4, 3_4],
						]
						# fmt: on

						# We assume that `decode` works as expected. All we will check now is
						# the output type is correct and the output is identical to `decode`

						# char
						lowerCAmelCase__      :		int    							=      tokenizer.batch_decode(lowercase_  ,output_char_offsets=lowercase_						)
						lowerCAmelCase__      :		Optional[Any]    							=      [tokenizer.decode(lowercase_  ,output_char_offsets=lowercase_						) for ids in sample_ids]
						check_list_tuples_equal(lowercase_  ,lowercase_						)







					@unittest.skip('''Wav2Vec2PhonemeTokenizer always lower cases letters to correctly map to phonemes'''						)
					def 			__lowerCAmelCase					(			self     :							List[str]						):
						pass







					@unittest.skip('''Wav2Vec2PhonemeTokenizer always puts spaces between phonemes'''						)
					def 			__lowerCAmelCase					(			self     :							int						):
						pass







					@unittest.skip('''encodes to text to ids, but decodes ids to phonemes -> not possible to have internal consistency'''						)
					def 			__lowerCAmelCase					(			self     :							Dict						):
						pass







					@unittest.skip('''Wav2Vec2PhonemeModel has no max model length => no testing'''						)
					def 			__lowerCAmelCase					(			self     :							Optional[int]						):
						pass







					def 			__lowerCAmelCase					(			self     :							Union[str, Any]						):
						lowerCAmelCase__      :		List[Any]    							=      self.get_tokenizers(do_lower_case=lowercase_						)
						for tokenizer in tokenizers:
							with self.subTest(F'{tokenizer.__class__.__name__}'						):
								lowerCAmelCase__      :		str    							=      tokenizer.vocab_size
								lowerCAmelCase__      :		List[str]    							=      len(lowercase_						)

								self.assertNotEqual(lowercase_  ,0						)

								# We usually have added tokens from the start in tests because our vocab fixtures are
								# smaller than the original vocabs - let's not assert this
								# self.assertEqual(vocab_size, all_size)

								lowerCAmelCase__      :		Union[str, Any]    							=      ['''aaaaa bbbbbb''', '''cccccccccdddddddd''']
								lowerCAmelCase__      :		Optional[int]    							=      tokenizer.add_tokens(lowercase_						)
								lowerCAmelCase__      :		Optional[Any]    							=      tokenizer.vocab_size
								lowerCAmelCase__      :		Optional[Any]    							=      len(lowercase_						)

								self.assertNotEqual(lowercase_  ,0						)
								self.assertEqual(lowercase_  ,lowercase_						)
								self.assertEqual(lowercase_  ,len(lowercase_						)						)
								self.assertEqual(lowercase_  ,all_size + len(lowercase_						)						)

								lowerCAmelCase__      :		Tuple    							=      tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l'''  ,add_special_tokens=lowercase_						)

								self.assertGreaterEqual(len(lowercase_						)  ,4						)
								self.assertGreater(tokens[0]  ,tokenizer.vocab_size - 1						)
								self.assertGreater(tokens[-3]  ,tokenizer.vocab_size - 1						)

								lowerCAmelCase__      :		Dict    							=      {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''}
								lowerCAmelCase__      :		Any    							=      tokenizer.add_special_tokens(lowercase_						)
								lowerCAmelCase__      :		Union[str, Any]    							=      tokenizer.vocab_size
								lowerCAmelCase__      :		Tuple    							=      len(lowercase_						)

								self.assertNotEqual(lowercase_  ,0						)
								self.assertEqual(lowercase_  ,lowercase_						)
								self.assertEqual(lowercase_  ,len(lowercase_						)						)
								self.assertEqual(lowercase_  ,all_size_a + len(lowercase_						)						)

								lowerCAmelCase__      :		List[Any]    							=      tokenizer.encode(
								    '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l'''  ,add_special_tokens=lowercase_						)

								self.assertGreaterEqual(len(lowercase_						)  ,6						)
								self.assertGreater(tokens[0]  ,tokenizer.vocab_size - 1						)
								self.assertGreater(tokens[0]  ,tokens[1]						)
								self.assertGreater(tokens[-3]  ,tokenizer.vocab_size - 1						)
								self.assertGreater(tokens[-3]  ,tokens[-4]						)
								self.assertEqual(tokens[0]  ,tokenizer.eos_token_id						)
								self.assertEqual(tokens[-3]  ,tokenizer.pad_token_id						)







					@unittest.skip('''The tokenizer shouldn\'t be used to encode input IDs (except for labels), only to decode.'''						)
					def 			__lowerCAmelCase					(			self     :							int						):
						pass







					@unittest.skip('''The tokenizer shouldn\'t be used to encode input IDs (except for labels), only to decode.'''						)
					def 			__lowerCAmelCase					(			self     :							Tuple						):
						pass







					def 			__lowerCAmelCase					(			self     :							Dict						):
						# The default common tokenizer tests assumes that the output of `convert_tokens_to_string` is a string which
						# is not the case for Wav2Vec2PhonemeCTCTokenizer.
						lowerCAmelCase__      :		Any    							=      self.get_tokenizers(fast=lowercase_  ,do_lower_case=lowercase_						)
						for tokenizer in tokenizers:
							with self.subTest(F'{tokenizer.__class__.__name__}'						):
								lowerCAmelCase__      :		Tuple    							=      ['''ð''', '''ɪ''', '''s''', '''ɪ''', '''z''', '''ɐ''', '''t''', '''ɛ''', '''k''', '''s''', '''t''']
								lowerCAmelCase__      :		Optional[Any]    							=      tokenizer.convert_tokens_to_string(lowercase_						)

								self.assertIsInstance(output['''text''']  ,lowercase_						)







"""simple docstring"""





import inspect
import tempfile
import unittest

from huggingface_hub import hf_hub_download

from transformers import is_torch_available
from transformers.testing_utils import is_flaky, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


__UpperCamelCase    : Optional[Any]				 =						1e-4

if is_torch_available():
							import torch

							from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel
							from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder







@require_torch
class 							SCREAMING_SNAKE_CASE   :






					"""simple docstring"""



					def __init__(			self     :							str  ,lowercase_     :							Optional[Any]  ,lowercase_     :							Optional[Any]=1_6  ,lowercase_     :							int=1_3  ,lowercase_     :							Optional[int]=7  ,lowercase_     :							int=1_4  ,lowercase_     :							str=1_0  ,lowercase_     :							List[Any]=1_9  ,lowercase_     :							Any=5  ,lowercase_     :							Any=4  ,lowercase_     :							List[str]=True  ,lowercase_     :							Union[str, Any]=1_6  ,lowercase_     :							Tuple=2  ,lowercase_     :							str=4  ,lowercase_     :							Tuple=4  ,lowercase_     :							int="gelu"  ,lowercase_     :							Any=0.1  ,lowercase_     :							int=0.1  ,lowercase_     :							Optional[int]=[1, 2, 3, 4, 5]  ,lowercase_     :							List[Any]=2_5  ,lowercase_     :							Union[str, Any]=5  ,):
						lowerCAmelCase__      :		List[str]    							=      d_model
						lowerCAmelCase__      :		Optional[Any]    							=      parent
						lowerCAmelCase__      :		Dict    							=      batch_size
						lowerCAmelCase__      :		Any    							=      prediction_length
						lowerCAmelCase__      :		str    							=      context_length
						lowerCAmelCase__      :		int    							=      cardinality
						lowerCAmelCase__      :		Dict    							=      num_time_features
						lowerCAmelCase__      :		str    							=      lags_sequence
						lowerCAmelCase__      :		int    							=      embedding_dimension
						lowerCAmelCase__      :		Dict    							=      is_training
						lowerCAmelCase__      :		Optional[Any]    							=      hidden_size
						lowerCAmelCase__      :		Optional[int]    							=      num_hidden_layers
						lowerCAmelCase__      :		List[str]    							=      num_attention_heads
						lowerCAmelCase__      :		int    							=      intermediate_size
						lowerCAmelCase__      :		List[str]    							=      hidden_act
						lowerCAmelCase__      :		Dict    							=      hidden_dropout_prob
						lowerCAmelCase__      :		Optional[int]    							=      attention_probs_dropout_prob

						lowerCAmelCase__      :		Tuple    							=      context_length
						lowerCAmelCase__      :		Optional[Any]    							=      prediction_length + label_length
						lowerCAmelCase__      :		Union[str, Any]    							=      label_length

						lowerCAmelCase__      :		Optional[int]    							=      moving_average
						lowerCAmelCase__      :		Dict    							=      autocorrelation_factor







					def 			__lowerCAmelCase					(			self     :							Tuple						):
						return AutoformerConfig(
						    d_model=self.d_model  ,encoder_layers=self.num_hidden_layers  ,decoder_layers=self.num_hidden_layers  ,encoder_attention_heads=self.num_attention_heads  ,decoder_attention_heads=self.num_attention_heads  ,encoder_ffn_dim=self.intermediate_size  ,decoder_ffn_dim=self.intermediate_size  ,dropout=self.hidden_dropout_prob  ,attention_dropout=self.attention_probs_dropout_prob  ,prediction_length=self.prediction_length  ,context_length=self.context_length  ,label_length=self.label_length  ,lags_sequence=self.lags_sequence  ,num_time_features=self.num_time_features  ,num_static_categorical_features=1  ,cardinality=[self.cardinality]  ,embedding_dimension=[self.embedding_dimension]  ,moving_average=self.moving_average  ,)







					def 			__lowerCAmelCase					(			self     :							Union[str, Any]  ,lowercase_     :							str						):
						lowerCAmelCase__      :		str    							=      config.context_length + max(config.lags_sequence						)

						lowerCAmelCase__      :		Optional[int]    							=      ids_tensor([self.batch_size, 1]  ,config.cardinality[0]						)
						lowerCAmelCase__      :		int    							=      floats_tensor([self.batch_size, _past_length, config.num_time_features]						)
						lowerCAmelCase__      :		Any    							=      floats_tensor([self.batch_size, _past_length]						)
						lowerCAmelCase__      :		List[str]    							=      floats_tensor([self.batch_size, _past_length]						) > 0.5

						# decoder inputs
						lowerCAmelCase__      :		List[str]    							=      floats_tensor([self.batch_size, config.prediction_length, config.num_time_features]						)
						lowerCAmelCase__      :		Tuple    							=      floats_tensor([self.batch_size, config.prediction_length]						)

						lowerCAmelCase__      :		Optional[int]    							=      {
						    '''past_values''': past_values,
						    '''static_categorical_features''': static_categorical_features,
						    '''past_time_features''': past_time_features,
						    '''past_observed_mask''': past_observed_mask,
						    '''future_time_features''': future_time_features,
						    '''future_values''': future_values,
						}
						return inputs_dict







					def 			__lowerCAmelCase					(			self     :							Optional[Any]						):
						lowerCAmelCase__      :		Dict    							=      self.get_config()
						lowerCAmelCase__      :		Dict    							=      self.prepare_autoformer_inputs_dict(lowercase_						)
						return config, inputs_dict







					def 			__lowerCAmelCase					(			self     :							List[Any]						):
						lowerCAmelCase__							,lowerCAmelCase__      :		List[Any]    							=      self.prepare_config_and_inputs()
						return config, inputs_dict







					def 			__lowerCAmelCase					(			self     :							Dict  ,lowercase_     :							Optional[int]  ,lowercase_     :							Union[str, Any]						):
						lowerCAmelCase__      :		Any    							=      AutoformerModel(config=lowercase_						).to(lowercase_						).eval()
						lowerCAmelCase__      :		Tuple    							=      model(**lowercase_						)

						lowerCAmelCase__      :		Any    							=      outputs.encoder_last_hidden_state
						lowerCAmelCase__      :		str    							=      outputs.last_hidden_state

						with tempfile.TemporaryDirectory() as tmpdirname:
							lowerCAmelCase__      :		List[Any]    							=      model.get_encoder()
							encoder.save_pretrained(lowercase_						)
							lowerCAmelCase__      :		Union[str, Any]    							=      AutoformerEncoder.from_pretrained(lowercase_						).to(lowercase_						)

						lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__      :		str    							=      model.create_network_inputs(**lowercase_						)
						lowerCAmelCase__							,lowerCAmelCase__      :		Optional[int]    							=      model.decomposition_layer(transformer_inputs[:, : config.context_length, ...]						)

						lowerCAmelCase__      :		int    							=      torch.cat(
						    (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...])  ,dim=-1  ,)
						lowerCAmelCase__      :		Dict    							=      encoder(inputs_embeds=lowercase_						)[0]
						self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3						)

						lowerCAmelCase__      :		Optional[int]    							=      (
						    torch.mean(transformer_inputs[:, : config.context_length, ...]  ,dim=1						)
						    .unsqueeze(1						)
						    .repeat(1  ,config.prediction_length  ,1						)
						)
						lowerCAmelCase__      :		Optional[Any]    							=      torch.zeros(
						    [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]]  ,device=enc_input.device  ,)

						lowerCAmelCase__      :		List[Any]    							=      torch.cat(
						    (
						        torch.cat((seasonal_input[:, -config.label_length :, ...], zeros)  ,dim=1						),
						        feature[:, config.context_length - config.label_length :, ...],
						    )  ,dim=-1  ,)
						lowerCAmelCase__      :		Any    							=      torch.cat(
						    (
						        torch.cat((trend_input[:, -config.label_length :, ...], mean)  ,dim=1						),
						        feature[:, config.context_length - config.label_length :, ...],
						    )  ,dim=-1  ,)

						with tempfile.TemporaryDirectory() as tmpdirname:
							lowerCAmelCase__      :		Optional[int]    							=      model.get_decoder()
							decoder.save_pretrained(lowercase_						)
							lowerCAmelCase__      :		Tuple    							=      AutoformerDecoder.from_pretrained(lowercase_						).to(lowercase_						)

						lowerCAmelCase__      :		Union[str, Any]    							=      decoder(
						    trend=lowercase_  ,inputs_embeds=lowercase_  ,encoder_hidden_states=lowercase_  ,)[0]

						self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3						)







@require_torch
class 							SCREAMING_SNAKE_CASE   (						a_       ,				a_       ,				unittest.TestCase			):






					"""simple docstring"""



					lowercase__												=			(AutoformerModel, AutoformerForPrediction) if is_torch_available() else ()
					lowercase__												=			(AutoformerForPrediction,) if is_torch_available() else ()
					lowercase__												=			{"feature-extraction": AutoformerModel} if is_torch_available() else {}
					lowercase__												=			False
					lowercase__												=			False
					lowercase__												=			False
					lowercase__												=			False
					lowercase__												=			False
					lowercase__												=			False







					def 			__lowerCAmelCase					(			self     :							int						):
						lowerCAmelCase__      :		int    							=      AutoformerModelTester(self						)
						lowerCAmelCase__      :		Optional[int]    							=      ConfigTester(self  ,config_class=lowercase_  ,has_text_modality=lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Optional[Any]						):
						self.config_tester.run_common_tests()







					def 			__lowerCAmelCase					(			self     :							str						):
						lowerCAmelCase__							,lowerCAmelCase__      :		Union[str, Any]    							=      self.model_tester.prepare_config_and_inputs()
						for model_class in self.all_model_classes:
							lowerCAmelCase__      :		Optional[Any]    							=      model_class(lowercase_						)

							with tempfile.TemporaryDirectory() as tmpdirname:
								model.save_pretrained(lowercase_						)
								lowerCAmelCase__							,lowerCAmelCase__      :		List[Any]    							=      model_class.from_pretrained(lowercase_  ,output_loading_info=lowercase_						)
							self.assertEqual(info['''missing_keys''']  ,[]						)







					def 			__lowerCAmelCase					(			self     :							List[Any]						):
						lowerCAmelCase__      :		Tuple    							=      self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.check_encoder_decoder_model_standalone(*lowercase_						)







					@unittest.skip(reason='''Model has no tokens embeddings'''						)
					def 			__lowerCAmelCase					(			self     :							Optional[int]						):
						pass







					def 			__lowerCAmelCase					(			self     :							Optional[Any]						):
						lowerCAmelCase__      :		List[str]    							=      inspect.signature(getattr(lowercase_  ,'''forward'''						)						)
						# The main input is the name of the argument after `self`
						lowerCAmelCase__      :		Any    							=      list(model_signature.parameters.keys()						)[1]
						self.assertEqual(AutoformerModel.main_input_name  ,lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Union[str, Any]						):
						lowerCAmelCase__							,lowerCAmelCase__      :		Optional[Any]    							=      self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							lowerCAmelCase__      :		int    							=      model_class(lowercase_						)
							lowerCAmelCase__      :		Optional[Any]    							=      inspect.signature(model.forward						)
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							lowerCAmelCase__      :		int    							=      [*signature.parameters.keys()]

							lowerCAmelCase__      :		Optional[int]    							=      [
							    '''past_values''',
							    '''past_time_features''',
							    '''past_observed_mask''',
							    '''static_categorical_features''',
							    '''static_real_features''',
							    '''future_values''',
							    '''future_time_features''',
							]

							if model.__class__.__name__ in ["AutoformerForPrediction"]:
								expected_arg_names.append('''future_observed_mask'''						)

							expected_arg_names.extend(
							    [
							        '''decoder_attention_mask''',
							        '''head_mask''',
							        '''decoder_head_mask''',
							        '''cross_attn_head_mask''',
							        '''encoder_outputs''',
							        '''past_key_values''',
							        '''output_hidden_states''',
							        '''output_attentions''',
							        '''use_cache''',
							        '''return_dict''',
							    ]						)

							self.assertListEqual(arg_names[: len(lowercase_						)]  ,lowercase_						)







					def 			__lowerCAmelCase					(			self     :							List[Any]						):
						lowerCAmelCase__							,lowerCAmelCase__      :		str    							=      self.model_tester.prepare_config_and_inputs_for_common()
						lowerCAmelCase__      :		List[str]    							=      True

						lowerCAmelCase__      :		int    							=      getattr(self.model_tester  ,'''seq_length'''  ,lowercase_						)
						lowerCAmelCase__      :		Union[str, Any]    							=      getattr(self.model_tester  ,'''decoder_seq_length'''  ,lowercase_						)
						lowerCAmelCase__      :		Tuple    							=      getattr(self.model_tester  ,'''encoder_seq_length'''  ,lowercase_						)
						lowerCAmelCase__      :		List[Any]    							=      getattr(self.model_tester  ,'''d_model'''  ,lowercase_						)
						lowerCAmelCase__      :		Union[str, Any]    							=      getattr(self.model_tester  ,'''num_attention_heads'''  ,lowercase_						)
						lowerCAmelCase__      :		str    							=      d_model // num_attention_heads

						for model_class in self.all_model_classes:
							lowerCAmelCase__      :		List[str]    							=      True
							lowerCAmelCase__      :		Optional[int]    							=      False
							lowerCAmelCase__      :		Optional[Any]    							=      True
							lowerCAmelCase__      :		Any    							=      model_class(lowercase_						)
							model.to(lowercase_						)
							model.eval()
							with torch.no_grad():
								lowerCAmelCase__      :		str    							=      model(**self._prepare_for_class(lowercase_  ,lowercase_						)						)
							lowerCAmelCase__      :		Optional[Any]    							=      outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
							self.assertEqual(len(lowercase_						)  ,self.model_tester.num_hidden_layers						)

							# check that output_attentions also work using config
							del inputs_dict["output_attentions"]
							lowerCAmelCase__      :		List[str]    							=      True
							lowerCAmelCase__      :		Union[str, Any]    							=      model_class(lowercase_						)
							model.to(lowercase_						)
							model.eval()
							with torch.no_grad():
								lowerCAmelCase__      :		Dict    							=      model(**self._prepare_for_class(lowercase_  ,lowercase_						)						)
							lowerCAmelCase__      :		int    							=      outputs.encoder_attentions
							self.assertEqual(len(lowercase_						)  ,self.model_tester.num_hidden_layers						)

							self.assertListEqual(
							    list(attentions[0].shape[-3:]						)  ,[self.model_tester.num_attention_heads, encoder_seq_length, dim]  ,)
							lowerCAmelCase__      :		Tuple    							=      len(lowercase_						)

							lowerCAmelCase__      :		List[str]    							=      7

							if "last_hidden_state" in outputs:
								correct_outlen += 1

							if "trend" in outputs:
								correct_outlen += 1

							if "past_key_values" in outputs:
								correct_outlen += 1  # past_key_values have been returned

							if "loss" in outputs:
								correct_outlen += 1

							if "params" in outputs:
								correct_outlen += 1

							self.assertEqual(lowercase_  ,lowercase_						)

							# decoder attentions
							lowerCAmelCase__      :		str    							=      outputs.decoder_attentions
							self.assertIsInstance(lowercase_  ,(list, tuple)						)
							self.assertEqual(len(lowercase_						)  ,self.model_tester.num_hidden_layers						)
							self.assertListEqual(
							    list(decoder_attentions[0].shape[-3:]						)  ,[self.model_tester.num_attention_heads, decoder_seq_length, dim]  ,)

							# cross attentions
							lowerCAmelCase__      :		Any    							=      outputs.cross_attentions
							self.assertIsInstance(lowercase_  ,(list, tuple)						)
							self.assertEqual(len(lowercase_						)  ,self.model_tester.num_hidden_layers						)
							self.assertListEqual(
							    list(cross_attentions[0].shape[-3:]						)  ,[self.model_tester.num_attention_heads, decoder_seq_length, dim]  ,)

						# Check attention is always last and order is fine
						lowerCAmelCase__      :		str    							=      True
						lowerCAmelCase__      :		Tuple    							=      True
						lowerCAmelCase__      :		Optional[Any]    							=      model_class(lowercase_						)
						model.to(lowercase_						)
						model.eval()
						with torch.no_grad():
							lowerCAmelCase__      :		Optional[Any]    							=      model(**self._prepare_for_class(lowercase_  ,lowercase_						)						)

						self.assertEqual(out_len + 2  ,len(lowercase_						)						)

						lowerCAmelCase__      :		Optional[Any]    							=      outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions

						self.assertEqual(len(lowercase_						)  ,self.model_tester.num_hidden_layers						)
						self.assertListEqual(
						    list(self_attentions[0].shape[-3:]						)  ,[self.model_tester.num_attention_heads, encoder_seq_length, dim]  ,)







					@is_flaky()
					def 			__lowerCAmelCase					(			self     :							str						):
						super().test_retain_grad_hidden_states_attentions()

def     __SCREAMING_SNAKE_CASE    ( A_="train-batch.pt"					):
	lowerCAmelCase__      :		Any    							=      hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch'''		,	filename=A_		,	repo_type='''dataset'''					)
	lowerCAmelCase__      :		Union[str, Any]    							=      torch.load(A_		,	map_location=A_					)
	return batch







@require_torch
@slow
class 							SCREAMING_SNAKE_CASE   (						unittest.TestCase			):






					"""simple docstring"""



					def 			__lowerCAmelCase					(			self     :							int						):
						lowerCAmelCase__      :		List[Any]    							=      AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly'''						).to(lowercase_						)
						lowerCAmelCase__      :		int    							=      prepare_batch()

						with torch.no_grad():
							lowerCAmelCase__      :		Any    							=      model(
							    past_values=batch['''past_values''']  ,past_time_features=batch['''past_time_features''']  ,past_observed_mask=batch['''past_observed_mask''']  ,static_categorical_features=batch['''static_categorical_features''']  ,future_values=batch['''future_values''']  ,future_time_features=batch['''future_time_features''']  ,)[0]

						lowerCAmelCase__      :		Dict    							=      torch.Size(
						    (6_4, model.config.prediction_length + model.config.label_length, model.config.feature_size)						)
						self.assertEqual(output.shape  ,lowercase_						)

						lowerCAmelCase__      :		Optional[int]    							=      torch.tensor(
						    [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]]  ,device=lowercase_						)
						self.assertTrue(torch.allclose(output[0, :3, :3]  ,lowercase_  ,atol=lowercase_						)						)







					def 			__lowerCAmelCase					(			self     :							Dict						):
						lowerCAmelCase__      :		List[Any]    							=      AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly'''						).to(lowercase_						)
						lowerCAmelCase__      :		Optional[int]    							=      prepare_batch('''val-batch.pt'''						)
						with torch.no_grad():
							lowerCAmelCase__      :		str    							=      model(
							    past_values=batch['''past_values''']  ,past_time_features=batch['''past_time_features''']  ,past_observed_mask=batch['''past_observed_mask''']  ,static_categorical_features=batch['''static_categorical_features''']  ,).encoder_last_hidden_state
						lowerCAmelCase__      :		Any    							=      torch.Size((6_4, model.config.context_length, model.config.d_model)						)
						self.assertEqual(output.shape  ,lowercase_						)

						lowerCAmelCase__      :		Optional[int]    							=      torch.tensor(
						    [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]]  ,device=lowercase_						)
						self.assertTrue(torch.allclose(output[0, :3, :3]  ,lowercase_  ,atol=lowercase_						)						)







					def 			__lowerCAmelCase					(			self     :							List[str]						):
						lowerCAmelCase__      :		Union[str, Any]    							=      AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly'''						).to(lowercase_						)
						lowerCAmelCase__      :		Dict    							=      prepare_batch('''val-batch.pt'''						)
						with torch.no_grad():
							lowerCAmelCase__      :		int    							=      model.generate(
							    static_categorical_features=batch['''static_categorical_features''']  ,past_time_features=batch['''past_time_features''']  ,past_values=batch['''past_values''']  ,future_time_features=batch['''future_time_features''']  ,past_observed_mask=batch['''past_observed_mask''']  ,)
						lowerCAmelCase__      :		List[Any]    							=      torch.Size((6_4, model.config.num_parallel_samples, model.config.prediction_length)						)
						self.assertEqual(outputs.sequences.shape  ,lowercase_						)

						lowerCAmelCase__      :		Union[str, Any]    							=      torch.tensor([3130.6763, 4056.5293, 7053.0786]  ,device=lowercase_						)
						lowerCAmelCase__      :		Dict    							=      outputs.sequences.mean(dim=1						)
						self.assertTrue(torch.allclose(mean_prediction[0, -3:]  ,lowercase_  ,rtol=1E-1						)						)




